Team Ai
Datasetpublic

khaimaitien/leetcode_problem_solution

This dataset contains: problems and solutions in Leetcode, crawled from: https://github.com/AnasImloul/Leetcode-Solutions The format of data: title: title of the problem algo_input: the description of the problem solution_py: the solution in Python solution_js: the solution in Js solution_java: the solution in Java solution_c: the solution in C

sourceHugging Faceupdated 3y agoView on Hugging Face
2likes65downloads
evaluation.json1226 linesDownload Raw Back to root
1[2    {3        "title": "Maximum Absolute Sum of Any Subarray",4        "algo_input": "You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).\n\nReturn the maximum absolute sum of any (possibly empty) subarray of nums.\n\nNote that abs(x) is defined as follows:\n\n\n\tIf x is a negative integer, then abs(x) = -x.\n\tIf x is a non-negative integer, then abs(x) = x.\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,-3,2,3,-4]\nOutput: 5\nExplanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\n\n\nExample 2:\n\nInput: nums = [2,-5,1,-4,3,-2]\nOutput: 8\nExplanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\n",5        "solution_py": "class Solution:\n\tdef maxAbsoluteSum(self, A):\n\n\t\tma,mi,res = 0,0,0\n\t\tfor a in A:\n\t\t\tma = max(0,ma+a)\n\t\t\tmi = min(0,mi+a)\n\t\t\tres = max(res,ma,-mi)\n\t\treturn res",6        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxAbsoluteSum = function(nums) {\n    maxi = Number.MIN_VALUE , mini = Number.MAX_VALUE\n    cur_max = 0, cur_min = 0\n    for(let i=0; i<nums.length; i++){\n        cur_max = Math.max(cur_max+nums[i],nums[i])\n        cur_min = Math.min(cur_min+nums[i], nums[i])\n        maxi = Math.max(maxi,cur_max)\n        mini = Math.min(mini,cur_min)\n    }\n    return Math.max(maxi,-mini)\n};",7        "solution_java": "class Solution {\n    public int maxAbsoluteSum(int[] nums) {\n        int minSum = Integer.MAX_VALUE, maxSum = Integer.MIN_VALUE, currentMinSum = 0, currentMaxSum = 0;\n        for(int num: nums) {\n            currentMaxSum += num;\n            maxSum = Math.max(maxSum, currentMaxSum);\n            if (currentMaxSum < 0)\n                currentMaxSum = 0;\n\n            currentMinSum += num;\n            minSum = Math.min(minSum, currentMinSum);\n            if (currentMinSum > 0)\n                currentMinSum = 0;\n        }\n        return Math.max(maxSum, -minSum);\n    }\n}",8        "solution_c": "class Solution {\npublic:\n    int maxAbsoluteSum(vector<int>& nums) {\n        int mx1=0;\n        int sum=0;\n        for(int i=0;i<nums.size();i++){\n            sum+=nums[i];\n            if(sum<0)sum=0;\n            mx1=max(sum,mx1);\n        }\n        sum=0;\n        int mx2=0;\n        for(int i=0;i<nums.size();i++){\n            sum+=nums[i];\n            if(sum>=0)sum=0;\n            mx2=min(sum,mx2);\n        }\n        \n        return max(mx1,abs(mx2));\n    }\n};"9    },10    {11        "title": "Verifying an Alien Dictionary",12        "algo_input": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.\n\nGiven a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\nOutput: true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.\n\n\nExample 2:\n\nInput: words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\nOutput: false\nExplanation: As 'd' comes after 'l' in this language, then words[0] &gt; words[1], hence the sequence is unsorted.\n\n\nExample 3:\n\nInput: words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: false\nExplanation: The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" &gt; \"app\", because 'l' &gt; '∅', where '∅' is defined as the blank character which is less than any other character (More info).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 20\n\torder.length == 26\n\tAll characters in words[i] and order are English lowercase letters.\n\n",13        "solution_py": "class Solution:\n    def isAlienSorted(self, words: List[str], order: str) -> bool:\n        order_index = {key:index for index, key in enumerate(order)}\n\n        for i in range(len(words)-1):\n           w1,w2 = words[i] , words[i + 1]\n           for j in range(len(w1)):\n                if j == len(w2):\n                    return False\n                if w1[j] != w2[j]:\n                    if order_index.get(w2[j]) < order_index.get(w1[j]):\n                        return False\n                    break\n        return True",14        "solution_js": "/**\n * @param {string[]} words\n * @param {string} order\n * @return {boolean}\n */\nvar isAlienSorted = function(words, order) {\n    let map = {}\n    for(let i = 0; i < 26; i++){\n        map[order[i]] = i\n    }\n    for(let i = 0; i < words.length - 1; i++){\n        for(let j = 0; j < words[i].length; j++){\n            if(j === words[i+1].length) return false\n            if(words[i][j] !== words[i+1][j]){\n                if(map[words[i+1][j]] < map[words[i][j]]) return false\n                break\n            }\n        }\n    }\n    return true\n};",15        "solution_java": "class Solution {\n    public boolean isAlienSorted(String[] words, String order) {\n        int val=1;\n        int[] alp = new int[26];\n\n        for(int i=0;i<order.length();i++) {\n            alp[order.charAt(i)-'a']=val;\n            val++;\n        }\n        int flag=0; // if second string is shorter than first then this will be used to check if second is a subset of first starting from the beginning\n\n        for(int i=0;i<words.length-1;i++) {\n            flag=0;\n            for(int j=0; j<words[i].length() && j<words[i+1].length(); j++) {\n                if(words[i].charAt(j) == words[i+1].charAt(j)) {\n                    continue;\n                }\n                if(alp[words[i].charAt(j)-'a'] > alp[words[i+1].charAt(j)-'a']) {\n                    return false;\n                } else if(alp[words[i].charAt(j)-'a'] < alp[words[i+1].charAt(j)-'a']) {\n                    flag=1;\n                    break;\n                }\n            }\n            if(flag==0 && words[i].length()>words[i+1].length()) {\n                return false; // if second word is sub string of first word starting from the beginning, return false.\n            }\n        }\n\n        return true;\n    }\n}",16        "solution_c": "class Solution {\npublic:\n    bool isAlienSorted(vector<string>& words, string order)\n    {\n        unordered_map<char,char> m;\n        for(int i=0;i<26;i++)\n        {\n            m[order[i]]=i+'a';\n        }\n        for(auto &w:words)\n        {\n            for(auto &ch:w)\n            {\n                ch=m[ch];\n            }\n        }\n        return is_sorted(words.begin(),words.end());// check sorting\n\n    }\n};\n//if you like the solution plz upvote;"17    },18    {19        "title": "Minimum Time to Make Rope Colorful",20        "algo_input": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.\n\nAlice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.\n\nReturn the minimum time Bob needs to make the rope colorful.\n\n&nbsp;\nExample 1:\n\nInput: colors = \"abaac\", neededTime = [1,2,3,4,5]\nOutput: 3\nExplanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.\n\nExample 2:\n\nInput: colors = \"abc\", neededTime = [1,2,3]\nOutput: 0\nExplanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.\n\n\nExample 3:\n\nInput: colors = \"aabaa\", neededTime = [1,2,3,4,1]\nOutput: 2\nExplanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == colors.length == neededTime.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= neededTime[i] &lt;= 104\n\tcolors contains only lowercase English letters.\n\n",21        "solution_py": "class Solution:\n    def minCost(self, s: str, cost: List[int]) -> int:\n        ans = prev = 0 # index of previously retained letter \n        for i in range(1, len(s)): \n            if s[prev] != s[i]: prev = i\n            else: \n                ans += min(cost[prev], cost[i])\n                if cost[prev] < cost[i]: prev = i\n        return ans ",22        "solution_js": "var minCost = function(colors, neededTime) {\n    let stack = [], time = 0;\n    for (let i = 0; i < colors.length; i++) {\n        let skipPush = false;\n        while (stack.length && colors[i] === colors[stack[stack.length - 1]]) {\n            if (neededTime[i] >= neededTime[stack[stack.length - 1]]) {\n                time += neededTime[stack.pop()];\n            }\n            else if (neededTime[i] < neededTime[stack[stack.length - 1]]) {\n                time += neededTime[i];\n                skipPush = true;\n                break;\n            }\n        }\n        if (!skipPush) stack.push(i);\n    }\n    return time;\n};",23        "solution_java": "class Solution {\n    public int minCost(String colors, int[] neededTime) {\n        return minCost(colors, neededTime, 0, neededTime.length - 1);\n    }\n    \n    public int minCost(String colors, int[] neededTime, int start, int end) {\n        if (start == end) {\n            return 0;\n        }\n        \n        int mid = (start + end) / 2;\n        int lEnd = mid;\n        int rStart = mid + 1;\n        int t1 = minCost(colors, neededTime, start, lEnd);\n        int t2 = minCost(colors, neededTime, rStart, end);\n        \n        while (neededTime[lEnd] < 0 && lEnd >= start) {\n            --lEnd;\n        }\n        while (neededTime[rStart] < 0 && rStart <= end) {\n            ++rStart;\n        }\n        \n        if (colors.charAt(lEnd) != colors.charAt(rStart)) {\n            return t1 + t2;\n        }\n        \n        int removeTime = 0;\n        if (neededTime[lEnd] <= neededTime[rStart]) {\n            removeTime = neededTime[lEnd];\n            neededTime[lEnd] *= -1;\n        }\n        else {\n            removeTime = neededTime[rStart];\n            neededTime[rStart] *= -1;\n        }\n            \n        return t1 + t2 + removeTime;\n    }\n}",24        "solution_c": "class Solution {\npublic:\n    int minCost(string colors, vector<int>& neededTime) {\n        int time=0;\n        for(int i=0;i<colors.length()-1;i++){\n            if(colors[i]==colors[i+1]){\n                if(neededTime[i]>neededTime[i+1]){\n                    swap(neededTime[i],neededTime[i+1]);\n                }\n                time+=min(neededTime[i],neededTime[i+1]);\n            }\n        }return time;\n    }\n};"25    },26    {27        "title": "Construct Binary Tree from Preorder and Inorder Traversal",28        "algo_input": "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.\n\n&nbsp;\nExample 1:\n\nInput: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput: [3,9,20,null,null,15,7]\n\n\nExample 2:\n\nInput: preorder = [-1], inorder = [-1]\nOutput: [-1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= preorder.length &lt;= 3000\n\tinorder.length == preorder.length\n\t-3000 &lt;= preorder[i], inorder[i] &lt;= 3000\n\tpreorder and inorder consist of unique values.\n\tEach value of inorder also appears in preorder.\n\tpreorder is guaranteed to be the preorder traversal of the tree.\n\tinorder is guaranteed to be the inorder traversal of the tree.\n\n",29        "solution_py": "# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n    def buildTree(self, preorder, inorder):\n        \"\"\"\n        :type preorder: List[int]\n        :type inorder: List[int]\n        :rtype: TreeNode\n        \"\"\"\n        if not preorder or not inorder:\n            return None\n\n        root = TreeNode(preorder[0])\n        mid = inorder.index(preorder[0])\n        root.left = self.buildTree(preorder[1:mid+1], inorder[:mid])\n        root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])\n        return root",30        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {number[]} preorder\n * @param {number[]} inorder\n * @return {TreeNode}\n */\nvar buildTree = function(preorder, inorder) {\n    let idx = 0;\n    function create(inorderStart, inorderEnd) {\n        if (idx === preorder.length || inorderStart > inorderEnd) {\n            return null;\n        }\n        const root = new TreeNode(preorder[idx]);\n        const mid = inorder.indexOf(preorder[idx]);\n        idx++;\n        root.left = create(inorderStart, mid -1);\n        root.right = create(mid + 1, inorderEnd);\n        return root;\n    }\n\n    return create(0, inorder.length -1);\n};",31        "solution_java": "class Solution {\n    Map<Integer, Integer> inMap;\n    int curIndex = 0;\n    int[] preOrder;\n    public TreeNode buildTree(int[] preorder, int[] inorder) {\n        preOrder = preorder;\n        inMap = new HashMap<>();\n        for(int i=0; i<inorder.length; i++) {\n            inMap.put(inorder[i], i);\n        }\n        return dfs(0, preorder.length-1);\n    }\n    \n    public TreeNode dfs(int s, int e){\n        if(s > e) return null;\n        int curNode = preOrder[curIndex++];\n        TreeNode root  = new TreeNode(curNode);\n        int inRoot = inMap.get(curNode);\n        root.left = dfs(s, inRoot-1);\n        root.right = dfs(inRoot+1, e);\n        return root;\n    }\n}",32        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    typedef vector<int>::iterator vecIt;\n\n    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, TreeNode* retNode, vecIt startIt, vecIt endIt)\n    {\n        if (startIt >= endIt)\n            return (NULL);\n        vecIt rootIt;\n        vecIt midIt;\n        int rootVal;\n\n        rootIt = preorder.begin();\n        rootVal = *rootIt;\n        preorder.erase(rootIt);\n        retNode = new TreeNode(rootVal);\n        midIt = find(startIt, endIt, rootVal);\n        retNode->left = buildTree(preorder, inorder, retNode->left, startIt, midIt);\n        retNode->right = buildTree(preorder, inorder, retNode->right, midIt + 1, endIt);\n        return (retNode);\n    }\n    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n        TreeNode* retNode;\n\n        return (buildTree(preorder, inorder, retNode, inorder.begin(), inorder.end()));\n    }\n};"33    },34    {35        "title": "Best Time to Buy and Sell Stock IV",36        "algo_input": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.\n\nFind the maximum profit you can achieve. You may complete at most k transactions.\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n\n&nbsp;\nExample 1:\n\nInput: k = 2, prices = [2,4,1]\nOutput: 2\nExplanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n\n\nExample 2:\n\nInput: k = 2, prices = [3,2,6,5,0,3]\nOutput: 7\nExplanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= k &lt;= 100\n\t0 &lt;= prices.length &lt;= 1000\n\t0 &lt;= prices[i] &lt;= 1000\n\n",37        "solution_py": "class Solution:\n    def maxProfit(self, k: int, prices: List[int]) -> int:\n        buy = [-inf] * (k+1)\n        sell = [0] * (k+1)\n        for price in prices:\n            for i in range(1,k+1):\n                    buy[i] = max(buy[i],sell[i-1]-price)\n                    sell[i] = max(sell[i],buy[i]+price)\n        return sell[-1]",38        "solution_js": "var maxProfit = function(k, prices) {\n    const len = prices.length;\n    let dp = new Array(len).fill(0);\n    dp = dp.map(() => new Array(2).fill(0).map(() => new Array(k+1).fill(-1)));\n    const solve = (day = 0, cap = k, buy = 0) => {\n        if(day == len || cap == 0) return 0;\n\n        if(dp[day][buy][cap] != -1) return dp[day][buy][cap];\n\n        let take, notake;\n        notake = solve(day + 1, cap, buy);\n        if(buy == 0) {\n            take = solve(day + 1, cap, 1) - prices[day];\n        } else {\n            take = solve(day + 1, cap - 1, 0) + prices[day];\n        }\n        return dp[day][buy][cap] = Math.max(take, notake)\n    };\n    return solve();\n};",39        "solution_java": "class Solution {\n    public int maxProfit(int k, int[] prices) {\n        int transaction = k;\n        int N = prices.length;\n        int[][][]dp =new int[N][2][k+1];\n        for(int i=0;i<N;i++){\n            for(int j =0;j<2;j++){\n                for(int tran=0;tran<=k;tran++){\n                    dp[i][j][tran] = -1;\n                }\n            }\n        }//init dp\n        return profit(0,1,k,prices,dp);\n    }\n    int profit(int index, int buy, int transaction , int[]prices, int[][][]dp){\n        if(transaction == 0){\n            return 0;\n        }\n        if(index == prices.length){\n            return 0;\n        }\n        if(dp[index][buy][transaction] != -1){\n            return dp[index][buy][transaction];\n        }\n        int profit =0;\n        if(buy == 1){\n            profit = Math.max(-prices[index] + profit(index+1,0,transaction,prices,dp),\n                               0 + profit(index+1,1,transaction,prices,dp));\n        }else{\n            profit = Math.max(prices[index] + profit(index+1,1,transaction-1,prices,dp),\n                              0 + profit(index+1, 0, transaction,prices,dp));\n        }\n        dp[index][buy][transaction] = profit;\n        return dp[index][buy][transaction];\n    }\n}",40        "solution_c": "class Solution {\npublic:\n    int solve(int ind, int buy, int k, vector<int>& prices, vector<vector<vector<int>>>& dp){\n        if(k==0 || ind==prices.size()) return 0;\n        if(dp[ind][buy][k] != -1) return dp[ind][buy][k];\n        if(buy){\n            return dp[ind][buy][k] = max(-prices[ind]+solve(ind+1, 0, k, prices, dp), solve(ind+1, 1, k, prices, dp));\n        }\n        return dp[ind][buy][k] = max(prices[ind]+solve(ind+1, 1, k-1, prices, dp), solve(ind+1, 0, k, prices, dp));\n    }\n    int maxProfit(int k, vector<int>& prices) {\n        vector<vector<vector<int>>> dp(prices.size(), vector<vector<int>> (2, vector<int> (k+1, -1)));\n        return solve(0, 1, k, prices, dp);\n    }\n};"41    },42    {43        "title": "Get Watched Videos by Your Friends",44        "algo_input": "There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.\n\nLevel 1 of videos are all watched videos by your&nbsp;friends, level 2 of videos are all watched videos by the friends of your&nbsp;friends and so on. In general, the level k of videos are all&nbsp;watched videos by people&nbsp;with the shortest path exactly equal&nbsp;to&nbsp;k with you. Given your&nbsp;id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.&nbsp;\n\n&nbsp;\nExample 1:\n\n\n\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput: [\"B\",\"C\"] \nExplanation: \nYou have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -&gt; watchedVideos = [\"C\"]&nbsp;\nPerson with id = 2 -&gt; watchedVideos = [\"B\",\"C\"]&nbsp;\nThe frequencies of watchedVideos by your friends are:&nbsp;\nB -&gt; 1&nbsp;\nC -&gt; 2\n\n\nExample 2:\n\n\n\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput: [\"D\"]\nExplanation: \nYou have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).\n\n\n&nbsp;\nConstraints:\n\n\n\tn == watchedVideos.length ==&nbsp;friends.length\n\t2 &lt;= n&nbsp;&lt;= 100\n\t1 &lt;=&nbsp;watchedVideos[i].length &lt;= 100\n\t1 &lt;=&nbsp;watchedVideos[i][j].length &lt;= 8\n\t0 &lt;= friends[i].length &lt; n\n\t0 &lt;= friends[i][j]&nbsp;&lt; n\n\t0 &lt;= id &lt; n\n\t1 &lt;= level &lt; n\n\tif&nbsp;friends[i] contains j, then friends[j] contains i\n\n",45        "solution_py": "class Solution:\n\tdef watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n\t\tq=[id]\n\t\tvis=set([id])\n\t\tl=0\n\t\twhile l<level:\n\t\t\tnew_q=[]\n\t\t\tfor x in q:\n\t\t\t\tfor friend in friends[x]:\n\t\t\t\t\tif not friend in vis:\n\t\t\t\t\t\tvis.add(friend)\n\t\t\t\t\t\tnew_q.append(friend)\n\t\t\tq=new_q\n\t\t\tl+=1\n\t\ta=Counter()\n\t\tfor x in q:\n\t\t\tfor vids in watchedVideos[x]:\n\t\t\t\ta[vids]+=1\n\t\tA=sorted([[a[x],x] for x in a])\n\t\treturn [x[1] for x in A]",46        "solution_js": "/**\n * @param {string[][]} watchedVideos\n * @param {number[][]} friends\n * @param {number} id\n * @param {number} level\n * @return {string[]}\n */\nvar watchedVideosByFriends = function(watchedVideos, friends, id, level) {\n  const queue = [];\n  queue.push([id, 0]);\n  const seen = new Set();\n  const map = {};\n\n  while (queue.length > 0) {\n    const [id, _level] = queue.shift();\n    if (seen.has(id)) {\n      continue;\n    }\n    seen.add(id);\n    if (_level == level) {\n      for (const video of watchedVideos[id]) {\n        if (!map[video]) {\n          map[video] = 1\n        } else {\n          map[video] += 1;\n        }\n      }\n      continue;\n    }\n\n    for (const f of friends[id]) {\n      queue.push([f, _level + 1]);\n    }\n  }\n\n  return Object.keys(map).sort((a, b) => {\n    const diff = map[a] - map[b];\n    if (diff == 0) {\n      return a.localeCompare(b);\n    }\n    return diff;\n  })\n};",47        "solution_java": "class Solution {\n    public List<String> watchedVideosByFriends(List<List<String>> watchedVideos, int[][] friends, int id, int level) {\n        int n = friends.length;\n        boolean[] visited = new boolean[n];\n        List<List<Integer>> graph = new ArrayList<>();\n        for(int i=0;i<n;i++) graph.add(new ArrayList<>());\n        for(int i=0;i<n;i++){\n            for(int j=0;j<friends[i].length;j++){\n                graph.get(i).add(friends[i][j]);\n            }\n        }\n        // System.out.println(graph.get(0));\n        Queue<Integer> queue = new ArrayDeque<>();\n        queue.offer(id);\n        visited[id] = true;\n        Map<String,Integer> answer = new HashMap<>();\n        while(!queue.isEmpty() && level>0){\n            int size = queue.size();\n            for(int i=0;i<size;i++){\n                int vertex = queue.remove();\n                for(int child: graph.get(vertex)){\n                    if(!visited[child]){\n                        //   if(level == 1) System.out.println(watchedVideos.get(child));\n                        if(level == 1) {\n                            for(String a: watchedVideos.get(child)){\n                                answer.put(a,answer.getOrDefault(a,0)+1);\n                            }\n                        }\n                        visited[child] = true;\n                        queue.offer(child);\n                    }\n                }\n            }\n            level--;\n        }\n        Queue<String[]> sortedQueue = new PriorityQueue<>((a,b)->{\n            if(a[1].equals(b[1])) return a[0].compareTo(b[0]);\n            return Integer.parseInt(a[1])-Integer.parseInt(b[1]);\n        });\n        for(String key: answer.keySet()){\n            sortedQueue.offer(new String[]{key,Integer.toString(answer.get(key))});\n        }\n        List<String> finalAnswer = new ArrayList<>();\n        while(!sortedQueue.isEmpty()) finalAnswer.add(sortedQueue.remove()[0]);\n        return finalAnswer;\n    }\n}",48        "solution_c": "class Solution {\npublic:\n  vector<string> watchedVideosByFriends(vector<vector<string>>& watchedVideos, vector<vector<int>>& friends, int id, int level) {\n    vector<vector<int>>graph(watchedVideos.size());\n    \n    for(int i = 0;i != friends.size(); i++)\n      for(auto &f: friends[i])\n        graph[f].push_back(i), graph[i].push_back(f);\n    \n    int tmp_level = 0;\n    vector<int>vis(watchedVideos.size(),0);\n    vector<string>ans;\n    \n    queue<int>q;\n    q.push(id);\n    while(!q.empty()){\n      if(tmp_level++ == level){\n        unordered_map<string,int>mp;\n        while(!q.empty()){\n          int t = q.front(); q.pop();\n          if(vis[t])continue;\n          vis[t] = 1;\n          for(auto &v: watchedVideos[t]) mp[v]++;\n        }\n        set<pair<int,string>>st;  \n        for(auto &[s, n]: mp) st.insert({n,s});\n        for(auto &it: st) ans.push_back(it.second);\n      }\n                    \n      int n = q.size();\n      while(n--){\n        int t = q.front(); q.pop();\n        if(vis[t])continue;\n        vis[t] = 1;\n        \n        for(auto &x: graph[t])\n          if(!vis[x]) q.push(x);\n      }\n    }\n    \n    return ans;\n  }\n};"49    },50    {51        "title": "Snapshot Array",52        "algo_input": "Implement a SnapshotArray that supports the following interface:\n\n\n\tSnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.\n\tvoid set(index, val) sets the element at the given index to be equal to val.\n\tint snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.\n\tint get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id\n\n\n&nbsp;\nExample 1:\n\nInput: [\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n[[3],[0,5],[],[0,6],[0,0]]\nOutput: [null,null,0,null,5]\nExplanation: \nSnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\nsnapshotArr.set(0,5);  // Set array[0] = 5\nsnapshotArr.snap();  // Take a snapshot, return snap_id = 0\nsnapshotArr.set(0,6);\nsnapshotArr.get(0,0);  // Get the value of array[0] with snap_id = 0, return 5\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= length &lt;= 5 * 104\n\t0 &lt;= index &lt; length\n\t0 &lt;= val &lt;= 109\n\t0 &lt;= snap_id &lt; (the total number of times we call snap())\n\tAt most 5 * 104 calls will be made to set, snap, and get.\n\n",53        "solution_py": "class SnapshotArray:\n\n    def __init__(self, length: int):\n        self.snap_id = 0\n        self.history = defaultdict(dict)\n\n    def set(self, index: int, val: int) -> None:\n        self.history[self.snap_id][index] = val\n\n    def snap(self) -> int:\n        self.snap_id += 1\n        return self.snap_id-1\n\n    def get(self, index: int, snap_id: int) -> int:\n        for i in range(snap_id,-1,-1):\n            if index in self.history[i]:\n                return self.history[i][index]\n        return 0 # default value in case it wasn't set earlier",54        "solution_js": "var SnapshotArray = function(length) {\n    this.snaps = []\n    this.currentIndex = 0\n    this.currentSnaps = []\n}\n\nSnapshotArray.prototype.set = function(index, val) {\n    this.currentSnaps[index] = val\n}\n\nSnapshotArray.prototype.snap = function() {\n    this.snaps[this.currentIndex] = [...this.currentSnaps]\n    \n    return this.currentIndex++\n}\n\nSnapshotArray.prototype.get = function(index, snap_id) {\n    const res = this.snaps[snap_id]\n    \n    if (res[index] === undefined) return 0\n    \n    return res[index]\n}",55        "solution_java": "class SnapshotArray {\n\n    TreeMap<Integer,Integer>[] snapshotArray;\n    int currSnapId;\n\n    public SnapshotArray(int length) {\n        snapshotArray = new TreeMap[length];\n        for(int i=0;i<length;i++)\n        {\n            snapshotArray[i] = new TreeMap();\n        }\n        currSnapId =0;\n    }\n\n    public void set(int index, int val) {\n        snapshotArray[index].put(currSnapId,val);\n    }\n\n    public int snap() {\n        return currSnapId++;\n    }\n\n    public int get(int index, int snap_id) {\n        Integer lowerKey = snapshotArray[index].floorKey(snap_id);\n\n        if(lowerKey !=null)\n        {\n            return snapshotArray[index].get(lowerKey);\n        }\n        return 0;\n    }\n}\n\n/**\n * Your SnapshotArray object will be instantiated and called as such:\n * SnapshotArray obj = new SnapshotArray(length);\n * obj.set(index,val);\n * int param_2 = obj.snap();\n * int param_3 = obj.get(index,snap_id);\n */",56        "solution_c": "class SnapshotArray {\n    int timestamp;\n    unordered_map<int, vector<int>> toSnaps, toValues;\npublic:\n    SnapshotArray(int length) {\n        timestamp = 0;\n    }\n\n    void set(int index, int val) {\n        if (toSnaps.count(index) == 0) {\n            // After lower_bound, prevent returning negative lo\n            toSnaps[index].push_back(-1);\n            // 0 means not found\n            toValues[index].push_back(0);\n        }\n        // same timestamp -> just update value\n        if (toSnaps[index].back() == timestamp) {\n            toValues[index].back() = val;\n        }\n        // not -> add timestamp and value\n        else {\n            toSnaps[index].push_back(timestamp);\n            toValues[index].push_back(val);\n        }\n    }\n\n    int snap() {\n        return timestamp++;\n    }\n\n    int get(int index, int snap_id) {\n        // check whether index exists or not\n        if (toSnaps.count(index) == 0) return 0;\n        auto& snaps = toSnaps[index];\n        int lo = 0, hi = snaps.size()-1;\n        while (lo < hi) {\n            int m = lo + (hi - lo)/2;\n            if (snaps[m] >= snap_id) hi = m;\n            else lo = m + 1;\n        }\n        // lower bound can be larger than target\n        if (snaps[lo] > snap_id) lo--;\n        // if lo is negative, then ther is no value of index at lo time\n        //if (lo < 0) return 0;\n        return toValues[index][lo];\n    }\n};\n\n/**\n * Your SnapshotArray object will be instantiated and called as such:\n * SnapshotArray* obj = new SnapshotArray(length);\n * obj->set(index,val);\n * int param_2 = obj->snap();\n * int param_3 = obj->get(index,snap_id);\n */"57    },58    {59        "title": "1-bit and 2-bit Characters",60        "algo_input": "We have two special characters:\n\n\n\tThe first character can be represented by one bit 0.\n\tThe second character can be represented by two bits (10 or 11).\n\n\nGiven a binary array bits that ends with 0, return true if the last character must be a one-bit character.\n\n&nbsp;\nExample 1:\n\nInput: bits = [1,0,0]\nOutput: true\nExplanation: The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.\n\n\nExample 2:\n\nInput: bits = [1,1,1,0]\nOutput: false\nExplanation: The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= bits.length &lt;= 1000\n\tbits[i] is either 0 or 1.\n\n",61        "solution_py": "# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282638543/\n# (Time, Space) Complexity : O(n), O(1)\n\nclass Solution:\n    def isOneBitCharacter(self, bits: List[int]) -> bool:\n        \"\"\"\n        :type bits: List[int]\n        :rtype: bool\n        \"\"\"\n        # Important Rules:\n        # 1. If bit n is 0, bit n+1 must be a new char\n        # 2. If bits end with 1, last bit must be a two bit char\n        #    However, this case had been rejected by question\n        # 3. If 1s in row and end with 0, \n        #    we can use count or 1s to check last char\n        #    If count is even, last char is \"0\"\n        #    If count is odd,  last char is \"10\"\n        # Strategy:\n        # 1. We don't care last element, since it must be 0.\n        # 2. We check from reversed, and count 1s in a row\n        # 3. Once 0 occur or list end, We stop counting\n        # 4. We use count to determin result\n        # 5. Since we will mod count by 2, we simplify it to bool\n        ret = True\n        for bit in bits[-2::-1]:\n            if bit: ret = not ret\n            else: break\n        return ret",62        "solution_js": "/**\n * @param {number[]} bits\n * @return {boolean}\n */\nvar isOneBitCharacter = function(bits) {\n  let i = 0;\n  while (i < bits.length - 1) {\n    if (bits[i] === 1) i++;\n    i++;\n  }\n  return bits[i] === 0;\n};",63        "solution_java": "class Solution {\n    public boolean isOneBitCharacter(int[] bits) {\n        int ones = 0;\n        //Starting from one but last, as last one is always 0.\n        for (int i = bits.length - 2; i >= 0 && bits[i] != 0 ; i--) { \n            ones++;\n        }\n        if (ones % 2 > 0) return false; \n        return true;\n    }\n}",64        "solution_c": "class Solution {\npublic:\n    bool isOneBitCharacter(vector<int>& bits) \n    {\n        int n = bits.size();\n        if(n == 1)\n            return true;\n       \n        int i = 0;\n        while(i <= n - 2)\n        {\n            if(bits[i] == 0)\n                i++;\n            else \n                i = i + 2;\n        }\n        if(i <= n-1)\n            return true;\n        else \n            return false;\n        \n    }\n};"65    },66    {67        "title": "Remove Duplicates from Sorted Array",68        "algo_input": "Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.\n\nSince it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums&nbsp;should hold the final result. It does not matter what you leave beyond the first&nbsp;k&nbsp;elements.\n\nReturn k after placing the final result in the first k slots of nums.\n\nDo not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n\nCustom Judge:\n\nThe judge will test your solution with the following code:\n\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n\n\nIf all assertions pass, then your solution will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,1,2]\nOutput: 2, nums = [1,2,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\nExample 2:\n\nInput: nums = [0,0,1,1,1,2,2,3,3,4]\nOutput: 5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 3 * 104\n\t-100 &lt;= nums[i] &lt;= 100\n\tnums is sorted in non-decreasing order.\n\n",69        "solution_py": "class Solution:\n    def removeDuplicates(self, nums: List[int]) -> int:\n        i = 1\n        for index in range(1, len(nums)):\n            if(nums[index] != nums[index-1]):\n                nums[i] = nums[index]\n                i += 1\n        return i",70        "solution_js": "var removeDuplicates = function(nums) {\n    for (i = 0; i < nums.length; i++) {\n        //Next number is identical to current one\n        if (nums[i] == nums[i+1]) {\n            nums.splice(i, 1);\n            i--;\n        }\n    }\n};",71        "solution_java": "class Solution {\n    public int removeDuplicates(int[] arr) {\n        int i=0;\n        for(int j=1;j<arr.length;j++){\n            if(arr[i]!=arr[j]){\n                i++;\n                arr[i]=arr[j];\n            }\n        }\n        return i+1;\n        \n    }\n}",72        "solution_c": "class Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        int ans=0;\n        for(int i=1;i<nums.size();i++){\n            if(nums[i]!=nums[ans]){\n                ans++;\n                nums[ans]=nums[i];\n            }\n        }\n        return ans+1;\n    }\n};"73    },74    {75        "title": "132 Pattern",76        "algo_input": "Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i &lt; j &lt; k and nums[i] &lt; nums[k] &lt; nums[j].\n\nReturn true if there is a 132 pattern in nums, otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4]\nOutput: false\nExplanation: There is no 132 pattern in the sequence.\n\n\nExample 2:\n\nInput: nums = [3,1,4,2]\nOutput: true\nExplanation: There is a 132 pattern in the sequence: [1, 4, 2].\n\n\nExample 3:\n\nInput: nums = [-1,3,2,0]\nOutput: true\nExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 2 * 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",77        "solution_py": "class Solution(object):\n    def find132pattern(self, nums):\n        # Base Condition...\n        if len(nums) < 3:\n            return False\n        m = float('-inf')\n        # Initialise a empty stack...\n        stack = []\n        # Run a Loop from last to first index...\n        for i in range(len(nums)-1, -1, -1):\n            # If m is greater than nums[i], return true...\n            if nums[i] < m:\n                return True\n            # If stack is not empty &  nums[i] is greater than the top element of stack, then pop the element...\n            else:\n                while stack and stack[-1] < nums[i]:\n                    m = stack.pop()\n            # Otherwise, append nums[i] into stack...\n            stack.append(nums[i])\n        # If the condition is not satisfied, return false.\n        return False",78        "solution_js": "var find132pattern = function(nums) {\n    let m = -Infinity\n    // Initialise a empty stack...\n    const stack = []\n    // Run a Loop from last to first index...\n    for (let i = nums.length - 1; i >= 0; i--) {\n        // If nums[i] is greater than the top element of stack, then pop the element...\n        while (nums[i] > stack[stack.length - 1]) {\n            m = stack.pop()\n        }\n        // If m is greater than nums[i], return true...\n        if (nums[i] < m) {\n            return true\n        }\n        // Otherwise, push nums[i] into stack...\n        stack.push(nums[i])\n    }\n    // If the condition is not satisfied, return false.\n    return false\n};",79        "solution_java": "class Solution {\n    public boolean find132pattern(int[] nums) {\n        int min = Integer.MIN_VALUE;\n        int peak = nums.length;\n        for (int i = nums.length - 1; i >= 0; i--) {\n            // We find a \"132\" pattern if nums[i] < min, so return true...\n            if (nums[i] < min)\n                return true;\n            // If peak < nums.length & nums[i] is greater than the peak element...\n            while (peak < nums.length && nums[i] > nums[peak])\n                min = nums[peak++];\n            // Now we have nums[i] <= nums[peak]\n            // We push nums[i] to the \"stack\"\n            peak--;\n            nums[peak] = nums[i];\n        }\n        return false;\n    }\n}",80        "solution_c": "class Solution {\npublic:\n    bool find132pattern(vector<int>& nums) {\n        // Initialise a empty stack \"s\"...\n        stack<int> s;\n        // To keep track of minimum element...\n        int min = INT_MIN;\n        // Run a Loop from last to first index...\n        for (int i = nums.size() - 1; i >= 0; i--) {\n            // If min is greater than nums[i], return true...\n            if (nums[i] < min)\n                return true;\n            // If stack is not empty &  nums[i] is greater than the top element of stack, then pop the element...\n            while (!s.empty() && nums[i] > s.top()) {\n                min = s.top();\n                s.pop();\n            }\n            // Otherwise, push nums[i] into stack...\n            s.push(nums[i]);\n        }\n        // If the condition is not satisfied, return false.\n        return false;\n    }\n};"81    },82    {83        "title": "Reveal Cards In Increasing Order",84        "algo_input": "You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].\n\nYou can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.\n\nYou will do the following steps repeatedly until all cards are revealed:\n\n\n\tTake the top card of the deck, reveal it, and take it out of the deck.\n\tIf there are still cards in the deck then put the next top card of the deck at the bottom of the deck.\n\tIf there are still unrevealed cards, go back to step 1. Otherwise, stop.\n\n\nReturn an ordering of the deck that would reveal the cards in increasing order.\n\nNote that the first entry in the answer is considered to be the top of the deck.\n\n&nbsp;\nExample 1:\n\nInput: deck = [17,13,11,2,3,5,7]\nOutput: [2,13,3,11,5,17,7]\nExplanation: \nWe get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom.  The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom.  The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom.  The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom.  The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom.  The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom.  The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.\n\n\nExample 2:\n\nInput: deck = [1,1000]\nOutput: [1,1000]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= deck.length &lt;= 1000\n\t1 &lt;= deck[i] &lt;= 106\n\tAll the values of deck are unique.\n\n",85        "solution_py": "class Solution:\n    def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n        def reveal(n):\n            lst = list(range(n))\n            ans = []\n            i = 0\n            while lst:\n                if not i&1: ans.append(lst.pop(0))\n                else: lst.append(lst.pop(0))\n                i += 1\n            return ans\n        ans = reveal(len(deck))\n        ans = sorted([v, i] for i, v in enumerate(ans))\n        deck.sort()\n        return (deck[j] for i,j in ans)",86        "solution_js": "/**\n * @param {number[]} deck\n * @return {number[]}\n */\nvar deckRevealedIncreasing = function(deck) {\n    // simulate the stack with the last revealed card at the top of the stack (index = 0)\n    // => sort the deck in descending order\n    let stack = deck.sort((a, b) => b - a)\n    let queue = [stack.shift()]\n        \n    while (stack.length > 0) {\n        // reverse the operation by shifting the last card of the queue to the start of the queue\n        queue.unshift(queue.pop())\n        // put the top card of the stack on the start of the queue\n        queue.unshift(stack.shift())\n    }\n    \n    return queue\n    \n};",87        "solution_java": "class Solution {\n    public int[] deckRevealedIncreasing(int[] deck) { // deck=[ 17,13,11,2,3,5,7 ]\n        Queue<Integer> ql = new LinkedList<Integer>();\n        for(int i=0;i<deck.length;i++)\n            ql.add(i);\n            // now the queue is [ 0, 1, 2, 3, 4, 5, 6 ]\n\n        int[] ans = new int[deck.length];\n        int k=0;\n                                     //index : 0 1 2 3 4 5 6\n        Arrays.sort(deck); //deck=[ 2 ,3 ,5, 7, 13, 11, 17 ]\n\n        while(!ql.isEmpty())\n        {\n            ans[ql.peek()]=deck[k];\n            ql.poll();\n            k++;\n            if(!ql.isEmpty())\n            {\n                ql.add(ql.peek());\n                ql.poll();\n            }\n        }\n        /*\n        ql=[0,1,2,3,4,5,6]\n        k=0;\n        ql=[2,3,4,5,6,1]\n        ans=[2,0,0,0,0,0,0] ans[0]=deck[0]\n        k=1;\n        ql=[4,5,6,1,3]\n        ans=[2,13,0,0,0,0,0] ans[2]=deck[1]\n        k=2;\n        ql=[6,1,3,5]\n        ans=[2,13,3,0,0,0,0] ans[4]=deck[2]\n        k=3;\n        ql=[3,5,1]\n        ans=[2,13,3,11,0,0,0] ans[6]=deck[3]\n        k=4;\n        ql=[1,5]\n        ans=[2,13,3,11,5,0,0] ans[3]=deck[4]\n        k=5;\n        ql=[5]\n        ans=[2,13,3,11,5,17,0] ans[1]=deck[5]\n        k=6;\n        ql=[]\n        ans=[2,13,3,11,5,17,7] ans[5]=deck[6]\n        */\n\n      return ans;\n    }\n}",88        "solution_c": "class Solution {\npublic:\n    vector<int> deckRevealedIncreasing(vector<int>& deck) {\n        int n = deck.size(), idx = 0, idx1 = 0;\n        vector<int> res(n, -1);\n        sort(deck.begin(), deck.end());\n        bool found = 1;\n        while(idx < n) {\n            if(res[idx1] == -1 and found) {\n                res[idx1] = deck[idx]; found = 0; idx++;\n            }\n            else if(res[idx1] == -1) found = 1;\n            idx1 = (idx1 +1)%n;\n        }\n        return res;\n    }\n};"89    },90    {91        "title": "Slowest Key",92        "algo_input": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.\n\nYou are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0,&nbsp;and every subsequent key was pressed at the exact time the previous key was released.\n\nThe tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].\n\nNote that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.\n\nReturn the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.\n\n&nbsp;\nExample 1:\n\nInput: releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\nOutput: \"c\"\nExplanation: The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.\n\n\nExample 2:\n\nInput: releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\nOutput: \"a\"\nExplanation: The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.\n\n&nbsp;\nConstraints:\n\n\n\treleaseTimes.length == n\n\tkeysPressed.length == n\n\t2 &lt;= n &lt;= 1000\n\t1 &lt;= releaseTimes[i] &lt;= 109\n\treleaseTimes[i] &lt; releaseTimes[i+1]\n\tkeysPressed contains only lowercase English letters.\n\n",93        "solution_py": "class Solution:\n    def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n        max_dur = releaseTimes[0]\n        max_key = keysPressed[0]\n\n        for i in range(1, len(releaseTimes)):\n            if releaseTimes[i] - releaseTimes[i-1] > max_dur:\n                max_dur = releaseTimes[i] - releaseTimes[i-1]\n                max_key = keysPressed[i]\n            elif releaseTimes[i] - releaseTimes[i-1] == max_dur and max_key < keysPressed[i]:\n                 max_key = keysPressed[i]\n\n        return max_key",94        "solution_js": "var slowestKey = function(releaseTimes, keysPressed) {\nlet maxDuration = releaseTimes[0], char=keysPressed[0];\nfor (let i = 1; i < releaseTimes.length; i++) {\n    if (releaseTimes[i]-releaseTimes[i-1]==maxDuration && keysPressed[i]>char) char=keysPressed[i]\n    else if (releaseTimes[i]-releaseTimes[i-1]>maxDuration) {\n        char=keysPressed[i];\n        maxDuration=releaseTimes[i]-releaseTimes[i-1];\n    }\n}\nreturn char;    \n};",95        "solution_java": "class Solution {\n    public char slowestKey(int[] releaseTimes, String keysPressed) {\n        int max = releaseTimes[0];\n        char ch = keysPressed.charAt(0);\n        for(int i=1;i<releaseTimes.length;i++){\n            int diff = releaseTimes[i]-releaseTimes[i-1];\n            if( diff >= max){\n                if(diff>max)\n                    ch = keysPressed.charAt(i);\n                else if(diff== max)\n                    ch = (char)Math.max((int) ch, (int) keysPressed.charAt(i));\n                max = diff;\n            }   \n        }\n        return ch;      \n    }    \n}",96        "solution_c": "class Solution {\npublic:\n    char slowestKey(vector<int>& releaseTimes, string keysPressed) {\n        int time = releaseTimes[0], new_time = 0;\n        char key = keysPressed[0];\n        \n        for (int i = 1; i < releaseTimes.size(); i++) {\n            new_time = releaseTimes[i] - releaseTimes[i-1];\n            \n            if (new_time == time) \n                key = keysPressed[i] > key ? keysPressed[i] : key;\n            \n            else if (new_time > time) {\n                time = new_time;\n                key = keysPressed[i];\n            }\n        }\n        return key;\n    }\n};"97    },98    {99        "title": "Partition Array Into Two Arrays to Minimize Sum Difference",100        "algo_input": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.\n\nReturn the minimum possible absolute difference.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,9,7,3]\nOutput: 2\nExplanation: One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.\n\n\nExample 2:\n\nInput: nums = [-36,36]\nOutput: 72\nExplanation: One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.\n\n\nExample 3:\n\nInput: nums = [2,-1,0,4,-2,-9]\nOutput: 0\nExplanation: One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 15\n\tnums.length == 2 * n\n\t-107 &lt;= nums[i] &lt;= 107\n\n",101        "solution_py": "class Solution:\n    def minimumDifference(self, nums: List[int]) -> int:\n        n = len(nums)//2\n        left, right = nums[:n], nums[n:]\n        lsum, rsum = sum(left), sum(right)\n        \n        ans = inf\n        for i in range(n+1): \n            vals = sorted(2*sum(combo)-lsum for combo in combinations(left, i))\n            for combo in combinations(right, n-i): \n                diff = 2*sum(combo) - rsum\n                k = bisect_left(vals, -diff)\n                if k: ans = min(ans, abs(vals[k-1] + diff))\n                if k < len(vals): ans = min(ans, abs(vals[k] + diff))\n        return ans ",102        "solution_js": "var minimumDifference = function(nums) {\n    let mid = Math.floor(nums.length / 2);\n    let firstHalf = nums.slice(0, mid), secondHalf = nums.slice(mid);\n    let firstHalfSum = firstHalf.reduce((a, c) => a + c);\n    let secondHalfSum = secondHalf.reduce((a, c) => a + c);\n    \n    // Find all combinations of sums of subsets made up of k integers\n    function sumK(arr, set, idx, sum, k) {\n        if (k === 0) return set.add(sum);\n        if (idx === arr.length) return;\n        sumK(arr, set, idx + 1, sum, k);\n        sumK(arr, set, idx + 1, sum + arr[idx], k - 1);\n    }\n    \n    function populateArray(dp, arr, isFirstArray) {\n        for (let i = 1; i <= arr.length; i++) {\n            let set = new Set();\n            sumK(arr, set, 0, 0, i);\n            set = [...set.values()];\n            if (!isFirstArray) {\n                // Sort the secondDP array for binary searching\n                set.sort((a, b) => a - b);\n            }\n            // i === a subset of i integers\n            dp[i] = (set);\n        }\n    }\n\n    let firstDP = [[0]], secondDP = [[0]];\n    populateArray(firstDP, firstHalf, true);\n    populateArray(secondDP, secondHalf, false);\n    \n    let min = Infinity;\n    // i === subset of length i\n    for (let i = 1; i < firstDP.length; i++) {\n        for (let num1 of firstDP[i]) {\n            let remainingNum1 = firstHalfSum - num1;\n            \n            // i + remainingSubsetLen must equal length n since our goal is to create two arrays of length n\n            let remainingSubsetLen = secondHalf.length - i;\n            \n            let l = 0, r = secondDP[remainingSubsetLen].length - 1;\n            while (l <= r) {\n                let mid = l + Math.floor((r - l) / 2);\n                let num2 = secondDP[remainingSubsetLen][mid];\n                let remainingNum2 = secondHalfSum - num2;\n\t\t\t\t// arr1Sum === sum of subsets of length n and arr2Sum === sum of subsets of length n\n\t\t\t\t// thereby creating two arrays of length n\n                let arr1Sum = num1 + num2, arr2Sum = remainingNum1 + remainingNum2;\n                if (arr1Sum === arr2Sum) return 0;\n\n                min = Math.min(min, Math.abs(arr1Sum - arr2Sum));\n                if (arr1Sum > arr2Sum) r = mid - 1;\n                else l = mid + 1;\n            }\n        }\n    }\n    return min;\n};",103        "solution_java": "class Solution {\n    public int minimumDifference(int[] nums) {\n        int n = nums.length;\n        int sum = 0;\n        for (int i : nums) {\n            sum += i;\n        }\n\n        TreeSet<Integer>[] sets = new TreeSet[n/2+1];\n        for (int i = 0; i < (1 << (n / 2)); ++i) {\n            int curSum = 0;\n            int m = 0;\n            for (int j = 0; j < n / 2; ++j) {\n                if ((i & (1<<j)) != 0) {\n                    curSum += nums[j];\n                    m ++;\n                }\n            }\n            if (sets[m] == null)\n                sets[m] = new TreeSet<Integer>();\n            sets[m].add(curSum);\n        }\n\n        int res = Integer.MAX_VALUE / 3;\n        for (int i = 0; i < (1 << (n / 2)); ++i) {\n            int curSum = 0;\n            int m = 0;\n            for (int j = 0; j < n / 2; ++j) {\n                if ((i & (1<<j)) != 0) {\n                    curSum += nums[n/2 + j];\n                    m ++;\n                }\n            }\n            int target = (sum - 2 * curSum) / 2;\n\n            Integer left = sets[n/2-m].floor(target), right = sets[n/2-m].ceiling(target);\n            if (left != null) {\n                res = Math.min(res, Math.abs(sum - 2 * (curSum + left.intValue())));\n            }\n\n            if (right != null) {\n                res = Math.min(res, Math.abs(sum - 2 * (curSum + right.intValue())));\n            }\n\n            if (res == 0)\n                return 0;\n\n        }\n\n        return res;\n    }\n}\n// Time Complexity: O(2^(n/2) * n/2 * n/2)",104        "solution_c": "class Solution {\npublic:\n    int minimumDifference(vector<int>& nums) {\n        int n = nums.size()/2; \n        vector<int> left(nums.begin(), nums.begin()+n), right(nums.begin()+n, nums.begin()+2*n); \n        \n        vector<vector<int>> vals(n+1); \n        for (int mask = 0; mask < (1<<n); ++mask) {\n            int diff = 0, key = __builtin_popcount(mask); \n            for (int i = 0; i < n; ++i) \n                diff += (mask & (1 << i)) ? left[i] : -left[i]; \n            vals[key].push_back(diff); \n        }\n        \n        for (auto& v : vals) sort(v.begin(), v.end()); \n        \n        int ans = INT_MAX; \n        for (int mask = 0; mask < (1<<n); ++mask) {\n            int diff = 0, key = n - __builtin_popcount(mask); \n            for (int i = 0; i < n; ++i) \n                diff += (mask & (1 << i)) ? right[i] : -right[i]; \n            auto it = lower_bound(vals[key].begin(), vals[key].end(), -diff); \n            if (it != vals[key].begin()) ans = min(ans, abs(diff + *prev(it))); \n            if (it != vals[key].end()) ans = min(ans, abs(diff + *it)); \n        }\n        return ans; \n    }\n};"105    },106    {107        "title": "Adding Spaces to a String",108        "algo_input": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.\n\n\n\tFor example, given s = \"EnjoyYourCoffee\" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain \"Enjoy Your Coffee\".\n\n\nReturn the modified string after the spaces have been added.\n\n&nbsp;\nExample 1:\n\nInput: s = \"LeetcodeHelpsMeLearn\", spaces = [8,13,15]\nOutput: \"Leetcode Helps Me Learn\"\nExplanation: \nThe indices 8, 13, and 15 correspond to the underlined characters in \"LeetcodeHelpsMeLearn\".\nWe then place spaces before those characters.\n\n\nExample 2:\n\nInput: s = \"icodeinpython\", spaces = [1,5,7,9]\nOutput: \"i code in py thon\"\nExplanation:\nThe indices 1, 5, 7, and 9 correspond to the underlined characters in \"icodeinpython\".\nWe then place spaces before those characters.\n\n\nExample 3:\n\nInput: s = \"spacing\", spaces = [0,1,2,3,4,5,6]\nOutput: \" s p a c i n g\"\nExplanation:\nWe are also able to place spaces before the first character of the string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 3 * 105\n\ts consists only of lowercase and uppercase English letters.\n\t1 &lt;= spaces.length &lt;= 3 * 105\n\t0 &lt;= spaces[i] &lt;= s.length - 1\n\tAll the values of spaces are strictly increasing.\n\n",109        "solution_py": "#TLE SOLUTION\nclass Solution:\n    def addSpaces(self, s: str, spaces: List[int]) -> str:\n\t\tspaces_idx = len(spaces)-1\n\n\t\tdef addString(index,s):\n\t\t\ts = s[:index]+\" \"+s[index:] \n\t\t\t#This changes the string at every instance hence taking so much time\n\t\t\treturn s\n\t\t\t\n\t\twhile spaces_idx>=0:\n\t\t\ts = addString(spaces[spaces_idx],s)\n\t\t\tspaces_idx-=1\n\t\treturn s",110        "solution_js": "/**\n * @param {string} s\n * @param {number[]} spaces\n * @return {string}\n */\nvar addSpaces = function(s, spaces) {\n    let words = spaces.map((space, index) => s.slice(index == 0 ? 0 : spaces[index-1], space));\n    words.push(s.slice(spaces[spaces.length-1]));\n    return words.join(' ');\n};",111        "solution_java": "class Solution {\n    public String addSpaces(String s, int[] spaces) {\n        \n        int j = 0,curr = 0;\n        StringBuilder sb = new StringBuilder();\n        while(curr<s.length()){\n           \n             if(j<spaces.length&&spaces[j]==curr){\n                 \n                sb.append(\" \");\n                j++;\n    \n                }\n                sb.append(s.charAt(curr));\n                curr++;\n\n        }\n\n        return sb.toString();\n        \n    }\n}",112        "solution_c": "class Solution {\npublic:\n    string addSpaces(string s, vector<int>& spaces) {\n        \n        int i,n=spaces.size(),m=s.size(),j;\n        string ans=\"\";\n        i=0;\n        j=0;\n        \n        //jth pointer for current index of spaces vector\n        //ith pointer for current index of our answer string\n        while(i<m)\n        {\n            //if at our current index i is equals to spaces[j] which means we have space at this index,so we add space right here\n            if(j<n&&i==spaces[j])\n            {\n                ans+=\" \";\n                j++;\n                //incrementing j to get next space index location\n            }\n            ans+=s[i];\n            i++;\n        }\n        \n        return ans;\n    }\n};"113    },114    {115        "title": "Poor Pigs",116        "algo_input": "There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.\n\nYou can feed the pigs according to these steps:\n\n\n\tChoose some live pigs to feed.\n\tFor each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.\n\tWait for minutesToDie minutes. You may not feed any other pigs during this time.\n\tAfter minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\n\tRepeat this process until you run out of time.\n\n\nGiven buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.\n\n&nbsp;\nExample 1:\n\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 15\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.\n\n\nExample 2:\n\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 30\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= buckets &lt;= 1000\n\t1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100\n\n",117        "solution_py": "class Solution(object):\n    def poorPigs(self, buckets, minutesToDie, minutesToTest):\n        # Calculate the max time for a pig to test buckets...\n        # Note that, max time will not be (minutesToTest / minutesToDie)...\n        # Thinking about all pigs drinking all buckets at last, but no one died immediately, so the poison bucket is the last bucket...\n        max_time = minutesToTest / minutesToDie + 1\n        # Initialize the required minimum number of pigs...\n        req_pigs = 0\n        # To find the minimum number of pigs, find the minimum req_pigs such that Math.pow(max_time, req_pigs) >= buckets...\n        while (max_time) ** req_pigs < buckets:\n            # Increment until it will be greater or equals to bucket...\n            req_pigs += 1\n        # Return the required minimum number of pigs...\n        return req_pigs",118        "solution_js": "/**\n * @param {number} buckets\n * @param {number} minutesToDie\n * @param {number} minutesToTest\n * @return {number}\n */\nvar poorPigs = function(buckets, minutesToDie, minutesToTest) {\n  let answer = 1;\n  let n = minutesToTest / minutesToDie >> 0;\n  n += 1;\n  \n  // calculation with loop\n  // while(n ** answer <= buckets) {\n  //   answer++;\n  // }\n  \n  return Math.ceil(Math.log(buckets) / Math.log(n));\n};",119        "solution_java": "class Solution {\n    public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n        int T = (minutesToTest/minutesToDie) + 1;\n        int cnt = 0;\n        int total = 1;\n        while (total < buckets) {\n            total *= T;\n            cnt++;\n        }\n        return cnt;\n    }\n}",120        "solution_c": "class Solution {\npublic:\n    int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n        // min_pig_count determined by equation: buckets =max_sub_job_load ** min_pig_count\n\t\t// max_sub_job_load  = minutesToTest / minutesToDie + 1\n        // min_pig_count = ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));\n        return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));\n    }\n};"121    },122    {123        "title": "Last Substring in Lexicographical Order",124        "algo_input": "Given a string s, return the last substring of s in lexicographical order.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abab\"\nOutput: \"bab\"\nExplanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\n\n\nExample 2:\n\nInput: s = \"leetcode\"\nOutput: \"tcode\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 4 * 105\n\ts contains only lowercase English letters.\n\n",125        "solution_py": "class Solution:\n    def lastSubstring(self, s: str) -> str:\n        i = 0\n        j = 1\n        k = 0\n        n = len(s)\n        while j + k < n:\n            if s[i + k] == s[j + k]:\n                k += 1\n            elif s[i + k] > s[j + k]:\n                j += k + 1\n                k = 0\n            elif s[i + k] < s[j + k]:\n                i = max(i + k + 1, j)\n                j = i + 1\n                k = 0\n        return s[i:]",126        "solution_js": "var lastSubstring = function(s) {\n    let res = 0;\n    for(let i = 1; i < s.length; i++){\n        if(s.slice(i) > s.slice(res)) res = i;\n    };\n    return s.slice(res);\n};",127        "solution_java": "class Solution {\n\npublic String lastSubstring(String s) {\nint maxIndex = s.length() - 1;\n\nfor(int currIndex = s.length() - 1 ; currIndex >= 0 ; currIndex--){\n    if(s.charAt(currIndex) > s.charAt(maxIndex))\n        maxIndex = currIndex;\n\n    else if(s.charAt(currIndex) == s.charAt(maxIndex)){\n        int i = currIndex + 1;\n        int j = maxIndex + 1;\n\n        while(i < maxIndex && j < s.length() && s.charAt(i) == s.charAt(j)){\n            i++;\n            j++;\n        }\n\n        if(i == maxIndex || j == s.length() || s.charAt(i) > s.charAt(j))\n            maxIndex = currIndex;\n    }\n}\n\nreturn s.substring(maxIndex);\n}\n}",128        "solution_c": "class Solution\n{\n    public:\n        string lastSubstring(string s)\n        {\n            int maxIndex = s.length() - 1;\n\n            for (int currIndex = s.length() - 1; currIndex >= 0; currIndex--)\n            {\n                if (s[currIndex] > s[maxIndex])\n                    maxIndex = currIndex;\n\n                else if (s[currIndex] == s[maxIndex])\n                {\n                    int i = currIndex + 1;\n                    int j = maxIndex + 1;\n\n                    while (i < maxIndex && j < s.length() && s[i] == s[j])\n                    {\n                        i++;\n                        j++;\n                    }\n\n                    if (i == maxIndex || j == s.length() || s[i] > s[j])\n                        maxIndex = currIndex;\n                }\n            }\n\n            return s.substr(maxIndex);\n        }\n};"129    },130    {131        "title": "Minimum Time to Complete Trips",132        "algo_input": "You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.\n\nEach bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.\n\nYou are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.\n\n&nbsp;\nExample 1:\n\nInput: time = [1,2,3], totalTrips = 5\nOutput: 3\nExplanation:\n- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n  The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n  The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n  The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.\n\n\nExample 2:\n\nInput: time = [2], totalTrips = 1\nOutput: 2\nExplanation:\nThere is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= time.length &lt;= 105\n\t1 &lt;= time[i], totalTrips &lt;= 107\n\n",133        "solution_py": "class Solution(object):\n    def minimumTime(self, time, totalTrips):\n        anstillnow=-1;\n        left=1;\n        right= 100000000000001;\n        \n        while(left<=right):\n            mid= left+ (right-left)/2      #find mid point like this to avoid overflow\n            \n            curr_trips=0;\n            \n            for t in time:\n                curr_trips+= mid/t\n            \n            if(curr_trips>=totalTrips):\n                anstillnow=mid\n                right=mid-1\n            \n            else:\n                left=mid+1\n\n        return anstillnow",134        "solution_js": "var minimumTime = function(time, totalTrips) {\n    let low = 1;\n    let high = Number.MAX_SAFE_INTEGER;\n    let ans = 0;\n    \n    while(low <= high) {\n        let mid = Math.floor(low + (high - low) / 2); // to prevent overflow\n        \n        if(isPossible(time, mid, totalTrips)) {\n            ans = mid\n            high = mid - 1;\n        } else {\n            low = mid + 1;\n        }\n    }\n    return ans;\n};\n\nfunction isPossible(arr, mid, totalTrips) {\n    let trips = 0;\n    for (let i = 0; i < arr.length; i++) {\n      trips += Math.floor(mid / arr[i]);\n    }\n    return trips >= totalTrips;\n}",135        "solution_java": "class Solution {\n    public long minimumTime(int[] time, int totalTrips) {\n        long anstillnow=-1;\n        \n        long left=1, right= 100000000000001L;\n        \n        while(left<=right){\n            long mid= left+ (right-left)/2;  //find mid point like this to avoid overflow\n            long curr_trips=0;\n            for(int t: time){\n                curr_trips+= mid/t;\n            }\n            \n            if(curr_trips>=totalTrips){\n                anstillnow=mid;\n                right=mid-1;\n            }\n            \n            else{\n                left=mid+1;\n            }\n        }\n        \n        return anstillnow;        \n    }\n}",136        "solution_c": "class Solution {\npublic:\n    long long minimumTime(vector<int>& time, int totalTrips) {\n        long long anstillnow=-1;\n\n        long long left=1, right= 100000000000001; //can also write this as 1+1e14\n\n        while(left<=right){\n            long long mid= left+ (right-left)/2; // find mid point like this to avoid overflow\n            long long curr_trips=0;\n            for(int t: time){\n                curr_trips+= mid/t;\n            }\n\n            if(curr_trips>=totalTrips){\n                anstillnow=mid;\n                right=mid-1;\n            }\n\n            else{\n                left=mid+1;\n            }\n        }\n\n        return anstillnow;\n    }\n};"137    },138    {139        "title": "Selling Pieces of Wood",140        "algo_input": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.\n\nTo cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.\n\nReturn the maximum money you can earn after cutting an m x n piece of wood.\n\nNote that you can cut the piece of wood as many times as you want.\n\n&nbsp;\nExample 1:\n\nInput: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\nOutput: 19\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.\n\n\nExample 2:\n\nInput: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\nOutput: 32\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 200\n\t1 &lt;= prices.length &lt;= 2 * 104\n\tprices[i].length == 3\n\t1 &lt;= hi &lt;= m\n\t1 &lt;= wi &lt;= n\n\t1 &lt;= pricei &lt;= 106\n\tAll the shapes of wood (hi, wi) are pairwise distinct.\n\n",141        "solution_py": "class Solution:\n    def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n        price = {(dimension_price[0], dimension_price[1]): dimension_price[2] for dimension_price in prices}\n        DP = [[-1 for _ in range(n + 1)] for _ in range(m + 1)]\n        \n        def solve(h: int, v: int) -> int:\n            if DP[h][v] != -1:\n                return DP[i][j]\n            \n            ans = price.get((h, v), 0)\n            \n            for i in range(1, 1 + h // 2):\n                ans = max(ans, (DP[i][v] if DP[i][v] != -1 else solve(i, v)) + (DP[h - i][v] if DP[h - i][v] != -1 else solve(h - i, v)))\n            \n            for j in range(1, 1 + v // 2):\n                ans = max(ans, (DP[h][j] if DP[h][j] != -1 else solve(h, j)) + (DP[h][v - j] if DP[h][v - j] != -1 else solve(h, v - j)))\n            \n            DP[h][v] = ans\n            \n            return ans\n        \n        return solve(m, n)",142        "solution_js": "var sellingWood = function(m, n, prices) {\n  let price = Array(n + 1).fill(0).map(() => Array(m + 1).fill(0));\n  for (let [height, width, woodPrice] of prices) {\n    price[width][height] = woodPrice;\n  }\n  let memo = Array(n + 1).fill(0).map(() => Array(m + 1).fill(-1));\n  return dfs(n, m);\n\n  function dfs(width, height) {\n    if (width === 0 || height === 0) return 0;\n    if (memo[width][height] !== -1) return memo[width][height];\n\n    let ans = price[width][height];\n    for (let h = 1; h <= Math.floor(height / 2); h++) {\n      ans = Math.max(ans, dfs(width, h) + dfs(width, height - h));\n    }\n    for (let w = 1; w <= Math.floor(width / 2); w++) {\n      ans = Math.max(ans, dfs(w, height) + dfs(width - w, height));\n    }\n    return memo[width][height] = ans;\n  }\n};",143        "solution_java": "class Solution {\n    public long sellingWood(int m, int n, int[][] prices) {\n        long[][] dp = new long[m+1][n+1];\n        for (int[] price : prices) {\n            dp[price[0]][price[1]] = price[2];\n        }\n        for (int i = 1; i < m+1; i++) {\n            for (int j = 1; j < n+1; j++) {\n                // all horizontal\n                for (int k = 1; k <= i/2; k++) {\n                    dp[i][j] = Math.max(dp[i][j], dp[i-k][j] + dp[k][j]);\n                }\n                // all vertical\n                for (int k = 1; k <= j/2; k++) {\n                    dp[i][j] = Math.max(dp[i][j], dp[i][j-k] + dp[i][k]);\n                }\n            }\n        }\n        \n        return dp[m][n];\n    }\n}",144        "solution_c": "class Solution {\nprivate:\n\tlong long f(int row, int col, map<pair<int,int>,long long> &mp){\n\n\t\t//Base case is tackled in this line\n\t\tlong long ans = mp[{row,col}]; \n\n\t\tfor(int i = 1;i < row;i++) //Partitions Row-wise\n\t\t\tans = max(ans,f(i,col,mp) + f(row-i,col,mp));\n\n\t\tfor(int j = 1;j < col;j++) //Partitions Column-wise\n\t\t\tans = max(ans,f(row, j, mp) + f(row, col-j, mp));\n\n\t\treturn ans;\n\t}\npublic:\n\tlong long sellingWood(int m, int n, vector<vector<int>>& prices) {\n\t\t//Declaring the HashMap\n\t\tmap<pair<int,int>,long long> mp;\n\n\t\t//Storing Prices in HashMap where {height,width} of wood is key and {Price} is value\n\t\tfor(int i = 0;i < prices.size();i++)\n\t\t\tmp[{prices[i][0],prices[i][1]}] = prices[i][2];\n\n\t\treturn f(m,n,mp);\n\t}\n};"145    },146    {147        "title": "Shortest Distance to a Character",148        "algo_input": "Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.\n\nThe distance between two indices i and j is abs(i - j), where abs is the absolute value function.\n\n&nbsp;\nExample 1:\n\nInput: s = \"loveleetcode\", c = \"e\"\nOutput: [3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.\n\n\nExample 2:\n\nInput: s = \"aaab\", c = \"b\"\nOutput: [3,2,1,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts[i] and c are lowercase English letters.\n\tIt is guaranteed that c occurs at least once in s.\n\n",149        "solution_py": "class Solution:\n    def shortestToChar(self, s: str, c: str) -> List[int]:\n        res = []\n        ch= []\n        for i in range(len(s)):\n            if s[i] == c:\n                ch.append(i)\n        min_d = len(s)\n        for i in range(len(s)):\n            for j in range(len(ch)):\n                min_d = min(min_d, abs(i-ch[j]))\n            res.append(min_d)\n            min_d = len(s)\n        return res",150        "solution_js": "/**\n * @param {string} s\n * @param {character} c\n * @return {number[]}\n */\nvar shortestToChar = function(s, c) {\n    \n    let result = []\n    \n    for(let i = 0; i< s.length ; i++) {\n        \n        if(s.charAt(i) === c) result.push(0)\n        else {\n            const next = s.indexOf(c,i) === -1 ? Infinity : s.indexOf(c,i) -i\n            const prev = result.lastIndexOf(0) === -1 ? Infinity : i- result.lastIndexOf(0) \n            result.push(Math.min(next,prev))\n        }\n        \n    }\n    \n    return result\n};",151        "solution_java": "class Solution {\n    public int[] shortestToChar(String s, char c) {\n        int n = s.length();\n        int index = -1;\n        int[] ans = new int[n];\n        // Starting from index 0 and storing the distance from the next c;\n        for(int i=0;i<n;i++){\n            if(s.charAt(i)==c) index = i;//to store the index of the nearest previous c\n\n            if(index==-1) ans[i] = Integer.MAX_VALUE;\n            else ans[i] = i-index;\n        }\n\n        // Starting from thr end and storing the distance from the previous c;\n        index = -1;\n        for(int i=n-1;i>=0;i--){\n            if(s.charAt(i)==c) index = i;//to store the index of the nearest next c\n\n            if(index!=-1) ans[i] = Math.min(ans[i],index-i);\n        }\n        return ans;\n    }\n}",152        "solution_c": "class Solution {\npublic:\n    vector<int> shortestToChar(string s, char c) {\n        vector<int>sk;\n        vector<int>res;\n        vector<int>temp;\n        int ss=0;\n        int mins;\n        for(int i=0;i<s.length();i++){\n            if(s[i]==c)\n            //storing all the c character location i.e 'e' in sk i.e [3,5,6,11]\n             sk.push_back(i);\n        }\n        for(int i=0;i<s.length();i++){\n            for(int j=0;j<sk.size();j++){\n            //now subtracting every i value with all value of character locations and storing the minimum in res vector.\n\n                mins=abs(sk[j]-i);\n                temp.push_back(mins);\n            }\n                //in first iteration [3-0=3,5-0=5,6-0=6,11-0=0] so removing the minimum elemnet from this that is 3 and stroing is res.\n            int min=temp[0];\n            for(auto i:temp){\n                if(i<min){\n                    min=i;\n                }\n            }\n            res.push_back(min);\n            temp.clear();\n\n        }\n\n        return res;\n    }\n};"153    },154    {155        "title": "Finding Pairs With a Certain Sum",156        "algo_input": "You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:\n\n\n\tAdd a positive integer to an element of a given index in the array nums2.\n\tCount the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 &lt;= i &lt; nums1.length and 0 &lt;= j &lt; nums2.length).\n\n\nImplement the FindSumPairs class:\n\n\n\tFindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2.\n\tvoid add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val.\n\tint count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]\nOutput\n[null, 8, null, 2, 1, null, null, 11]\n\nExplanation\nFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7);  // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\nfindSumPairs.count(8);  // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4);  // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\nfindSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\nfindSumPairs.count(7);  // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length &lt;= 1000\n\t1 &lt;= nums2.length &lt;= 105\n\t1 &lt;= nums1[i] &lt;= 109\n\t1 &lt;= nums2[i] &lt;= 105\n\t0 &lt;= index &lt; nums2.length\n\t1 &lt;= val &lt;= 105\n\t1 &lt;= tot &lt;= 109\n\tAt most 1000 calls are made to add and count each.\n\n",157        "solution_py": "class FindSumPairs:\n\n    def __init__(self, nums1: List[int], nums2: List[int]):\n        self.nums1 = sorted(nums1)\n        self.nums2 = nums2\n        self.hash2 = defaultdict(int)\n        for n in nums2:\n            self.hash2[n] += 1\n\n    def add(self, index: int, val: int) -> None:\n        self.hash2[self.nums2[index]] -= 1\n        self.nums2[index] += val\n        self.hash2[self.nums2[index]] += 1\n\n    def count(self, tot: int) -> int:\n        result = 0\n        for n in self.nums1:\n            if n >= tot:\n                break\n            result += self.hash2[tot - n]\n        return result",158        "solution_js": "function Counter(arr) {\n\n    // input: array\n    // output: corresponding occurrence-based dictionary\n\n    let keyOccDict = {};\n\n    arr.forEach(val => keyOccDict[val] = (keyOccDict[val] || 0) + 1);\n\n    return keyOccDict;\n}\n\nvar FindSumPairs = function(nums1, nums2) {\n    this.arrA = nums1;\n    this.arrB = nums2;\n\n    // maintain mapping between distinct number and occurrence for array A\n    this.dictA = Counter(this.arrA );\n\n    // maintain mapping between distinct number and occurrence for array B\n    this.dictB = Counter(this.arrB );\n\n    return\n};\n\nFindSumPairs.prototype.add = function(index, val) {\n\n    // update mapping for arrB\n\n    let old_value = this.arrB[index];\n    this.arrB[index] += val;\n    let new_value = this.arrB[index];\n\n    this.dictB[ old_value ] = this.dictB[old_value] - 1;\n    this.dictB[ new_value ] = (this.dictB[new_value] || 0) + 1;\n\n    return\n};\n\nFindSumPairs.prototype.count = function(tot) {\n\n    /*\n      Goal:\n\n      Find the method count of a + b = total,\n      where a comes from array A, and b comes from array B\n\n      apply the concept learned from Leetcode #1 Two sum\n      a + b = total <=> b = total - a\n\n      speed-up by dictionary\n    */\n\n    let counter = 0;\n\n    for( const [a, occ_a] of Object.entries(this.dictA) ){\n\n        let b = tot - a;\n\n        counter += occ_a * (this.dictB[b] || 0);\n\n    }\n\n    return counter;\n};",159        "solution_java": "class FindSumPairs {\n\n    private int [] nums1;\n    private int [] nums2;\n    Map<Integer, Integer> map = new HashMap<>();\n    public FindSumPairs(int[] nums1, int[] nums2) {\n        this.nums1 = nums1;\n        this.nums2 = nums2;\n        for (int number : nums2) {\n            map.put(number, map.getOrDefault(number, 0) + 1);\n        } \n        \n    }\n    \n    public void add(int index, int val) {\n        map.put(nums2[index], map.get(nums2[index]) - 1);\n        nums2[index] += val;\n        map.put(nums2[index], map.getOrDefault(nums2[index], 0) + 1);\n    }\n    \n    public int count(int tot) {\n        int result = 0;\n        for (int number : nums1) {\n            if (map.containsKey(tot - number)) {\n                result += map.get(tot - number);\n            }\n        }\n        return result;\n    }\n}\n\n/**\n * Your FindSumPairs object will be instantiated and called as such:\n * FindSumPairs obj = new FindSumPairs(nums1, nums2);\n * obj.add(index,val);\n * int param_2 = obj.count(tot);\n */",160        "solution_c": "class FindSumPairs {\npublic:\n    //use map to store the element as key and its frequency as its value\n    unordered_map<int,int> freq;\n    vector<int> v1;\n    vector<int> v2;\n    FindSumPairs(vector<int>& nums1, vector<int>& nums2) {\n        for(auto ele:nums2)\n            freq[ele]++;\n        v1=nums1;\n        v2=nums2;\n    }\n    \n    void add(int index, int val) {\n        //decrease the freq of value at the index\n        freq[v2[index]]-- ;\n        v2[index]+=val;\n        //we got a new value, increment the freq of the value\n        freq[v2[index]]++;\n    }\n    \n    int count(int tot) {\n        //traverese through the v1 and find the elements which sum upto the target tot\n        int pairs=0;\n        for(auto ele:v1)\n            if(tot>ele && freq.count(tot-ele))\n                pairs+=freq[tot-ele];\n        return pairs;\n    }\n};\n\n/**\n * Your FindSumPairs object will be instantiated and called as such:\n * FindSumPairs* obj = new FindSumPairs(nums1, nums2);\n * obj->add(index,val);\n * int param_2 = obj->count(tot);\n */"161    },162    {163        "title": "Queens That Can Attack the King",164        "algo_input": "On an 8x8 chessboard, there can be multiple Black Queens and one White King.\n\nGiven an array of integer coordinates queens that represents the positions of the Black Queens, and a pair of coordinates king that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.\n&nbsp;\nExample 1:\n\n\n\nInput: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput: [[0,1],[1,0],[3,3]]\nExplanation:&nbsp; \nThe queen at [0,1] can attack the king cause they're in the same row. \nThe queen at [1,0] can attack the king cause they're in the same column. \nThe queen at [3,3] can attack the king cause they're in the same diagnal. \nThe queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. \nThe queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. \nThe queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.\n\n\nExample 2:\n\n\n\nInput: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput: [[2,2],[3,4],[4,4]]\n\n\nExample 3:\n\n\n\nInput: queens = [[5,6],[7,7],[2,1],[0,7],[1,6],[5,1],[3,7],[0,3],[4,0],[1,2],[6,3],[5,0],[0,4],[2,2],[1,1],[6,4],[5,4],[0,0],[2,6],[4,5],[5,2],[1,4],[7,5],[2,3],[0,5],[4,2],[1,0],[2,7],[0,1],[4,6],[6,1],[0,6],[4,3],[1,7]], king = [3,4]\nOutput: [[2,3],[1,4],[1,6],[3,7],[4,3],[5,4],[4,5]]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= queens.length&nbsp;&lt;= 63\n\tqueens[i].length == 2\n\t0 &lt;= queens[i][j] &lt;&nbsp;8\n\tking.length == 2\n\t0 &lt;= king[0], king[1] &lt; 8\n\tAt most one piece is allowed in a cell.\n\n",165        "solution_py": "class Solution:\n    def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n        ans = []\n        d = {(i[0],i[1]) : True for i in queens}\n        def goUp(r,c):\n            while r >=0:\n                if (r,c) in d:\n                    ans.append([r,c])\n                    break\n                r -= 1\n        def goDown(r,c):\n            while r < 8:\n                if (r,c) in d: \n                    ans.append([r,c])\n                    break\n                r += 1\n        def goLeft(r,c):\n            while c >= 0:\n                if (r,c) in d:\n                    ans.append([r,c])\n                    break\n                c -= 1\n        def goRight(r,c):\n            while c < 8:\n                if (r,c) in d: \n                    ans.append([r,c])\n                    break\n                c += 1\n        def goD1(r,c):\n            while r >=0 and c >= 0:\n                if (r,c) in d:\n                    ans.append([r,c])\n                    break\n                r -= 1\n                c -= 1\n        def goD2(r,c):\n            while r < 8 and c >= 0:\n                if (r,c) in d: \n                    ans.append([r,c])\n                    break\n                r += 1\n                c -= 1\n        def goD3(r,c):\n            while r < 8 and c < 8:\n                if (r,c) in d: \n                    ans.append([r,c])\n                    break\n                r += 1\n                c += 1\n        def goD4(r,c):\n            while r >= 0 and c < 8:\n                if (r,c) in d: \n                    ans.append([r,c])\n                    break\n                r -= 1\n                c += 1\n\n        goUp(king[0],king[1])\n        goDown(king[0],king[1])\n        goLeft(king[0],king[1])\n        goRight(king[0],king[1])\n        goD1(king[0],king[1])\n        goD2(king[0],king[1])\n        goD3(king[0],king[1])\n        goD4(king[0],king[1])\n\n        return ans",166        "solution_js": "/**\n * @param {number[][]} queens\n * @param {number[]} king\n * @return {number[][]}\n */\nvar queensAttacktheKing = function(queens, king) {\n    const map = {}, res = []\n    for (let queen of queens) {\n        map[queen] = 1\n    }\n    \n    for (let i = -1; i < 2; i++) {\n        for (let j = -1; j < 2; j++) {\n            if (i==0 && j==0) continue\n            for (let k = 1; k < 8; k++) {\n                let x = king[0] + k*i\n                let y = king[1] + k*j\n                if (x < 0 || y < 0 || x > 7|| y > 7) break\n                if ([x,y] in map) {\n                    res.push([x,y])\n                    break\n                }\n            }\n        }\n    }\n    \n    return res\n};",167        "solution_java": "class Solution {\n    public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {\n        List<List<Integer>> res = new ArrayList<>();\n        int r=king[0];\n        int l=king[1];\n        int [][]board =new int[8][8];\n        int n=8;\n\n// 8 cases;\n// moving upward\n// moving downward\n// moving right\n// moving left\n// moving upper right diagonal\n// moving upper left diagonal'\n// moving lower left diagonal\n// moving lower right diagonal\n\n        int i,j;\n        for(i=0;i<queens.length;i++)\n        {\n            for(j=0;j<1;j++)\n            {\n                int row=queens[i][j];\n                int column=queens[i][j+1];\n                board[row][column]=1;\n            }\n\n        }\n        // for(i=0;i<8;i++)\n        // {\n        // for(j=0;j<8;j++)\n        // {\n        // System.out.println(board[i][j]);\n        // }\n        // System.out.println();\n        // }\n        for(j=l;j<n;j++)\n        {\n            if(board[r][j]==1)\n            {\n                res.add(new ArrayList<>(Arrays.asList(r, j)));\n                break;\n            }\n        }\n        for(i=r;i<n;i++)\n        {\n            if(board[i][l]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(i, l)));\n                 break;\n            }\n        }\n        for(i=r;i>=0;i--)\n        {\n            if(board[i][l]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(i, l)));\n                 break;\n\n            }\n        }\n        for(j=l;j>=0;j--)\n        {\n            if(board[r][j]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(r, j)));\n                 break;\n\n            }\n        }\n        for(i=r,j=l;i>=0 && j>=0;j--,i--)\n        {\n            if(board[i][j]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(i, j)));\n                 break;\n            }\n        }\n        for(i=r,j=l;j<n && i>=0;j++,i--)\n        {\n            if(board[i][j]==1)\n            {\n                res.add(new ArrayList<>(Arrays.asList(i, j)));\n                break;\n            }\n        }\n        for(i=r,j=l;i<n && j<n;j++,i++)\n        {\n            if(board[i][j]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(i, j)));\n                 break;\n            }\n        }\n        for(i=r,j=l;j>=0 && i<n;j--,i++)\n        {\n            if(board[i][j]==1)\n            {\n                 res.add(new ArrayList<>(Arrays.asList(i, j)));\n                 break;\n            }\n        }\n        return res;\n    }\n}",168        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) \n    {\n        vector<vector<int>> ans;\n        vector<vector<int>> board(8, vector<int>(8, 0));\n\n        for(auto queen: queens) board[queen[0]][queen[1]] = 1;\n        \n        for(int x=-1; x<=1; x++)  // Both loops are for checking in all the 8 possible directions\n        {\n            for(int y=-1; y<=1; y++)\n            {\n                if(x == 0 and y == 0) continue;\n                int startx = king[0], starty = king[1];\n                \n                while(startx >= 0 and startx < 8 and starty >= 0 and starty < 8)\n                {\n                    if(board[startx][starty] == 1)  // If queen is found, append it to ans and break\n                    {\n                        ans.push_back({startx, starty});\n                        break;\n                    }\n                    startx += x, starty += y;      // Otherwise keep moving forward in earlier direction\n                }\n            }\n        }\n        return ans;\n    }\n};"169    },170    {171        "title": "First Unique Character in a String",172        "algo_input": "Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.\n\n&nbsp;\nExample 1:\nInput: s = \"leetcode\"\nOutput: 0\nExample 2:\nInput: s = \"loveleetcode\"\nOutput: 2\nExample 3:\nInput: s = \"aabb\"\nOutput: -1\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of only lowercase English letters.\n\n",173        "solution_py": "class Solution:\n    def firstUniqChar(self, s: str) -> int:\n        ls=[]\n        for i in range(len(s)):\n            x=s.count(s[i])\n            if x==1:\n                return i\n        return -1",174        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\n\nvar firstUniqChar = function(s) {\n    let dec = {};\n\n    for(let i=0; i < s.length ; i++){\n        if(dec[s[i]]){\n            dec[s[i]]['counter']++;\n        }else{\n            dec[s[i]] = {},\n            dec[s[i]]['counter'] = 1;\n            dec[s[i]]['index'] = i;\n        }\n    }\n\n    for(let i=0; i < s.length ; i++){\n        if(dec[s[i]]['counter'] == 1) {\n            return dec[s[i]]['index'];\n            break;\n        }\n    }\n\n    return -1;\n};",175        "solution_java": "class Solution {\n    public int firstUniqChar(String s) {\n        HashMap<Character,Integer>hmap=new HashMap<>();\n        for(int i=0;i<s.length();i++){\n            if(!hmap.containsKey(s.charAt(i))){\n                hmap.put(s.charAt(i),1);\n            }\n                else{\n                    hmap.put(s.charAt(i),hmap.get(s.charAt(i))+1);\n            }\n        }\n        for(int i=0;i<s.length();i++){\n            if(hmap.get(s.charAt(i))==1)\n                return i;\n        }\n        return -1;\n    }\n}",176        "solution_c": "class Solution {\npublic:\nint firstUniqChar(string s) {\n    unordered_map<char, int> mp;\n\n    for(int i=0; i<s.length(); i++){\n        mp[s[i]]++;\n    }\n\n    for(int i=0; i<s.length(); i++){\n        if(mp[s[i]] == 1){\n            return i;\n        }\n    }\n\n    return -1;\n}\n};"177    },178    {179        "title": "Number of Nodes in the Sub-Tree With the Same Label",180        "algo_input": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).\n\nThe edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.\n\nReturn an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.\n\nA subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.\n\n&nbsp;\nExample 1:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\nOutput: [2,1,1,1,1,1,1]\nExplanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\n\n\nExample 2:\n\nInput: n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\nOutput: [4,2,1,1]\nExplanation: The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\n\n\nExample 3:\n\nInput: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\nOutput: [3,2,1,1,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 &lt;= ai, bi &lt; n\n\tai != bi\n\tlabels.length == n\n\tlabels is consisting of only of lowercase English letters.\n\n",181        "solution_py": "class Solution:\n    \"\"\"\n    we can solve this using dfs based approach\n    identify the root of the tree and start a dfs from there \n    \"\"\"\n    def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:\n        graph_map = {i: set() for i in range(n)}\n        for edge in edges:\n            graph_map[edge[0]].add(edge[1])\n            graph_map[edge[1]].add(edge[0])\n            \n        result = [None for _ in range(n)]\n        \n        visited = set()\n        def dfs(index):\n            visited.add(index)\n            temp = [0 for _ in range(26)]\n            temp[ord(labels[index])-97]+=1\n            for idx in graph_map[index]:\n                if idx not in visited:\n                    x = dfs(idx)\n                    temp = [a + b for a, b in zip(temp, x)]\n            result[index] = temp[ord(labels[index])-97]\n            return temp\n        \n        dfs(0)\n        return result",182        "solution_js": "var countSubTrees = function(n, edges, labels) {\n    const adj = [];\n\n    for (let i = 0; i < n; i++) {\n        adj[i] = [];\n    }\n\n    for (const [u, v] of edges) {\n        adj[u].push(v);\n        adj[v].push(u);\n    }\n\n    const resCount = new Array(n).fill(0);\n\n    dfs(0, -1);\n\n    return resCount;\n\n    function dfs(node, parent) {\n        const label = labels.charCodeAt(node) - 97;\n\n        const charCount = new Array(26).fill(0);\n\n        charCount[label] = 1;\n\n        for (const childNode of adj[node]) {\n            if (childNode == parent) continue;\n\n            const subCount = dfs(childNode, node);\n\n            for (let i = 0; i < 26; i++) {\n                charCount[i] += subCount[i];\n            }\n        }\n\n        resCount[node] = charCount[label];\n        return charCount;\n    }\n}",183        "solution_java": "class Solution {\n  int[] res;\n\n  public int[] countSubTrees(int n, int[][] edges, String labels) {\n    res = new int[n];\n    Map<Integer, List<Integer>> adjList = new HashMap<>();\n    for (int i = 0; i < n; i++) {\n      adjList.put(i, new ArrayList<>());\n    }\n    for (int[] edge : edges) {\n      adjList.get(edge[0]).add(edge[1]);\n      adjList.get(edge[1]).add(edge[0]);\n    }\n    postOrderDfs(adjList, labels, 0, -1);\n    return res;\n  }\n\n  int[] postOrderDfs(Map<Integer, List<Integer>> adjList, String labels, int n, int parent) {\n    int[] chars = new int[26];\n    chars[labels.charAt(n) - 'a']++;\n    for (int next : adjList.get(n)) {\n      if (next != parent) mergeArrCounts(chars, postOrderDfs(adjList, labels, next, n));\n    }\n    res[n] = chars[labels.charAt(n) - 'a'];\n    return chars;\n  }\n\n  // Merge from B to A\n  void mergeArrCounts(int[] A, int[] B) {\n    for (int i = 0; i < 26; i++) {\n      A[i] += B[i];\n    }\n  }\n}",184        "solution_c": "class Solution {\n    vector<int> ans;\n    vector<vector<int>> graph;\n    string global;\npublic:\n    \n    \n    vector<int> getAns(int u, int parent){\n        ans[u] = 1;\n        char rootChar = global[u];\n        vector<int> toReturn = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n        \n        for(int adj : graph[u]){\n            if(adj != parent){\n                vector<int> c = getAns(adj, u);\n                for(int i = 0 ; i < 26 ; i++){\n                    toReturn[i] += c[i];\n                } \n                ans[u] += c[rootChar-'a'];\n            }\n            \n        }\n        toReturn[rootChar-'a'] += 1;\n        return toReturn;\n    }\n    \n    vector<int> countSubTrees(int n, vector<vector<int>>& edges, string labels) {\n        ans.resize(n);\n        graph.resize(n);\n        global = labels;\n        \n        \n        \n        for(vector<int> edge : edges){\n            graph[edge[0]].push_back(edge[1]);\n            graph[edge[1]].push_back(edge[0]);\n        }\n        \n        int root = 0;\n        int parent =  -1;  \n        getAns(root, parent);\n        return ans;\n \n    }\n};"185    },186    {187        "title": "Maximum Value at a Given Index in a Bounded Array",188        "algo_input": "You are given three positive integers:&nbsp;n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:\n\n\n\tnums.length == n\n\tnums[i] is a positive integer where 0 &lt;= i &lt; n.\n\tabs(nums[i] - nums[i+1]) &lt;= 1 where 0 &lt;= i &lt; n-1.\n\tThe sum of all the elements of nums does not exceed maxSum.\n\tnums[index] is maximized.\n\n\nReturn nums[index] of the constructed array.\n\nNote that abs(x) equals x if x &gt;= 0, and -x otherwise.\n\n&nbsp;\nExample 1:\n\nInput: n = 4, index = 2,  maxSum = 6\nOutput: 2\nExplanation: nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].\n\n\nExample 2:\n\nInput: n = 6, index = 1,  maxSum = 10\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= maxSum &lt;= 109\n\t0 &lt;= index &lt; n\n\n",189        "solution_py": "class Solution:\n    def maxValue(self, n: int, index: int, maxSum: int) -> int:\n        l = 1\n        r = int(1e9)\n        ans = 0\n\n        while l<=r:\n            mid = (l+r)//2\n            total = 0\n\n            # add left numbers\n            if mid>=index+1:\n                first = mid-index\n                size = index+1\n                total += first*size + size*(size-1)/2\n            else:\n                total += mid*(mid+1)/2\n                total += index+1-mid\n\n\n            # add right numbers\n            size = n-index\n            if mid >= size:\n                last = mid - (n-index-1)\n                total += last*size + size*(size-1)/2\n            else:\n                total += mid*(mid+1)/2\n                total += (size-mid)   \n\n            # deduct mid because it was added twice \n            total -= mid\n            \n            if total <= maxSum:\n                ans = max(ans, mid)\n                l = mid+1\n            else:\n                r = mid-1\n\n        return ans",190        "solution_js": "var maxValue = function(n, index, maxSum) {\n    function getSum(len,v){\n        var sum = 0;\n        if(len<=v)\n        {\n            sum = (2*v-len+1) * len / 2;\n        }\n        else\n        {\n             sum = (1+v)*v/2 + len - v;\n        }\n        return sum;\n    }\n    function isValid(mid)\n    {\n        var curSum = getSum(leftLen,mid) + getSum(rightLen, mid) - mid;\n        return curSum<=maxSum;\n    }\n    var l = 0;\n    var r = 1000000000;\n    var leftLen = (index+1);\n    var rightLen = n-index;\n    while(l<r)\n    {\n        var mid = Math.ceil((l+r)/2); // handle dead loop when l===r & l=mid\n        if(!isValid(mid))\n        {\n            r = mid-1;\n        }\n        else\n        {\n            l = mid;\n        }\n    }\n    return l;\n};",191        "solution_java": "/* Intuition:\nAs the number of elements is 10^9 so we can't actually create the array\nAnd by seeing the limit we can judge that the complexity should be O(logn)\nSo it will become obvious that binary search can only help to solve this prob\n\nWe have to put the maximum possible value in the index position and then all \nthe values to its right and left should decrease by 1 until the value reaches 1\nfor Ex in n = 6, index = 1,  maxSum = 10\n\nour index at 1 should be 3 and the array will look like\n2  3  2 1 1\n+ max - - same\n\nmeans you have to make an array which is strictly increasing and it attains its max (which is answer)\nthen strictly decreasing till value becomes 1 and then continues it as 1. Like\n1 ... 1, 2, 3, 4, 5, 6(if answer is 6), 5, 4, 3, 2, 1, .... 1\n\nWhy this solution?\nBecause our objective is to maximize our index position value i.e. ans. So to maximize it\nwe all the other elements other than index position should be as low as possible (so that sum of our array\nis less than maxSum), which will lead to this solution of \"Get the max element on index given and decrease strictly\non both sides of the array till our value is 1, and then continue it to 1\"\n*/\n\nclass Solution {\n    public int maxValue(int n, int index, int maxSum) {\n        // Setting the initial values is very important, our ans can never be 0 so set low as 1\n        int low = 1, mid = 0, high = 1000000000;\n        while(low <= high) {\n            mid = (low + high) / 2;\n            \n            // If our ans (which is mid) is making the sum of array more than maxSum means we have to decrease our high\n            if(calcAns(mid, index, n) > maxSum) { \n                high = mid - 1;\n            } \n            \n            // If our ans (which is mid) is so low that even ans + 1 (i.e. mid + 1) is giving better result that means increase our low\n            else if(calcAns(mid + 1, index, n)  <= maxSum) {\n                low = mid + 1;\n            } \n            \n            // If our ans (== mid) is such that the sum of array is less than maxSum and even increasing 1 to mid will result the total\n            // sum to increase from maxSum, that signifies that we have the answer as mid\n            else {\n                break;\n            }\n        }\n        \n        return mid;\n    }\n    \n    public int calcAns(int max, int idx, int n) {\n        \n        // This method will give you answer of the setup where our peak element is ans at index idx and we have n elements\n        // So we have two part of array one is the left part (1, 1... 2, 3 ... max - 1) and then (max, max - 1, max - 2, 1 ... 1)\n        // so you can think of it as we have few extraOnes on both left and right parts and then an AP array which goes upto max\n        \n        // Left part I have taken till max - 1 and right part I have taken from max.\n        // calcPart takes (first value of AP, number of elements)\n        \n        long ret = calcPart(max - 1, idx) + calcPart(max, n - idx);\n        if(ret > 1000000000) {\n            // Seeing the constraints, if you chose to take high mid value then it might overflow from int. And our answer can never\n            // be greater than 10^9 so limit it to that.\n            return 1000000001;\n        } else {\n            \n            // This is the sum of the array where max is taken as answer\n            return (int)ret;\n        }\n    }\n    \n    public long calcPart(int a, int num) {\n        \n        // For AP we need first element (which is \"a\") and last element (which we calculate in an)\n        long an = 0, extraOnes = 0;\n        long ans = 0;\n        if(num >= a) {\n            \n            // If total number of elements is more than a which means it will look like\n            // a, a - 1, a - 2,  ... , 2, 1 ... followed by extraOnes\n            an = 1;\n            extraOnes = num - a;\n        } else if(num < a) {\n            \n            // If total number of elements is such that we never reach 1 as our last element means\n            // a, a - 1, a - 2 ... a - x, then extraOnes will be 0\n            extraOnes = 0;\n            an = a - num + 1;\n        }\n        \n        // Sum of AP where we know first and last element = ((first + last) * n) / 2\n        ans = ((an + a) * (a - an + 1)) / 2;\n        \n        // Add extra ones\n        ans += extraOnes;\n        \n        return ans;\n    }\n}",192        "solution_c": "class Solution {\npublic:\n    int maxValue(int n, int index, int maxSum) {\n        int lo = 1, hi = maxSum;\n        int r = n - index -1;\n        int l = index;\n        long res = 0;\n        while(lo <= hi) {\n            int mid = lo + (hi- lo)/2;\n            long sum = 0;\n            long rs = 0, ls = 0, m = mid -1;\n            if(r<=m)\n                rs = m*(m+1)/2 - (m-r)*(m-r+1)/2; // if we have to calculate 9+8+7+6, sum = 9*(9+1)/2 - (9-4)(9-4+1)/2\n            else\n                rs = m*(m+1)/2 + r - m; // if we encounter the case in which array right to index is 3,2,1,1,1, sum = 3*(3+1)/2 + 5-2\n            if(l<=m)\n                ls = m*(m+1)/2 - (m-l)*(m-l+1)/2; // similar to above.\n            else\n                ls = m*(m+1)/2 + l-m;\n\n            sum = mid + ls + rs;\n\n            if(sum <= maxSum)\n                res = mid,lo = mid+1;\n            else hi = mid -1;\n        }\n        return res;\n    }\n};"193    },194    {195        "title": "Copy List with Random Pointer",196        "algo_input": "A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.\n\nConstruct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.\n\nFor example, if there are two nodes X and Y in the original list, where X.random --&gt; Y, then for the corresponding two nodes x and y in the copied list, x.random --&gt; y.\n\nReturn the head of the copied linked list.\n\nThe linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:\n\n\n\tval: an integer representing Node.val\n\trandom_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.\n\n\nYour code will only be given the head of the original linked list.\n\n&nbsp;\nExample 1:\n\nInput: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput: [[7,null],[13,0],[11,4],[10,2],[1,0]]\n\n\nExample 2:\n\nInput: head = [[1,1],[2,1]]\nOutput: [[1,1],[2,1]]\n\n\nExample 3:\n\n\n\nInput: head = [[3,null],[3,0],[3,null]]\nOutput: [[3,null],[3,0],[3,null]]\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 1000\n\t-104 &lt;= Node.val &lt;= 104\n\tNode.random is null or is pointing to some node in the linked list.\n\n",197        "solution_py": "from collections import defaultdict\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n        self.val = int(x)\n        self.next = next\n        self.random = random\n\"\"\"\n\nclass Solution:\n    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n        \n        \n        \n        # ll=res\n        # k=0\n        # ind=0\n        # kmk=1\n        jj=None\n        g=defaultdict(lambda:-1)\n        k=0\n        hh=head\n        while(head):\n            res=Node(head.val)\n            if k==0:\n                jj=res\n\n            if k==1:\n                prev.next=res\n            \n            g[head]=res\n            prev=res\n            k=1\n            head=head.next\n            \n        # print(g)\n        \n        # for i in g:\n        #     print(i.val,g[i].val)\n            \n        kk=jj\n        mm=jj\n        # print(head)\n        while(hh):\n            if hh.random!=None:\n                \n                jj.random=g[hh.random]\n            else:\n                jj.random=None\n            hh=hh.next\n            \n            jj=jj.next    \n            # head=head.next\n        kkk=kk\n        # while(kk):\n        #     print(kk.val)\n        #     kk=kk.next\n            \n        return kkk\n#             if g[ind]!=-1:\n#                 g[ind].random=res\n                \n#             res=Node(head.val)\n#             if kmk==1:\n#                 ll=res\n#             kmk=0\n#             mm=head.next\n#             if mm:\n                \n#                 jk=Node(mm.val)\n#                 res.next=jk\n#             if head.random !=None:\n#                 g[head.random]=res\n#             else:\n#                 res.random=None\n#             head=head.next\n#             ind+=1\n#             # res=res.next\n            \n#         return ll\n            \n            # if k==0:\n            #     res.val=head.val\n            #     mm=head.next\n                \n                \n                \n            \n            ",198        "solution_js": "var copyRandomList = function(head) {\n    if(!head) return head\n    let curr = head;\n\n    // manipulate the Linked List and store a copy node at every nod's next\n    while(curr != null){\n        let next = curr.next;\n        curr.next = new Node(curr.val);\n        curr.next.next = next\n        curr = next\n    }\n    // console.log(head)\n\n    // Setting random point of copied node according to original node\n    curr = head;\n    while(curr != null && curr.next != null){\n        if(curr.random){\n            curr.next.random = curr.random.next\n        }else{\n            curr.next.random = null\n        }\n        curr = curr.next.next\n    }\n    // console.log(head.next.next.next)\n\n    // break the like made for linking copy node with original node\n    curr = head;\n    let ans = head.next;\n\n    while(curr != null){\n        let temp = curr.next;\n        if(temp){\n        curr.next = temp.next;\n        curr = curr.next;\n        }\n        if(curr){\n        temp.next = curr.next;\n        temp = temp.next\n        }\n    }\n    return ans\n};",199        "solution_java": "class Solution {\n    public Node copyRandomList(Node head) {\n        \n        if(head == null)\n            return null;\n        \n        HashMap<Node,Node> map = new HashMap<>();\n        \n        //node to be returned\n        Node ans = new Node(head.val);\n        \n        //temproary pointer to the ans node\n        Node tempAns = ans;\n        \n        Node temp = head;\n        \n        map.put(head,ans);\n        temp = temp.next;\n        \n        \n        //loop to store the lookalike new nodes of the original ones\n        //create the new list side by side\n        while(temp != null){\n            Node x = new Node(temp.val);\n            map.put(temp,x);\n            tempAns.next = x;\n            tempAns = x;\n            temp = temp.next;\n        }\n        \n        //repointing them to the start\n        temp = head;\n        tempAns = ans;\n        \n        //will have lookup of O(1) for the random nodes;\n        while(temp!=null){\n            tempAns.random = map.get(temp.random);\n            tempAns = tempAns.next;\n            temp = temp.next;\n        }\n        \n        return ans;\n        \n    }\n}",200        "solution_c": "class Solution {\npublic:\n    Node* copyRandomList(Node* head) {\n\n        if(head==NULL){\n            return NULL;\n        }\n\n        Node* temp= head;\n        while(temp!=NULL){\n            Node* m= new Node(temp->val);\n            m->next= temp->next;\n            temp->next= m;\n            temp = temp->next->next;\n        }\n        temp= head;\n        while(temp!=NULL){\n            if(temp->random==NULL){\n                temp->next->random=NULL;\n            }\n            else{\n                temp->next->random= temp->random->next;\n            }\n\n            temp= temp->next->next;\n        }\n        temp= head;\n        Node* p= new Node(-1);\n        Node* r= p;\n        Node* q= head;\n        while(q!=NULL){\n            q= q->next->next;\n            p->next=temp->next;\n            p=p->next;\n            temp->next=q;\n            temp= temp->next;\n        }\n        p->next=NULL;\n\n        return r->next;\n    }\n};"201    },202    {203        "title": "Distinct Echo Substrings",204        "algo_input": "Return the number of distinct non-empty substrings of text&nbsp;that can be written as the concatenation of some string with itself (i.e. it can be written as a + a&nbsp;where a is some string).\n\n&nbsp;\nExample 1:\n\nInput: text = \"abcabcabc\"\nOutput: 3\nExplanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\n\n\nExample 2:\n\nInput: text = \"leetcodeleetcode\"\nOutput: 2\nExplanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 2000\n\ttext&nbsp;has only lowercase English letters.\n\n",205        "solution_py": "class Solution:\n    def distinctEchoSubstrings(self, s: str) -> int:\n        hash=set()\n        n=len(s)\n        for i in range(n):\n            for j in range(i):\n                \n                if (i-j)&1==1:\n                    \n                    k=(i-j)//2\n                    \n                    if s[j:j+k+1]==s[j+k+1:i+1]:\n                        hash.add(s[j:j+k+1]+s[j+k+1:i+1])\n        return len(hash)\n                    \n                    \n                    \n        ",206        "solution_js": "/**\n * @param {string} text\n * @return {number}\n */\nvar distinctEchoSubstrings = function(text) {\n    const store = new Set();\n    for (let i = 0; i < text.length; i++) {\n        for (let j = i + 1; j < text.length; j++) {\n            const left = text.substring(i,j);\n\t\t\tconst right = text.substring(j, j + j - i);\n            if (left === right) store.add(left);\n        }\n    }\n    return store.size;\n};",207        "solution_java": "class Solution {\n    private static final int PRIME = 101;\n    private static final int MOD = 1_000_000_007;\n    public int distinctEchoSubstrings(String text) {\n        int n = text.length();\n        \n        // dp[i][j] : hash value of text[i:j]\n        int[][] dp = new int[n][n];\n        for (int i = 0; i < n; i++) {\n            long hash = 0;\n            for (int j = i; j < n; j++) {\n                hash = hash * PRIME + (text.charAt(j) - 'a' + 1);\n                hash %= MOD;\n                dp[i][j] = (int) hash;\n            }\n        }\n        \n        Set<Integer> set = new HashSet<>();\n        int res = 0;\n        for (int i = 0; i < n-1; i++) {\n            // compare text[i:j] with text[j+1: 2j-i+1]\n            for (int j = i; 2*j - i + 1 < n; j++) {\n                if (dp[i][j] == dp[j+1][2*j - i+1] && set.add(dp[i][j])) res++;\n            }\n        }\n        \n        return res;\n    }\n}",208        "solution_c": "class Solution {\npublic:\n    static const int N=2005;\n    int mod=1e9+7;\n    int B=31;\n    long long h[N],p[N],invp[N];\n    int modexp(int x,int y){\n        int res=1;\n        while(y>0){\n            if(y&1) res=((long long)res*x)%mod;\n            x=((long long)x*x)%mod;\n            y=y>>1;\n        }\n        return res;\n    }\n    int sub_hash(int l,int r){\n        int ans=h[r];\n        if(l>0)\n            ans=((ans+mod-h[l-1])*invp[l]*1LL)%mod;\n        return ans;\n    }\n    int distinctEchoSubstrings(string text) {\n        set<int> res;\n        int ans=0;\n        p[0]=1;invp[0]=1;\n        for(int i=1;i<2005;i++){\n            p[i]=(p[i-1]*B)%mod;\n        }\n        for(int i=1;i<N;i++){\n            invp[i]=(invp[i-1]*modexp(B,mod-2))%mod;\n        }\n        int n=text.size();\n        h[0]=(text[0]-'a'+1);\n        for(int i=1;i<n;i++){\n            h[i]=(h[i-1]+((text[i]-'a'+1)*p[i])*1LL)%mod;\n        }\n        for(int len=1;len<=n/2;len++){\n            for(int i=0;i<n+1-2*len;i++){\n                int a=sub_hash(i,i+len-1);\n                int b=sub_hash(i+len,i+2*len-1);\n                if(a==b){\n                    if(res.find(a)==res.end()){\n                        res.insert(a);\n                        ans++;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n};"209    },210    {211        "title": "Find Duplicate Subtrees",212        "algo_input": "Given the root&nbsp;of a binary tree, return all duplicate subtrees.\n\nFor each kind of duplicate subtrees, you only need to return the root node of any one of them.\n\nTwo trees are duplicate if they have the same structure with the same node values.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,4,null,2,4,null,null,4]\nOutput: [[2,4],[4]]\n\n\nExample 2:\n\nInput: root = [2,1,1]\nOutput: [[1]]\n\n\nExample 3:\n\nInput: root = [2,2,2,3,null,3,null]\nOutput: [[2,3],[3]]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of the nodes in the tree will be in the range [1, 10^4]\n\t-200 &lt;= Node.val &lt;= 200\n\n",213        "solution_py": "class Solution:\n    def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n        ans = []\n        path_map = {}\n        \n        def dfs(node):\n            if not node:\n                return \"#\"\n            \n            path = \",\".join([str(node.val), dfs(node.left), dfs(node.right)])\n            \n            if path in path_map:\n                path_map[path] += 1\n                if  path_map[path] == 2:\n                    ans.append(node)\n            else:\n                path_map[path] = 1\n                \n            return path\n        \n        \n        dfs(root)\n        return ans",214        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {TreeNode[]}\n */\nvar findDuplicateSubtrees = function(root) {\n    let stack = [];\n    let result = [];\n    let hashTable = {};\n    stack.push(root);\n    while (stack.length) {\n        let node = stack.pop();\n        let treeToArr = dfsArr(node);\n        if (node.right) {\n            stack.push(node.right);\n        }\n        if (node.left) {\n            stack.push(node.left);\n        }\n\t\t// If sub tree has not been seen, set to one.\n\t\t// If sub tree has been seen, increment number.\n        hashTable[treeToArr] = hashTable[treeToArr] ? \n            { num: hashTable[treeToArr].num + 1, ref: node} :\n            { num: 1, ref: node};\n    }\n\t// Builds result array with duplicate trees seen\n    for (let i in hashTable) {\n        if (hashTable[i].num > 1) {\n            result.push(hashTable[i].ref);\n        }\n    }\n    return result;\n};\n\n// Post order of subtree stored in array\nfunction dfsArr (node) {\n    let stack = [];\n    let result = [];\n    stack.push(node);\n    while (stack.length) {\n        let node = stack.pop();\n        node ? result.push(node.val) : result.push(null);\n        if (!node) continue;\n        if (node.right) {\n            stack.push(node.right);\n        } else {\n            stack.push(null);\n        }\n        if (node.left) {\n            stack.push(node.left);\n        } else {\n            stack.push(null);\n        }\n    }\n    return result;\n}",215        "solution_java": "/**\n * Definition for a binary tree node.\n * public class TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() {}\n * TreeNode(int val) { this.val = val; }\n * TreeNode(int val, TreeNode left, TreeNode right) {\n * this.val = val;\n * this.left = left;\n * this.right = right;\n * }\n * }\n */\nclass Solution {\n    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {\n        List<TreeNode> list = new ArrayList<TreeNode>();\n        HashSet<String> hashes = new HashSet<String>();\n        HashSet<String> added = new HashSet<String>();\n\n        // for each node, perform a dfs traversal and generate a hash\n        // check if the hash already exists in a set,\n        // if it does, get the treenode and add it to the list\n        Stack<TreeNode> s = new Stack<TreeNode>();\n\n        s.add(root);\n        while(!s.isEmpty()){\n            TreeNode tmp = s.pop();\n            dfs(tmp, \"\", tmp, list, hashes, added);\n\n            if(tmp.left != null){\n                s.add(tmp.left);\n            }\n            if(tmp.right != null){\n                s.add(tmp.right);\n            }\n        }\n\n        return list;\n\n    }\n\n    public void dfs(TreeNode parent, String hash, TreeNode root, List<TreeNode> list, HashSet<String> set, HashSet<String> added){\n\n        Stack<TreeNode> stack = new Stack<TreeNode>();\n\n        stack.add(root);\n        //String hash = \"\";\n        hash += root.val + \"ROOT,\";\n        while(!stack.isEmpty()){\n            TreeNode tmp = stack.pop();\n            //hash += tmp.val + \",\";\n\n            if(tmp.left != null){\n                hash += tmp.left.val + \"L,\";\n                stack.add(tmp.left);\n            }\n            else{\n                hash+= \"NULLL,\";\n            }\n            if(tmp.right != null){\n                hash += tmp.right.val + \"R,\";\n                stack.add(tmp.right);\n            }\n            else{\n                hash+=\"NULLR,\";\n            }\n            if(tmp.left == null && tmp.right == null && stack.isEmpty()){\n                if(set.contains(hash)){\n                    if(!added.contains(hash)){\n                        list.add(parent);\n                        added.add(hash);\n                    }\n                }\n                else{\n                    set.add(hash);\n                }\n                return;\n            }\n\n        }\n    }\n}",216        "solution_c": "class Solution {\npublic:\n    unordered_map<string,int> dp ;\n    vector<TreeNode*> ans ;\n\n    string solve(TreeNode * root){\n        if(!root) return \"\" ;\n\n        string left = solve(root->left) ;\n        string right = solve(root->right) ;\n\n        string code = to_string(root->val) + \" \" + left + \" \" + right ;\n        if(dp[code] == 1) ans.push_back(root) ;\n        dp[code]++ ;\n\n        return code ;\n    }\n\n    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {\n        string dummy = solve(root) ;\n        return ans ;\n    }\n};"217    },218    {219        "title": "Best Time to Buy and Sell Stock III",220        "algo_input": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\n\nFind the maximum profit you can achieve. You may complete at most two transactions.\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n\n&nbsp;\nExample 1:\n\nInput: prices = [3,3,5,0,0,3,1,4]\nOutput: 6\nExplanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n\nExample 2:\n\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n\n\nExample 3:\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 105\n\t0 &lt;= prices[i] &lt;= 105\n\n",221        "solution_py": "class Solution:\n    def maxProfit(self, prices: List[int]) -> int:\n        buy1, sell1, buy2, sell2 = -inf,0,-inf,0\n        for price in prices:\n            buy1 = max(buy1,-price)\n            sell1 = max(sell1,price+buy1)\n            \n            buy2 = max(buy2,sell1-price)\n            sell2 = max(sell2,price+buy2)\n        return sell2",222        "solution_js": "var maxProfit = function(prices) {\n  if(prices.length == 0) return 0\n  \n  let dp = new Array(prices.length).fill(0);\n  let min = prices[0];\n  let max = 0;\n  for (let i = 1; i < prices.length; i++) {\n    min = Math.min(min, prices[i]);  // or Math.min(min, prices[i] - dp[i]) , FYI: dp[i] is 0\n    max = Math.max(max, prices[i] - min);\n    dp[i] = max;\n  }\n  \n  // 1st run dp = [0,0,2,2,2,3,3,4];\n  \n  min = prices[0];\n  max = 0;\n  for (let i = 1; i < prices.length; i++) {\n    min = Math.min(min, prices[i] - dp[i]); // substract dp[i]  = current price - what profit we made during 1st run.\n    max = Math.max(max, prices[i] - min);\n    dp[i] = max;\n  }\n  \n  // 2nd run dp = [0,0,2,2,2,5,5,6];\n  \n  return dp.pop();\n};",223        "solution_java": "class Solution {\n    public int maxProfit(int[] prices) {\n        \n       int n = prices.length;\n        int maxSellProfit = 0;\n        int min = prices[0];\n        int[] maxSellArr = new int[n];\n        int i = 1;\n        \n        while(i < n){\n            if(prices[i] < min){\n                min = prices[i];\n            }\n            maxSellArr[i] = Math.max(maxSellArr[i-1],prices[i] - min);  \n            \n            i++;\n        }\n        int[] maxBuyArr = new int[n];\n        int j = n-2;\n        int max = prices[n-1];\n        while(j >= 0){\n            if(prices[j] > max){\n                max = prices[j];\n            }\n            maxBuyArr[j] = Math.max(maxBuyArr[j+1],max - prices[j]);\n            \n            j--;\n        }\n        int maxProfitTwoTrans = 0;\n        for(int k = 0; k < n; k++){\n            maxProfitTwoTrans = Math.max(maxProfitTwoTrans,maxBuyArr[k] + maxSellArr[k]);\n        }\n        return maxProfitTwoTrans;\n    }\n}",224        "solution_c": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int n=prices.size();\n        vector<int> left(n);\n        vector<int> right(n);\n        int mini=INT_MAX;\n        int ans1=0;\n        for(int i=0;i<n;i++)\n        {\n            mini=min(mini,prices[i]);\n            ans1=max(ans1,prices[i]-mini);\n            left[i]=ans1;\n        }\n        int maxi=INT_MIN;\n        int ans2=0;\n        for(int i=n-1;i>=0;i--)\n        {\n            maxi=max(maxi,prices[i]);\n            ans2=max(ans2,maxi-prices[i]);\n            right[i]=ans2;\n        }\n        int ans3=0;\n        for(int i=0;i<n;i++)\n        {\n            ans3=max(ans3,left[i]+right[i]);\n        }\n        return ans3;\n    }\n};"225    },226    {227        "title": "Best Time to Buy and Sell Stock",228        "algo_input": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\n\nYou want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\n\nReturn the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.\n\n&nbsp;\nExample 1:\n\nInput: prices = [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.\n\n\nExample 2:\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transactions are done and the max profit = 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= prices.length &lt;= 105\n\t0 &lt;= prices[i] &lt;= 104\n\n",229        "solution_py": "class Solution:\n    def maxProfit(self,prices):\n        left = 0 #Buy\n        right = 1 #Sell\n        max_profit = 0\n        while right < len(prices):\n            currentProfit = prices[right] - prices[left] #our current Profit\n            if prices[left] < prices[right]:\n                max_profit =max(currentProfit,max_profit)\n            else:\n                left = right\n            right += 1\n        return max_profit",230        "solution_js": "var maxProfit = function(prices) {\n    let L = 0;\n    let result = 0;\n    let length = prices.length;\n    for( let R = 1 ;R < length; R++){\n        if(prices[L] > prices[R]){\n            L = R;\n        }else {\n                result = Math.max(result, prices[R] - prices[L]);\n\n        }\n    }\n    return result;\n};",231        "solution_java": "class Solution {\n    public int maxProfit(int[] prices) {\n        int lsf = Integer.MAX_VALUE;\n        int op = 0;\n        int pist = 0;\n\n        for(int i = 0; i < prices.length; i++){\n            if(prices[i] < lsf){\n                lsf = prices[i];\n            }\n            pist = prices[i] - lsf;\n            if(op < pist){\n                op = pist;\n            }\n        }\n        return op;\n    }\n}",232        "solution_c": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        int lsf = INT_MAX;\n        int op = 0;\n        int pist = 0;\n\n        for(int i = 0; i < prices.size(); i++){\n            if(prices[i] < lsf){\n                lsf = prices[i];\n            }\n            pist = prices[i] - lsf;\n            if(op < pist){\n                op = pist;\n            }\n        }\n        return op;\n    }\n};"233    },234    {235        "title": "Binary Tree Right Side View",236        "algo_input": "Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\n\n\nExample 2:\n\nInput: root = [1,null,3]\nOutput: [1,3]\n\n\nExample 3:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 100].\n\t-100 &lt;= Node.val &lt;= 100\n\n",237        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n\n        def dfs(root, d):\n\n            if not root: return\n\n            if self.maxi < d:\n                self.res.append(root.val)\n                self.maxi = d\n\n            dfs(root.right, d+1)\n            dfs(root.left, d+1)\n\n        self.res, self.maxi = [], 0\n        dfs(root, 1)\n        return self.res\n\n        # An Upvote will be encouraging",238        "solution_js": "var rightSideView = function(root) {\n    if(!root) return [];\n    let ans = [];\n    let queue = [root];\n\t\n    while(queue.length > 0){\n        let queueLength = queue.length;\n\t\t\n\t\t// As we are giving priority to right node, \n\t\t// first node will always be the one that we want in output \n        ans.push(queue[0].val);\n\t\t\n        for(let i = 0;i<queueLength;i++){\n\t\t\t// Ignore TC of queue.shift (assuming we have queue implementation with O(1) TC)\n            let current = queue.shift();\n\t\t\t\n\t\t\t// Always give priority to right node\n            if(current.right) queue.push(current.right);\n            if(current.left) queue.push(current.left);\n        }\n    }\n    return ans;\n};",239        "solution_java": "class Solution {\n    // Utility Function of RightSideView\n    public void rightView(TreeNode curr, List<Integer> list, int level) {\n        // if, current is null, return\n        if(curr == null) {\n            return;\n        }\n        \n        // if, level = list size\n        // add current val to list\n        if(level == list.size()) {\n            list.add(curr.val);\n        }\n        \n        // recursive call for right side view\n        rightView(curr.right, list, level + 1);\n        // recursive call for left side view\n        rightView(curr.left, list, level + 1);\n    }\n    \n    // Binary Tree Right Side View Function\n    public List<Integer> rightSideView(TreeNode root) {\n        // create a list\n        List<Integer> result = new ArrayList<>();\n        // call right view function\n        rightView(root, result, 0);\n        return result;\n    }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(h) h = height of binary tree\n*/",240        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    void solve(TreeNode* root, vector<int> &ans, int level)\n    {\n        // base case\n        if (root == NULL)\n        {\n            return ; \n        }\n\n        // we entered a new level \n        if (level == ans.size())\n        {\n            ans.push_back(root -> val) ; \n        }\n\n        solve(root -> right, ans, level + 1) ; \n        solve(root -> left, ans, level + 1 ) ; \n    }\n    vector<int> rightSideView(TreeNode* root) {\n        vector<int> ans ; \n        int level = 0 ; \n\n        solve(root, ans, level) ;\n        \n        return ans ; \n    }\n};"241    },242    {243        "title": "Race Car",244        "algo_input": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):\n\n\n\tWhen you get an instruction 'A', your car does the following:\n\n\t\n\t\tposition += speed\n\t\tspeed *= 2\n\t\n\t\n\tWhen you get an instruction 'R', your car does the following:\n\t\n\t\tIf your speed is positive then speed = -1\n\t\totherwise speed = 1\n\t\n\tYour position stays the same.\n\n\nFor example, after commands \"AAR\", your car goes to positions 0 --&gt; 1 --&gt; 3 --&gt; 3, and your speed goes to 1 --&gt; 2 --&gt; 4 --&gt; -1.\n\nGiven a target position target, return the length of the shortest sequence of instructions to get there.\n\n&nbsp;\nExample 1:\n\nInput: target = 3\nOutput: 2\nExplanation: \nThe shortest instruction sequence is \"AA\".\nYour position goes from 0 --&gt; 1 --&gt; 3.\n\n\nExample 2:\n\nInput: target = 6\nOutput: 5\nExplanation: \nThe shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --&gt; 1 --&gt; 3 --&gt; 7 --&gt; 7 --&gt; 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= target &lt;= 104\n\n",245        "solution_py": "class Solution:\n    def racecar(self, target: int) -> int:\n        q = [(0, 1)]\n        steps = 0\n\n        while q:\n            num = len(q)\n            for i in range(num):\n                pos, speed = q.pop(0)\n                if pos == target:\n                    return steps\n                q.append((pos+speed, speed*2))\n                rev_speed = -1 if speed > 0 else 1\n                if (pos+speed) < target and speed < 0 or (pos+speed) > target and speed > 0:\n                    q.append((pos, rev_speed))\n            steps += 1",246        "solution_js": "var racecar = function(target) {\n    let queue = [[0, 1, 0]];\n    let visited = new Set(['0,1']);\n\n    while(queue.length > 0) {\n        const [pos, speed, distance] = queue.shift();\n\n        if(pos === target) return distance;\n\n        const posA = pos + speed;\n        const speedA = speed * 2;\n        const keyA = posA + ',' + speedA;\n\n        const posR = pos;\n        const speedR = speed > 0 ? -1 : 1;\n        const keyR = posR + ',' + speedR;\n\n        if(!visited.has(keyA) && posA >= 0 && posA <= 2*target) {\n            visited.add(keyA);\n            queue.push([posA, speedA, distance + 1]);\n        }\n\n        if(!visited.has(keyR) && posR >= 0 && posR <= 2*target) {\n            visited.add(keyR);\n            queue.push([posR, speedR, distance + 1]);\n        }\n    }\n};",247        "solution_java": "class Solution {\n    public int racecar(int target) {\n        Queue<int[]> queue = new LinkedList<>();\n        queue.add(new int[]{0, 1, 0});\n        Set<String> visited = new HashSet<>();\n\n        while(!queue.isEmpty()){\n            int[] item = queue.poll();\n            int currPos = item[0];\n            int currSpeed = item[1];\n            int distance = item[2];\n\n            if(currPos == target)\n                return distance;\n\n            // Choosing A\n            int nextPos = currPos + currSpeed;\n            int nextSpeed = currSpeed * 2;\n            String posSpeed = new StringBuilder().append(nextPos).append(\",\").append(nextSpeed).toString();\n\n            // If the particular state (position & speed) is not encountered earlier then we explore that state\n            // And we also check if the nextPos is not beyond twice the size of target, then there is no point in exploring that route\n            if(!visited.contains(posSpeed) && Math.abs(nextPos) < 2 * target){\n                visited.add(posSpeed);\n                queue.add(new int[]{nextPos, nextSpeed, distance + 1});\n            }\n\n            // Choosing R\n            // We go in reverse only when we are moving away from the target in the positive or in the negative direction\n            if((currPos + currSpeed > target && currSpeed > 0) || (currPos + currSpeed < target && currSpeed < 0)) {\n                nextSpeed = currSpeed > 0 ? -1 : 1;\n                posSpeed = new StringBuilder().append(currPos).append(\",\").append(nextSpeed).toString();\n\n                if(!visited.contains(posSpeed) && Math.abs(currPos) < 2 * target){\n                    visited.add(posSpeed);\n                    queue.add(new int[]{currPos, nextSpeed, distance + 1});\n                }\n            }\n        }\n        return -1;\n    }\n}",248        "solution_c": "struct Position {\n    long long int pos;\n    long long int speed;\n    long long int moves;\n\n    Position(int pos, int speed, int moves) {\n        this -> pos = pos;\n        this -> speed = speed;\n        this -> moves = moves;\n    }\n};\n\nclass Solution {\npublic:\n    int racecar(int target) {\n        queue<Position> q;\n        Position p(0, 1, 0);\n        q.push(p);\n\n        set<pair<long long int, long long int>> s;\n\n        while(!q.empty()) {\n            Position u = q.front();\n            q.pop();\n\n            if(u.pos == target) return u.moves;\n\n            if(s.find({u.pos, u.speed}) != s.end()) continue;\n            else {\n                s.insert({u.pos, u.speed});\n\n                // only cases when you might need to move backwards\n                if((u.pos + u.speed > target && u.speed > 0) ||\n                   (u.pos + u.speed < target && u.speed < 0)) {\n                    long long int speed = u.speed > 0 ? -1 : 1;\n                    Position bkwd(u.pos, speed, u.moves + 1);\n                    q.push(bkwd);\n                }\n\n                Position fwd(u.pos + u.speed, 2 * u.speed, u.moves + 1);\n                q.push(fwd);\n            }\n        }\n\n        return -1;\n    }\n};"249    },250    {251        "title": "Print Binary Tree",252        "algo_input": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:\n\n\n\tThe height of the tree is height&nbsp;and the number of rows m should be equal to height + 1.\n\tThe number of columns n should be equal to 2height+1 - 1.\n\tPlace the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).\n\tFor each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].\n\tContinue this process until all the nodes in the tree have been placed.\n\tAny empty cells should contain the empty string \"\".\n\n\nReturn the constructed matrix res.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2]\nOutput: \n[[\"\",\"1\",\"\"],\n&nbsp;[\"2\",\"\",\"\"]]\n\n\nExample 2:\n\nInput: root = [1,2,3,null,4]\nOutput: \n[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n&nbsp;[\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n&nbsp;[\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 210].\n\t-99 &lt;= Node.val &lt;= 99\n\tThe depth of the tree will be in the range [1, 10].\n\n",253        "solution_py": "class Solution:\n    def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:\n        def height(root):\n            if not root:\n                return 0\n            return 1 + max(height(root.left), height(root.right))\n        # 1. Find height of BT\n        h = height(root) - 1\n\n        rows = h + 1\n        cols = pow(2, h + 1) -1\n        # 2. Create a res matrix and intialize with \"\"\n        res = [[\"\" for _ in range(cols)] for _ in range(rows)]\n\n        def dfs(root, r , c):\n            if not root:\n                return\n\n            res[r][c] = str(root.val)\n            dfs(root.left, r + 1, c - pow(2, h - r - 1))\n            dfs(root.right, r + 1, c + pow(2, h - r - 1))\n            return\n        # 3. Fill the matrix recursively\n        dfs(root, 0, (cols - 1) // 2)\n        return res",254        "solution_js": "/**\n * @param {TreeNode} root\n * @return {string[][]}\n */\nvar printTree = function(root) {\n\t// find the height of the tree\n    const m = getHeight(root)\n    const height = m - 1\n    const n = 2**(height+1)-1\n    // create an empty m by n matrix    \n    const ans = []\n    for (let i = 0; i<m; i++) {\n        ans.push(Array(n).fill(\"\"))\n    }\n    // insert the root\n    ans[0][(n-1)/2] = root.val.toString()\n\t// insert the rest of the nodes\n    format(root,0,(n-1)/2,ans,height)\n    return ans\n};\n\nfunction getHeight(node) {\n    if (!node) return 0\n    const leftHeight = getHeight(node.left)+1\n    const rightHeight = getHeight(node.right)+1\n    return Math.max(leftHeight,rightHeight) // take the subtree with bigger height\n}\n\nfunction format(node,r,c,ans,height) {\n    const offset = 2**(height-r-1) // calculate the common offset\n    if (node.left) {\n        ans[r+1][c-offset] = node.left.val.toString()\n        format(node.left,r+1,c-offset,ans,height) // recurse left node\n    }\n    if (node.right) {\n        ans[r+1][c+offset] = node.right.val.toString()\n        format(node.right,r+1,c+offset,ans,height) // recurse right node\n    }\n}",255        "solution_java": "class Solution {\n    public List<List<String>> printTree(TreeNode root) {\n        List<List<String>> res = new ArrayList();\n\n        int height = getHeight(root);\n        int row = height + 1;\n        int column = (int) Math.pow(2, height+1) - 1;\n\n        for(int k=0; k<row; k++){\n            List<String> list = new ArrayList();\n            for(int i=0; i<column; i++){\n                list.add(\"\");\n            }\n            res.add(list);\n        }\n\n        int left = 0;\n        int right = column-1;\n        int level=0;\n        print(res, left, right, level, root);\n\n        return res;\n    }\n    public void print(List<List<String>> res, int left, int right, int level, TreeNode root){\n        if(root == null) return;\n        int mid = left+(right-left)/2;\n        res.get(level).set(mid, String.valueOf(root.val));\n\n        print(res, left, mid-1, level+1, root.left);\n        print(res, mid+1, right, level+1, root.right);\n    }\n    public int getHeight(TreeNode root){\n        if (root==null) return -1;\n        int left = getHeight(root.left);\n        int right = getHeight(root.right);\n\n        return Math.max(left, right)+1;\n    }\n}",256        "solution_c": "class Solution {\npublic:\n    vector<vector<string>> res;\n\n    int height(TreeNode* root){\n        if(!root)\n            return 0;\n        return 1 + max(height(root->left), height(root->right));\n    }\n\n    void fill(TreeNode* root, int r, int c, int h){\n        if(!root)\n            return;\n        res[r][c] = to_string(root->val);\n        fill(root->left, r + 1, c - pow(2, h - r - 1), h);\n        fill(root->right, r + 1, c + pow(2, h - r - 1), h);\n    }\n\n    vector<vector<string>> printTree(TreeNode* root) {\n        int h = height(root);\n        int c = pow(2, h) - 1;\n        res.resize(h, vector<string>(c, \"\"));\n        fill(root, 0, (c - 1) / 2, h - 1);\n        return res;\n    }\n};"257    },258    {259        "title": "Largest Submatrix With Rearrangements",260        "algo_input": "You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.\n\nReturn the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.\n\n&nbsp;\nExample 1:\n\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput: 4\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.\n\n\nExample 2:\n\nInput: matrix = [[1,0,1,0,1]]\nOutput: 3\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.\n\n\nExample 3:\n\nInput: matrix = [[1,1,0],[1,0,1]]\nOutput: 2\nExplanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m * n &lt;= 105\n\tmatrix[i][j] is either 0 or 1.\n\n",261        "solution_py": "from collections import Counter\n\nclass Solution:\n    def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n        M = len(matrix)\n        N = len(matrix[0])\n\n        colcons = [] # preprocess columns\n        for c in range(N):\n            cons = []\n            s = 0\n            for r in range(M):\n                if not matrix[r][c]:\n                    s = 0\n                else:\n                    s += 1\n                cons.append(s)\n            colcons.append(cons)\n        # colcons[c][r] is how much 1's we'll get if we start from column c at row r and go up\n\n        best = 0\n        for r in range(M):\n            # try r as the lowest row\n            C = Counter(colcons[c][r] for c in range(N))\n            vs = sorted(C.keys(), reverse=True)\n            cs = accumulate(C[v] for v in vs)\n            for v,c in zip(vs,cs):\n                best = max(best,v*c)\n        return best",262        "solution_js": "var largestSubmatrix = function(matrix) {\n    let n = matrix.length;\n    let m = matrix[0].length;\n    let col = new Array(m).fill(0);\n    let res = 0;\n    for(let i = 0; i < n; i++){\n        for(let j = 0; j < m; j++){\n            if(matrix[i][j]) col[j]++;\n            else col[j] = 0;\n        }\n        res = counting(col, res);\n    }\n    return res;\n};\n\n\n//if you did 84. Largest Rectangle in Histogram, you can replace the following part with your 84 answer and don't forget to sort.\nlet counting = function(column, max) {\n     let sorted = [...column].sort((a,b)=>b-a);\n     let k, j;\n    for (let i=0; i < sorted.length ;i++){\n        if(sorted[i]===sorted[i-1]) continue;  \n        k = j = i;\n        while(sorted[j]&&sorted[j]>=sorted[i]) j++;\n        while(sorted[k]&&sorted[k]>=sorted[i]) k--;\n        max = Math.max(sorted[i]*Math.abs(k-j+1), max);\n    }\n    return max;\n};",263        "solution_java": "class Solution {\n    public int largestSubmatrix(int[][] matrix) {\n         //Store matrix[i][j]= total number of consecutive 1s along column j ending at index (i,j).\n        for(int i=1;i<matrix.length;i++)  //Start from row 1 because row 0 will be unaffected as no row above it.\n        {\n            for(int j=0;j<matrix[i].length;j++)\n            {\n                if(matrix[i][j]==0) continue;\n                else  matrix[i][j]=matrix[i-1][j]+1;\n            }\n        }\n        \n        int maxSize=0;\n        for(int i=0;i<matrix.length;i++)\n        {\n           \n            PriorityQueue<Integer> pq  =  new PriorityQueue<Integer>();// minheap\n            for(int j=0;j<matrix[i].length;j++)\n            {\n                if(matrix[i][j]>0)  pq.add(matrix[i][j]); // Add all the entries from row i in minheap\n            }\n            int size=0,curr=0;\n            /*\n                In current row, total entries with value k or greater than k will contribute the squares of\n\t\t\t\tsize=k*(number of squares of size k or greater than k).Largest square ending at current\n\t\t\t\trow= k * (all entries greater than or equal to k in current row) for all ks in current row\n            */\n            while(!pq.isEmpty())  \n            {\n                curr=pq.peek(); \n                \n                size=curr*pq.size();\n                maxSize=Math.max(maxSize,size);\n                \n                pq.poll();\n            }\n        }\n        return maxSize;\n        \n        \n        \n    }\n}",264        "solution_c": "class Solution {\npublic:\n    int largestSubmatrix(vector<vector<int>>& matrix) {\n        int m = matrix.size(), n = matrix[0].size();\n        int ans = 0;\n        vector<int> height(n, 0);\n\t\t\n\t\t// view each row and its above as pillars \n        for(int i = 0; i < m; ++i){\n\t\t\t// calculate heights\n            for(int j = 0; j < n; ++j){\n                if(matrix[i][j] == 0) height[j] = 0;\n                else height[j] += 1;\n            }\n\t\t\t\n\t\t\t// sort pillars\n            vector<int> order_height = height;\n            sort(order_height.begin(), order_height.end());\n\t\t\t\n\t\t\t// iterate to get the maxium rectangle\n            for(int j = 0; j < n; ++j){\n                ans = max(ans, order_height[j] * (n - j));\n            }\n        }\n        return ans;\n    }\n};"265    },266    {267        "title": "Minimize Malware Spread",268        "algo_input": "You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\n\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.\n\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n\nNote that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.\n\n&nbsp;\nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\nExample 2:\nInput: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput: 0\nExample 3:\nInput: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput: 1\n\n&nbsp;\nConstraints:\n\n\n\tn == graph.length\n\tn == graph[i].length\n\t2 &lt;= n &lt;= 300\n\tgraph[i][j] is 0 or 1.\n\tgraph[i][j] == graph[j][i]\n\tgraph[i][i] == 1\n\t1 &lt;= initial.length &lt;= n\n\t0 &lt;= initial[i] &lt;= n - 1\n\tAll the integers in initial are unique.\n\n",269        "solution_py": "class Solution:\n    def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n        n = len(graph)\n        uf = UnionFind(n)\n        for i in range(n):\n            for j in range(n):\n                if graph[i][j]:\n                    uf.union(i, j)\n\n        max_remove = 0\n\n        initial.sort()\n        min_index = initial[0]\n        for i in range(len(initial)):\n            cur_remove = 0\n            linked = False\n            for j in range(len(initial)):\n                if i == j: continue\n                if uf.find(initial[i]) == uf.find(initial[j]):\n                    linked = True\n            if not linked:\n                cur_remove = uf.rank[uf.find(initial[i])]\n                if max_remove < cur_remove:\n                    max_remove = cur_remove\n                    min_index = initial[i]\n\n        return min_index\n\nclass UnionFind:\n    def __init__(self, size):\n        self.parent = {}\n        self.rank = {}\n        for i in range(size):\n            self.parent[i] = i\n            self.rank[i] = 1\n\n    def find(self, x):\n        if x != self.parent[x]:\n            x = self.find(self.parent[x])\n        return x\n\n    def union(self, x, y):\n        px, py = self.find(x), self.find(y)\n        if px == py: return\n        if self.rank[px] >= self.rank[py]:\n            self.parent[py] = px\n            self.rank[px] += self.rank[py]\n        else:\n            self.parent[px] = py\n            self.rank[py] += self.rank[px]",270        "solution_js": "var minMalwareSpread = function(graph, initial) {\n  let n = graph.length, uf = new UnionFind(n);\n  for (let i = 0; i < n; i++) {\n    for (let j = i + 1; j < n; j++) {\n      if (graph[i][j]) uf.union(i, j);\n    }\n  }\n  \n  // Get number of nodes in each connected component\n  let nodesCount = {};\n  for (let i = 0; i < n; i++) {\n    let parent = uf.find(i);\n    nodesCount[parent] = (nodesCount[parent] || 0) + 1;\n  }\n  \n  // Find the initial node connected to the most amount of other nodes, where it is the only malware infected node in its group.\n  let max = 0, res = Infinity;\n  for (let node of initial) {\n    let malwareNodes = malwareConnected(node);\n    let parent = uf.find(node);\n    let nodesAffected = malwareNodes === 1 ? nodesCount[parent] : 0;\n    if (nodesAffected > max || (nodesAffected === max && node < res)) {\n      res = node;\n      max = nodesAffected;\n    }\n  }\n  return res;\n  \n  function malwareConnected(node) { // gets number of malware infected nodes connected to node\n    let count = 0;\n    for (let malware of initial) {\n      if (uf.isConnected(node, malware)) count++;\n    }\n    return count;\n  }\n};\n\nclass UnionFind {\n  constructor(size) {\n    this.rank = Array(size);\n    this.root = Array(size);\n    for (let i = 0; i < size; i++) {\n      this.rank[i] = 1;\n      this.root[i] = i;\n    }\n  }\n  find(x) {\n    if (this.root[x] === x) return x;\n    return this.root[x] = this.find(this.root[x]);\n  }\n  union(x, y) {\n    let rootX = this.find(x), rootY = this.find(y);\n    if (rootX === rootY) return false;\n    if (this.rank[rootX] < this.rank[rootY]) this.root[rootX] = rootY;\n    else if (this.rank[rootX] > this.rank[rootY]) this.root[rootY] = rootX;\n    else {\n      this.root[rootY] = rootX;\n      this.rank[rootX]++;\n    }\n    return true;\n  }\n  isConnected(x, y) {\n    return this.find(x) === this.find(y);\n  }\n}",271        "solution_java": "class Solution {\n    int[]parent;\n    int[]size;\n\n    public int minMalwareSpread(int[][] graph, int[] initial) {\n        parent = new int[graph.length];\n        size = new int[graph.length];\n        for(int i=0;i<parent.length;i++){\n            parent[i] = i;\n            size[i] = 1;\n        }\n\n        for(int i=0;i<graph.length;i++){\n            for(int j=0;j<graph[0].length;j++){\n                if(i != j && graph[i][j] == 1){\n                    unionHelper(i,j);\n                }\n            }\n        }\n\n        int []imap = new int[graph.length];\n        for(int val : initial){\n            int ri = find(val);\n            imap[ri]++;\n        }\n\n        int ans_i = -1;\n        int ans_size = 0;\n        for(int i:initial){\n            int ri = find(i);\n            if(imap[ri] == 1){\n                if(ans_i == -1){\n                        ans_i = i;\n                        ans_size = size[ri];\n                }else if(size[ri] > ans_size){\n                        ans_i = i;\n                        ans_size = size[ri];\n                }else if(size[ri] == ans_size){\n                    if(i < ans_i){\n                        ans_i = i;\n                        ans_size = size[ri];\n                    }\n                }\n            }\n        }\n\n        if(ans_i == -1){\n            ans_i = graph.length;\n            for(int i : initial){\n                if(i < ans_i){\n                    ans_i = i;\n                }\n            }\n        }\n\n        return ans_i;\n\n    }\n\n    int find(int x){\n        if(parent[x] == x){\n            return x;\n        }else{\n            parent[x] = find(parent[x]);\n            return parent[x];\n        }\n    }\n\n    void unionHelper(int x,int y){\n        int xl = find(x);\n        int yl = find(y);\n\n        if(size[xl] < size[yl]){\n            parent[xl] = yl;\n            size[yl] += size[xl];\n        }else{\n            parent[yl] = xl;\n            size[xl] += size[yl];\n        }\n    }\n}",272        "solution_c": "class Solution {\npublic:\n    void dfs(int i,int n,vector<bool> &visited,vector<int>&cur,map<int,int>& ind,int &cnt,map<int,vector<int> >&mp)\n    {\n        if(!visited[i])\n        {\n            visited[i]=true;\n            cur.push_back(i);\n            ind[i]=cnt;\n            for(int j=0;j<mp[i].size();j++)\n            {\n                dfs(mp[i][j],n,visited,cur,ind,cnt,mp);\n            }\n        }\n    }\n    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n         int n=graph.size();\n         map<int,vector<int> > mp; //Adjacency list creation for the graph\n         for(int i=0;i<n;i++)\n         {\n             for(int j=0;j<n;j++)\n             {\n                 if(i!=j && graph[i][j]==1)\n                     mp[i].push_back(j);\n\n             }\n         }\n        map<int,int> ind; // This map is for storing the component number to which a particular node belongs to\n        vector<vector<int> > v; //Store all the connected components\n        vector<bool> visited(n,false); //Visited array to keep track of the visited nodes\n        int cnt=0;//Current component number\n        for(int i=0;i<n;i++)\n        {\n            if(!visited[i])\n            {\n                vector<int> cur;\n                dfs(i,n,visited,cur,ind,cnt,mp);//Dfs call for getting single components\n                cnt++;\n                v.push_back(cur);\n            }\n        }\n    map<int,vector<int> > help; //This map tells that how many node that is present in inital vector are of same component\n        for(int i=0;i<initial.size();i++)\n        {\n            int index=ind[initial[i]];\n            help[index].push_back(initial[i]);\n        }\n        int sz=INT_MIN;\n        int ans=n;//This loop is based on the logic described above\n        for(auto it=help.begin();it!=help.end();it++)\n        {\n            if(help[it->first].size()==1)\n            {\n                int cover=v[it->first].size();\n                if(cover>sz)\n                {\n                    sz=cover;\n                    ans=help[it->first][0];\n                }\n                else if(cover==sz)\n                {\n                    if(help[it->first][0]<ans)\n                        ans=help[it->first][0];\n                }\n            }\n        }\n        if(ans!=n)\n            return ans;\n        for(int i=0;i<initial.size();i++)\n            ans=min(ans,initial[i]);\n        return ans;\n\n    }\n};"273    },274    {275        "title": "Minimum Remove to Make Valid Parentheses",276        "algo_input": "Given a string s of '(' , ')' and lowercase English characters.\n\nYour task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.\n\nFormally, a parentheses string is valid if and only if:\n\n\n\tIt is the empty string, contains only lowercase characters, or\n\tIt can be written as AB (A concatenated with B), where A and B are valid strings, or\n\tIt can be written as (A), where A is a valid string.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"lee(t(c)o)de)\"\nOutput: \"lee(t(c)o)de\"\nExplanation: \"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.\n\n\nExample 2:\n\nInput: s = \"a)b(c)d\"\nOutput: \"ab(c)d\"\n\n\nExample 3:\n\nInput: s = \"))((\"\nOutput: \"\"\nExplanation: An empty string is also valid.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either'(' , ')', or lowercase English letter.\n\n",277        "solution_py": "class Solution:\n    def minRemoveToMakeValid(self, s) :\n        stack=[]\n        split_str=list(s)\n        for i in range(len(s)):\n            if s[i]=='(':\n                # if current char is '(' then push it to stack\n                stack.append(i)\n            elif s[i]==')':\n                # if current char is ')' then pop top of the stack\n                if len(stack) !=0:\n                    stack.pop()\n                else:\n                    # if our stack is empty then we can't pop so make  current char as ''\n                    split_str[i]=\"\"\n        for i in stack:\n            split_str[i]=\"\"\n        return '' .join(split_str)",278        "solution_js": "var minRemoveToMakeValid = function(s) {\n    let validity = 0;\n    for(let index = 0; index < s.length; index++) {\n        if(s[index] == ')') {\n            if(validity == 0) {\n                s = s.substring(0,index)+s.substring(index+1);\n                index--;\n            }\n            else {\n                validity--;\n            }\n        }\n        else if(s[index] == '(') {\n            validity++;\n        }\n    }\n    if(validity > 0) {\n        for(let index = s.length-1; index >= 0; index--) {\n            if(s[index] == '(') {\n                s = s.substring(0,index)+s.substring(index+1);\n                validity--;\n                if(validity === 0) break;\n            }\n        }\n    }\n    return s;\n};",279        "solution_java": "class Solution {\n    public String minRemoveToMakeValid(String s) {\n        Stack<Integer> stack = new Stack<>();\n        for(int i=0;i<s.length();i++) {\n            char ch = s.charAt(i);\n            if(Character.isAlphabetic(ch))\n                continue;\n            if(ch == '(')\n                stack.push(i);\n            else {\n                if(!stack.isEmpty() && s.charAt(stack.peek()) == '(')\n                    stack.pop();\n                else stack.push(i);\n            }\n        }\n\n        // if(stack.size() == 0) return \"\";\n\n        StringBuilder result = new StringBuilder();\n        HashSet<Integer> set = new HashSet<>(stack);\n        for(int i=0;i<s.length();i++)\n            if(!set.contains(i))\n                result.append(s.charAt(i));\n\n        return result.toString();\n    }\n}",280        "solution_c": "class Solution {\npublic:\n    string minRemoveToMakeValid(string s) {\n        int count = 0;\n        for(int i = 0; i < s.size(); i++)\n        {\n\n            if(s[i]=='(')\n            {\n                count++;\n            }\n            if(s[i]==')')\n            {\n                if(count==0)\n                {\n                    s[i]='*';\n                }\n                else\n                {\n                    count--;\n                }\n            }\n\n        }\n        if(count==0)\n        {\n            s.erase(remove(s.begin(), s.end(), '*'), s.end());\n            return s;\n        }\n        for(int i = s.size()-1; i >=0; i--)\n        {\n            if(s[i]=='(')\n            {\n                s[i]='*';\n                count--;\n            }\n            if(count==0)\n            {\n                s.erase(remove(s.begin(), s.end(), '*'), s.end());\n                return s;\n            }\n        }\n        return s;\n    }\n};"281    },282    {283        "title": "Powerful Integers",284        "algo_input": "Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.\n\nAn integer is powerful if it can be represented as xi + yj for some integers i &gt;= 0 and j &gt;= 0.\n\nYou may return the answer in any order. In your answer, each value should occur at most once.\n\n&nbsp;\nExample 1:\n\nInput: x = 2, y = 3, bound = 10\nOutput: [2,3,4,5,7,9,10]\nExplanation:\n2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32\n\n\nExample 2:\n\nInput: x = 3, y = 5, bound = 15\nOutput: [2,4,6,8,10,14]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= x, y &lt;= 100\n\t0 &lt;= bound &lt;= 106\n\n",285        "solution_py": "from math import log\nclass Solution:\n    def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n        if bound == 0:\n            return []\n        maxi = int(log(bound,max(x,2))) +1\n        maxj = int(log(bound,max(y,2))) +1\n        L = set()\n        for i in range(maxi):\n            for j in range(maxj):\n                if (t:=x**i +y**j) <= bound:\n                    L.add(t)\n                else:\n                    break\n        return list(L)",286        "solution_js": "var powerfulIntegers = function(x, y, bound) {\n    let ans = new Set()\n    for (let xi = 1; xi < bound; xi *= x) {\n        for (let yj = 1; xi + yj <= bound; yj *= y) {\n            ans.add(xi + yj)\n            if (y === 1) break\n        }\n        if (x === 1) break\n    }\n    return Array.from(ans)\n}",287        "solution_java": "class Solution {\n    public List<Integer> powerfulIntegers(int x, int y, int bound) {\n        HashSet<Integer> set = new HashSet<>();\n        for(int i = 1; i<bound; i*=x){\n            for(int j = 1; i+j <= bound; j*=y){\n                set.add(i+j);\n                if(y==1) break;\n            }\n            if(x==1) break;\n        }\n        return new ArrayList<>(set);\n    }\n}",288        "solution_c": "class Solution {\npublic:\n    vector<int> powerfulIntegers(int x, int y, int bound) {\n        unordered_set<int> s;\n       \n        for(int i=0; pow(x, i)<=bound; i++) {\n            for(int j=0; pow(x, i) + pow(y, j)<=bound; j++) {\n                s.insert(pow(x, i) + pow(y, j));\n                if(y == 1) break;\n            }\n            if(x == 1) break;\n        }\n        return vector<int> (s.begin(), s.end());\n    }\n};"289    },290    {291        "title": "Masking Personal Information",292        "algo_input": "You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.\n\nEmail address:\n\nAn email address is:\n\n\n\tA name consisting of uppercase and lowercase English letters, followed by\n\tThe '@' symbol, followed by\n\tThe domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character).\n\n\nTo mask an email:\n\n\n\tThe uppercase letters in the name and domain must be converted to lowercase letters.\n\tThe middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks \"*****\".\n\n\nPhone number:\n\nA phone number is formatted as follows:\n\n\n\tThe phone number contains 10-13 digits.\n\tThe last 10 digits make up the local number.\n\tThe remaining 0-3 digits, in the beginning, make up the country code.\n\tSeparation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way.\n\n\nTo mask a phone number:\n\n\n\tRemove all separation characters.\n\tThe masked phone number should have the form:\n\t\n\t\t\"***-***-XXXX\" if the country code has 0 digits.\n\t\t\"+*-***-***-XXXX\" if the country code has 1 digit.\n\t\t\"+**-***-***-XXXX\" if the country code has 2 digits.\n\t\t\"+***-***-***-XXXX\" if the country code has 3 digits.\n\t\n\t\n\t\"XXXX\" is the last 4 digits of the local number.\n\n\n&nbsp;\nExample 1:\n\nInput: s = \"LeetCode@LeetCode.com\"\nOutput: \"l*****e@leetcode.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\n\n\nExample 2:\n\nInput: s = \"AB@qq.com\"\nOutput: \"a*****b@qq.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.\n\n\nExample 3:\n\nInput: s = \"1(234)567-890\"\nOutput: \"***-***-7890\"\nExplanation: s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".\n\n\n&nbsp;\nConstraints:\n\n\n\ts is either a valid email or a phone number.\n\tIf s is an email:\n\t\n\t\t8 &lt;= s.length &lt;= 40\n\t\ts consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.\n\t\n\t\n\tIf s is a phone number:\n\t\n\t\t10 &lt;= s.length &lt;= 20\n\t\ts consists of digits, spaces, and the symbols '(', ')', '-', and '+'.\n\t\n\t\n\n",293        "solution_py": "class Solution:\n    def maskPII(self, s: str) -> str:\n        res=''\n        if '@' in s:\n            \n            l=s.split('@')\n            \n            a=l[0]\n            b=l[1]\n            \n            c=b.split('.')\n            \n            \n            res=a[0].lower()+'*'*5+a[-1].lower()+'@'+c[0].lower()+'.'+c[1].lower()\n            return res\n        else:\n            l=0\n            res=''\n            flag=False\n            f=False\n            c=0\n            for i in range(len(s)-1,-1,-1):\n                if s[i]==\"(\" or s[i]==')' or s[i]=='-' or s[i]=='+' or s[i]==' ':\n                    continue\n                  \n                if f==True:\n                    c+=1\n                    continue\n                \n                if flag==False:\n                    res=s[i]+res\n                else:\n                    res='*'+res\n                    \n                \n                \n                if l==3 or l==6:\n                    if l==3:\n                        flag=True\n                    res='-'+res\n                l+=1\n                \n                if len(res)==12:\n                    f=True\n            if c==1:\n                res='+*-'+res\n            elif c==2:\n                res=\"+**-\"+res\n            elif c==3:\n                res=\"+***-\"+res\n                    \n           \n            return res\n            \n                    \n                    \n                    \n                    \n        ",294        "solution_js": "var maskPII = function(S) {\n    if (isEmail(S)) return maskEmail(S);\n    return maskPhone(S);\n    \n    function isEmail(str) {\n       return /^[A-Za-z]{2,}@[A-Za-z]{2,}.[A-Za-z]{2,}$/.test(str);\n    }\n    \n    function maskEmail(str) {\n        let res = \"\";\n        const [local, domain] = str.split(\"@\");\n        \n        res += local.charAt(0).toLowerCase() + \"*****\" + local.charAt(local.length - 1).toLowerCase();\n        return res + \"@\" + domain.toLowerCase(); \n    }\n    \n    function maskPhone(str) {\n        const onlyDigits = str.replace(/\\D/g, \"\");\n        \n        const localNum = \"***-***-\" + onlyDigits.substring(onlyDigits.length - 4);\n        \n        if (onlyDigits.length === 10) return localNum;\n        \n        let countryNum = \"+\" + \"*\".repeat(onlyDigits.length - 10) + \"-\";\n        \n        return countryNum + localNum;\n    } \n};",295        "solution_java": "class Solution {\n    public String maskPII(String s) {\n        StringBuilder sb = new StringBuilder();\n                 //email handeling\n        if((s.charAt(0) >= 97 && s.charAt(0) <= 122) || (s.charAt(0) >= 65 && s.charAt(0) <= 90)){\n\n            s = s.toLowerCase();\n           int indexofAt = s.indexOf('@');\n           String firstName = s.substring(0, indexofAt);\n           sb.append(firstName.charAt(0)).append(\"*****\").append(firstName.charAt(firstName.length()-1));\n           sb.append(s.substring(indexofAt,s.length()));\n        }\n        //phone number handeling\n        else{\n           int digits = 0;\n           for(int i = 0 ; i < s.length(); i++){\n               if(Character.isDigit(s.charAt(i))){\n                   digits++;\n               }\n           }\n           if(digits > 10){\n               sb.append('+');\n           }\n           while(digits > 10){\n               sb.append('*');\n               digits--;\n           }\n           if(sb.toString().isEmpty() == false){\n               sb.append('-');\n           }\n           sb.append(\"***\").append('-').append(\"***-\");\n           StringBuilder last4 = new StringBuilder();\n           int count = 0;\n           for(int i = s.length()-1; i >=0; --i){\n               if(count == 4){\n                   break;\n               }\n               if(Character.isDigit(s.charAt(i))){\n                   last4.append(s.charAt(i));\n                   count++;\n               }\n           }\n           sb.append(last4.reverse());\n        }\n\n        return sb.toString();\n    }\n}",296        "solution_c": "class Solution {\npublic:\n  string email(string &s, int id){\n    string t = string(1, s[0] | ' ') + \"*****\" + string(1, s[id-1] | ' ');\n  \n    for(int i = id + 1; i != s.size(); i++) \n      if(s[i] != '.') s[i] |= ' ';\n    \n    return t + s.substr(id, s.size());\n  }\n  \n  string phone(string &s){\n    string table[] = { \"\" , \"+*-\", \"+**-\", \"+***-\" }, t;\n    \n    for(auto &ch: s)\n      if(ch >= '0' && ch <= '9') t.push_back(ch);\n   \n    return table[t.size() - 10] + \"***-***-\" + t.substr(t.size() - 4, 4);\n  }\n  \n  string maskPII(string s) {\n    int id = s.find('@'); \n    return id == -1 ? phone(s) : email(s, id);\n  }\n};"297    },298    {299        "title": "Longest Happy Prefix",300        "algo_input": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\n\nGiven a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists.\n\n&nbsp;\nExample 1:\n\nInput: s = \"level\"\nOutput: \"l\"\nExplanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\n\n\nExample 2:\n\nInput: s = \"ababab\"\nOutput: \"abab\"\nExplanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts contains only lowercase English letters.\n\n",301        "solution_py": "class Solution:\n    def longestPrefix(self, s: str) -> str:\n        n=len(s)\n        lps=[0]*n\n        j=0\n        for i in range(1,n):\n            while s[i]!=s[j] and j>0:\n                j=lps[j-1]\n\n            if s[i]==s[j]:\n                lps[i]=j+1\n                j+=1\n\n        return s[:lps[-1]]",302        "solution_js": "var longestPrefix = function(s) {\n    const len = s.length;\n    const z = new Array(len).fill(0);\n    let l = 0, r = 0;\n    \n    for(let i = 1; i < len; i++) {\n        if(i <= r) \n            z[i] = Math.min(r - i + 1, z[i - l]);\n        while(i + z[i] < len && s[z[i]] == s[i + z[i]]) {\n            z[i]++;\n        }\n        if(i + z[i] - 1 > r) {\n            r = i + z[i] - 1;\n            l = i;\n        }\n    }\n    \n    let idx = -1;\n    for(let i = 1; i < len; i++) {\n        if(i + z[i] == len) {\n            idx = i;\n            break;\n        }\n    }\n    if(idx == -1) return '';\n    return s.slice(idx);\n};",303        "solution_java": "class Solution {\n    public String longestPrefix(String s) {\n       int n=s.length();\n        char arr[] = s.toCharArray();\n        int lps[]=new int[n];\n        for(int i=1; i<n; i++){\n            int j=lps[i-1]; // COMPARING ITS i WITH ITS PREV ELEMENT\n            while(j>0 && arr[j]!=arr[i]){\n                j=lps[j-1]; // DEACREASING TILL WE FIND ITS PREFIX WHICH IS EQUAL TO ITS SUFFIX\n            }\n            if(arr[j]==arr[i]){// IF ITS PREV IS SAME AS CURRENT THEN INCREAMENT IT\n                j++;\n            }\n            lps[i]=j; // SAVE WHATEVER THE VALUE IS\n        }\n        int j=lps[n-1];\n       StringBuilder sb = new StringBuilder();\n        for(int i=0;i<j;i++){\n            sb.append(arr[i]);\n        }\n        return sb.toString();\n\n    }\n}\n/*\n ALTERNATE\n\n  for(int i=1;i<n;i++){\n            if(arr[i]==arr[j]){ // IF SAME INCREASE IT\n                lps[i]=++j;\n            }else if(j>0){ // ELSE DEACREASE TILL WE ARE NOT FINDING IT\n                j=lps[j-1];\n                i--;\n            }\n        }\n        return s.substring(0,j);\n\n */",304        "solution_c": "class Solution {\npublic:\n    string longestPrefix(string s) {\n        if(s == \"\")\n            return \"\";\n        int n = s.length();\n        int arr[n];\n        fill(arr, arr + n, 0);\n        int prevLPS = 0, i = 1;\n        while(i < n){\n            if(s[i] == s[prevLPS]){\n                arr[i] = prevLPS + 1;\n                i++;\n                prevLPS++;\n            }\n            else if(prevLPS == 0){\n                arr[i] = 0;\n                i++;\n            }\n            else{\n                prevLPS = arr[prevLPS - 1];\n            }\n        }\n        int oplen = arr[n-1];\n        string temp = s.substr(n - oplen, oplen);\n        return temp;\n    }\n};"305    },306    {307        "title": "Exclusive Time of Functions",308        "algo_input": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.\n\nFunction calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.\n\nYou are given a list logs, where logs[i] represents the ith log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\". For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3, and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.\n\nA function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.\n\nReturn the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\nOutput: [3,4]\nExplanation:\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n\n\nExample 2:\n\nInput: n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\nOutput: [8]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n\n\nExample 3:\n\nInput: n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\nOutput: [7,1]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= logs.length &lt;= 500\n\t0 &lt;= function_id &lt; n\n\t0 &lt;= timestamp &lt;= 109\n\tNo two start events will happen at the same timestamp.\n\tNo two end events will happen at the same timestamp.\n\tEach function has an \"end\" log for each \"start\" log.\n\n",309        "solution_py": "class Solution:\n    #T=O(n), S=O(d)\n    #n=len of logs, d=depth of stack\n    def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n        #init result array to zeroes of length n (function ids)\n        res = [0]*n\n        stack = []\n        #iterate through logs\n        for log in logs:\n            #split the log\n            #function_id: start|end: timestamp\n            log = log.split(\":\")\n            #type cast function id and timestamp to int type\n            id = int(log[0])\n            timestamp = int(log[2])\n            state = log[1]\n            #detect start of a function call\n            #stack[function_id, start_timestamp]\n            if state == \"start\":\n                #stack is non empty\n                if stack:\n                    #get the time taken by last function so far\n                    res[stack[-1][0]] += timestamp - stack[-1][1]\n                #append the current function_id and start timestamp to the stack\n                stack.append([id, timestamp])\n            else:\n                #get the time consumed by current function\n                #dont forget to add 1 as the last unit of time should be included\n                res[id] += timestamp - stack.pop()[1] + 1\n                if stack:\n                    #update the start time of last function in stack to get the cumulative result\n                    stack[-1][1] = timestamp + 1\n\n        return res",310        "solution_js": "var exclusiveTime = function(n, logs) {\n\tconst stack = [];\n\tlet preTimeStamp = 0;\n\n\treturn logs.reduce((times, log) => {\n\t\tconst [id, status, timeStamp] = log.split(':');\n\t\tconst time = +timeStamp - preTimeStamp;\n\t\tconst { length } = stack;\n\n\t\tif (length) {\n\t\t\tconst lastId = stack[length - 1];\n\t\t\ttimes[lastId] += time;\n\t\t}\n\t\tpreTimeStamp = +timeStamp;\n\n\t\tif (status === 'start') stack.push(id);\n\t\telse {\n\t\t\tconst lastId = stack.pop();\n\t\t\ttimes[lastId] += 1;\n\t\t\tpreTimeStamp += 1;\n\t\t}\n\t\treturn times;\n\t}, Array(n).fill(0));\n}",311        "solution_java": "class Solution {\n\n    //Time Complexity: O(N) for looping through logs\n    //Space Complexity: O(N) for stack\n\n    public int[] exclusiveTime(int n, List<String> logs) {\n        if (n == 0) {\n            return new int[0];\n        }\n\n        int[] result = new int[n];\n\n        Stack<Pair<Integer, Integer>> stack = new Stack<>();\n\n        for (String s : logs) {\n            String[] sArr = s.split(\":\");\n            int functionId = Integer.parseInt(sArr[0]);\n            String startOrEnd = sArr[1];\n            int timestamp = Integer.parseInt(sArr[2]);\n\n            if (startOrEnd.equals(\"start\")) {\n\n                //calculate previous in-progress length\n                if (!stack.empty()) {\n                    Pair<Integer, Integer> pair = stack.peek();\n                    int oldFunctionId = pair.getKey();\n                    int oldTimestamp = pair.getValue();\n                    result[oldFunctionId] += timestamp - oldTimestamp;\n                }\n\n                //add new start\n                stack.push(new Pair(functionId, timestamp));\n            } else {\n                //calculate current length\n                Pair<Integer, Integer> pair = stack.pop();\n                int oldTimestamp = pair.getValue();\n\n                result[functionId] += timestamp - oldTimestamp + 1;\n\n                //reset previous function's start\n                if (!stack.empty()) {\n                    pair = stack.pop();\n                    Pair<Integer, Integer> replacementPair = new Pair(pair.getKey(), timestamp + 1);\n                    stack.push(replacementPair);\n                }\n            }\n        }\n\n        return result;\n    }\n}",312        "solution_c": "class Solution {\npublic:\n    vector<int> exclusiveTime(int n, vector<string>& logs) {\n        vector<int> ret(n, 0);\n        stack<pair<int, int>> st;\n        for (auto& l : logs) {\n            auto p1 = l.find(':', 0), p2 = l.find(':', p1+1);\n            auto id = stoi(l.substr(0, p1));\n            auto time = stoi(l.substr(p2+1));\n            if (l[p1+1] == 's') {\n                st.push({id, time});\n            } else {\n                auto diff = time - st.top().second + 1;\n                ret[st.top().first] += diff;\n                st.pop();\n                if (!st.empty())\n                    ret[st.top().first] -= diff;\n            }\n        }\n        return ret;\n    }\n};"313    },314    {315        "title": "Map Sum Pairs",316        "algo_input": "Design a map that allows you to do the following:\n\n\n\tMaps a string key to a given value.\n\tReturns the sum of the values that have a key with a prefix equal to a given string.\n\n\nImplement the MapSum class:\n\n\n\tMapSum() Initializes the MapSum object.\n\tvoid insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.\n\tint sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n[[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]\nOutput\n[null, null, 3, null, 5]\n\nExplanation\nMapSum mapSum = new MapSum();\nmapSum.insert(\"apple\", 3);  \nmapSum.sum(\"ap\");           // return 3 (apple = 3)\nmapSum.insert(\"app\", 2);    \nmapSum.sum(\"ap\");           // return 5 (apple + app = 3 + 2 = 5)\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= key.length, prefix.length &lt;= 50\n\tkey and prefix consist of only lowercase English letters.\n\t1 &lt;= val &lt;= 1000\n\tAt most 50 calls will be made to insert and sum.\n\n",317        "solution_py": "\tclass MapSum:\n\n\t\tdef __init__(self):\n\t\t\tself.cache = {}\n\n\t\tdef insert(self, key: str, val: int) -> None:\n\t\t\tself.cache[key] = val\n\n\t\tdef sum(self, prefix: str) -> int:\n\t\t\tlen_prefix = len(prefix)\n\t\t\ttotal = 0\n\t\t\tfor word, value in self.cache.items():\n\t\t\t\tif word[: len_prefix] == prefix:\n\t\t\t\t\ttotal += value\n\n\t\t\treturn total",318        "solution_js": "var MapSum = function() {\n    this.hashKeys = new Map();\n    this.hashVals = new Map();\n};\n\nMapSum.prototype.insert = function(key, val) {\n    let prefix = '';\n    for (const str of key) {\n        prefix += str;\n        const hashKey = this.hashKeys.get(prefix) ?? new Set();\n        hashKey.add(key);\n        !this.hashKeys.has(prefix) && this.hashKeys.set(prefix, hashKey);\n    }\n    this.hashVals.set(key, val);\n};\n\nMapSum.prototype.sum = function(prefix) {\n    const hashKey = this.hashKeys.get(prefix);\n    if (!hashKey) return 0;\n    let sum = 0;\n    hashKey.forEach(key => sum += this.hashVals.get(key));\n    return sum;\n};",319        "solution_java": "class MapSum {\n    private Map<String, Integer> map;\n    private Map<String, Integer> words;\n\n    public MapSum() {\n        this.map = new HashMap<>();\n        this.words = new HashMap<>();\n    }\n    \n    public void insert(String key, int val) {\n        Integer lookup = this.words.getOrDefault(key, null);\n        int diff;\n        if (lookup == null)\n            diff = val;\n        else\n            diff = val - lookup;\n        \n        int k = key.length();\n        \n        StringBuilder sb = new StringBuilder(); \n        for (int i = 0; i < k; i++) {\n            sb.append(key.charAt(i));\n            \n            String prefix = sb.toString();\n            map.put(prefix, map.getOrDefault(prefix, 0) + diff);\n        }\n        \n        this.words.put(key, val);\n    }\n    \n    public int sum(String prefix) {\n        return this.map.getOrDefault(prefix, 0);\n    }\n}\n\n/**\n * Your MapSum object will be instantiated and called as such:\n * MapSum obj = new MapSum();\n * obj.insert(key,val);\n * int param_2 = obj.sum(prefix);\n */",320        "solution_c": "class MapSum {\npublic:\n    map<string,int>mp;\n    MapSum() {\n\n    }\n\n    void insert(string key, int val) {\n        mp[key]=val;\n    }\n\n    int sum(string prefix) {\n        int count=0;\n        for(auto i:mp){\n            int j;\n            for(j=0;j<i.first.size() && j<prefix.size();j++){\n                if(i.first[j]!=prefix[j])break;\n            }\n            if(j==prefix.size())count+=i.second;\n        }\n        return count;\n    }\n};"321    },322    {323        "title": "Seat Reservation Manager",324        "algo_input": "Design a system that manages the reservation state of n seats that are numbered from 1 to n.\n\nImplement the SeatManager class:\n\n\n\tSeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.\n\tint reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.\n\tvoid unreserve(int seatNumber) Unreserves the seat with the given seatNumber.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n[[5], [], [], [2], [], [], [], [], [5]]\nOutput\n[null, 1, 2, null, 2, 3, 4, 5, null]\n\nExplanation\nSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve();    // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve();    // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve();    // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve();    // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve();    // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= seatNumber &lt;= n\n\tFor each call to reserve, it is guaranteed that there will be at least one unreserved seat.\n\tFor each call to unreserve, it is guaranteed that seatNumber will be reserved.\n\tAt most 105 calls in total will be made to reserve and unreserve.\n\n",325        "solution_py": "class SeatManager:\n    def __init__(self, n: int):\n        self.lis = list(range(1,n+1))\n    def reserve(self) -> int:\n        mini = min(self.lis)\n        self.lis.remove(mini)\n        return mini\n\n    def unreserve(self, seatNumber: int) -> None:\n        self.lis.append(seatNumber)",326        "solution_js": "var SeatManager = function(n) {\n    \n    this.min = 1\n    this.n = n\n    this.seat = []\n    \n};\n\nSeatManager.prototype.reserve = function() {\n\n    let res\n\t\n    if( !this.seat[this.min] ){\n        \n        res = this.min\n        this.min = this.n < this.min ? NaN : this.min + 1\n\n    } else {\n        \n        res = this.min\n        this.min = this.seat[this.min]\n        \n    }\n    \n    return res\n};\n\nSeatManager.prototype.unreserve = function(seatNumber) {\n    \n    if (this.min < seatNumber ) {\n        \n        let pre_inx = this.min \n        let next_inx = this.seat[this.min]\n        \n        while(next_inx < seatNumber){\n            pre_inx = next_inx\n            next_inx = this.seat[next_inx]\n        }\n        \n        [ this.seat[pre_inx], this.seat[seatNumber] ] = [ seatNumber, this.seat[pre_inx] ]\n        \n    } else {\n        \n        [ this.seat[seatNumber], this.min ] = [ this.min, seatNumber ]\n        \n    }\n};",327        "solution_java": "class SeatManager {\n    PriorityQueue<Integer> pq;\n    int count;\n    public SeatManager(int n) {\n        count = 1;\n        pq = new PriorityQueue();\n    }\n\n    public int reserve() {\n        if(pq.size()==0)\n            return count++;\n\n        return pq.poll();\n    }\n\n    public void unreserve(int seatNumber) {\n        pq.add(seatNumber);\n    }\n}",328        "solution_c": "class SeatManager {\npublic:\n    priority_queue<int, vector<int>, greater<int> > pq;\n    SeatManager(int n) {\n        for(int i = 1; i <= n; i++) pq.push(i);\n    }\n\n    int reserve() {\n        int top = pq.top(); pq.pop();\n        return top;\n    }\n\n    void unreserve(int seatNumber) {\n        pq.push(seatNumber);\n    }\n};"329    },330    {331        "title": "Jewels and Stones",332        "algo_input": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.\n\nLetters are case sensitive, so \"a\" is considered a different type of stone from \"A\".\n\n&nbsp;\nExample 1:\nInput: jewels = \"aA\", stones = \"aAAbbbb\"\nOutput: 3\nExample 2:\nInput: jewels = \"z\", stones = \"ZZ\"\nOutput: 0\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;jewels.length, stones.length &lt;= 50\n\tjewels and stones consist of only English letters.\n\tAll the characters of&nbsp;jewels are unique.\n\n",333        "solution_py": "class Solution:\n    def numJewelsInStones(self, jewels: str, stones: str) -> int:\n\t\t# 1 : One line solution, My best runtime 38 with 13.9 MB\n        return sum(1 for k in stones if k in jewels)\n\t\t\n\t\t# 2 : Traditional solution\n\t\tx=0\n\t\tfor k in stones:\n\t\t\tif k in jewels:\n\t\t\t\tx+=1\n\t\treturn x",334        "solution_js": "var numJewelsInStones = function(jewels, stones) {\n    let trackDict = new Map();\n    let output = 0;\n\n    for (let char of stones)\n        trackDict.set(char, trackDict.has(char) ? trackDict.get(char) + 1 : 1);\n    \n    for (let char of jewels)\n        output += trackDict.has(char) ? trackDict.get(char) : 0;\n\n    return output;\n};",335        "solution_java": "class Solution {\n    public int numJewelsInStones(String jewels, String stones) {\n        HashSet<Character> hs=new HashSet<>();\n        int count=0;\n        for(int i=0;i<jewels.length();i++)\n        {\n            hs.add(jewels.charAt(i));\n        }\n        for(int i=0;i<stones.length();i++)\n        {\n            if(hs.contains(stones.charAt(i)))\n                count++;\n        }\n        return count;\n    }\n}",336        "solution_c": "class Solution {\npublic:\n\tint numJewelsInStones(string jewels, string stones) {\n\n\t\tunordered_map<char, int> mp;\n\n\t\tfor(int i=0 ; i<jewels.size() ; i++){\n\t\t\tmp[jewels[i]]++;\n\t\t}\n\n\t\tint ans = 0;\n\t\tfor(int i=0 ; i<stones.size() ; i++){\n\t\t\tif(mp.find(stones[i]) != mp.end()){\n\t\t\t\tans++;\n\t\t\t}\n\t\t}\n\n\t\treturn ans;\n\t}\n};"337    },338    {339        "title": "Find the Winner of an Array Game",340        "algo_input": "Given an integer array arr of distinct integers and an integer k.\n\nA game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.\n\nReturn the integer which will win the game.\n\nIt is guaranteed that there will be a winner of the game.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,1,3,5,4,6,7], k = 2\nOutput: 5\nExplanation: Let's see the rounds of the game:\nRound |       arr       | winner | win_count\n  1   | [2,1,3,5,4,6,7] | 2      | 1\n  2   | [2,3,5,4,6,7,1] | 3      | 1\n  3   | [3,5,4,6,7,1,2] | 5      | 1\n  4   | [5,4,6,7,1,2,3] | 5      | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\n\n\nExample 2:\n\nInput: arr = [3,2,1], k = 10\nOutput: 3\nExplanation: 3 will win the first 10 rounds consecutively.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i] &lt;= 106\n\tarr contains distinct integers.\n\t1 &lt;= k &lt;= 109\n\n",341        "solution_py": "class Solution:\n    def getWinner(self, arr: List[int], k: int) -> int:\n        winner = arr[0]\n        wins = 0\n        for i in range(1,len(arr),1):\n            if(winner > arr[i]): wins+=1  # increment wins count   \n            else:\n                wins = 1    # new winner\n                winner = arr[i]\n            if(wins == k): break    # if wins count is k, then return winner\n                \n        return winner",342        "solution_js": "var getWinner = function(arr, k) {\n    let ws=0;\n    let currentWinner=0;\n    for(let i=1;i<arr.length;i++){\n        if(arr[currentWinner]>arr[i]){\n            ++ws\n        }else{\n            ws=1\n            currentWinner=i\n        }\n        if(ws===k)return arr[currentWinner]\n    }\n    return arr[currentWinner]\n};",343        "solution_java": "class Solution {\n    public int getWinner(int[] arr, int k) {\n       \n       int winner =arr[0];\n        int count=0;\n        for(int i=1;i<arr.length;i++)\n        {\n                if(winner>arr[i])\n                    count++;\n                else\n                {\n                    winner=arr[i];\n                    count=1;\n                }\n            if(count==k)\n                return winner;\n        }\n        return winner;\n    }\n}",344        "solution_c": "class Solution {\npublic:\n    int getWinner(vector<int>& arr, int k) {\n        int winner = arr[0];\n        int wins = 0;\n        for (int i=1; i<arr.size();i++){\n            if(winner > arr[i])\n                wins+=1; //increment wins count\n            else{\n                wins = 1; //new winner\n                winner = arr[i];\n            }\n            if(wins == k)\n                break; //if wins count is k, then return winner\n        }\n        return winner;\n    }\n};"345    },346    {347        "title": "Find Nearest Point That Has the Same X or Y Coordinate",348        "algo_input": "You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.\n\nReturn the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.\n\nThe Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).\n\n&nbsp;\nExample 1:\n\nInput: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\nOutput: 2\nExplanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.\n\nExample 2:\n\nInput: x = 3, y = 4, points = [[3,4]]\nOutput: 0\nExplanation: The answer is allowed to be on the same location as your current location.\n\nExample 3:\n\nInput: x = 3, y = 4, points = [[2,3]]\nOutput: -1\nExplanation: There are no valid points.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 104\n\tpoints[i].length == 2\n\t1 &lt;= x, y, ai, bi &lt;= 104\n\n",349        "solution_py": "class Solution:\n    def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n        minDist = math.inf\n        ans = -1\n        for i in range(len(points)):\n            if points[i][0]==x or points[i][1]==y:\n                manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n                if manDist<minDist:\n                    ans = i\n                    minDist = manDist\n        return ans",350        "solution_js": "var nearestValidPoint = function(x, y, points) {\n    let min = Infinity\n    let idx = -1\n    points.forEach(([a,b], i)=>{\n        if(a===x || b===y){\n            const dist = Math.abs(x-a) + Math.abs(y-b)\n            if(dist<min){\n                idx = i\n                min = dist\n            }\n        }\n    })\n    return idx\n};",351        "solution_java": "class Solution {\n    public int nearestValidPoint(int x, int y, int[][] points) {\n        int min=Integer.MAX_VALUE, index=-1, i;\n        \n        for ( i=0;i<points.length;i++){\n            if (x==points[i][0] ||  y==points[i][1]){\n                 int d = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);\n                if (d<min){\n                    min=d;\n                    index=i;\n                }\n            }\n            \n        }\n        // if ( min== Integer.MAX_VALUE) return -1; --> no longer needed as index is initialized as -1 in the declartion.\n        return  index;\n        \n    }\n}",352        "solution_c": "class Solution {\npublic:\n    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {\n        int pos = -1;\n        int ans = INT_MAX;\n\n        for(int i=0; i<points.size(); i++){\n            if(points[i][0] == x or points[i][1] == y){\n                int dist = abs(x-points[i][0]) + abs(y-points[i][1]);\n                if(dist < ans){\n                    pos = i;\n                    ans = dist;\n                }\n            }\n        }\n       return pos;\n    }\n};"353    },354    {355        "title": "Longest Mountain in Array",356        "algo_input": "You may recall that an array arr is a mountain array if and only if:\n\n\n\tarr.length &gt;= 3\n\tThere exists some index i (0-indexed) with 0 &lt; i &lt; arr.length - 1 such that:\n\t\n\t\tarr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i]\n\t\tarr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]\n\t\n\t\n\n\nGiven an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,1,4,7,3,2,5]\nOutput: 5\nExplanation: The largest mountain is [1,4,7,3,2] which has length 5.\n\n\nExample 2:\n\nInput: arr = [2,2,2]\nOutput: 0\nExplanation: There is no mountain.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t0 &lt;= arr[i] &lt;= 104\n\n\n&nbsp;\nFollow up:\n\n\n\tCan you solve it using only one pass?\n\tCan you solve it in O(1) space?\n\n",357        "solution_py": "class Solution:\n    def longestMountain(self, arr: List[int]) -> int:\n        if len(arr) < 3:\n            return 0\n        \n        max_up, max_down = [1 for _ in arr], [1 for _ in arr]\n        \n        for i, x in enumerate(arr):\n            if i == 0:\n                continue\n            if x > arr[i - 1]:\n                max_up[i] = max_up[i - 1] + 1\n            \n        for j, y in reversed(list(enumerate(arr))):\n            if j == len(arr) - 1:\n                continue\n            if y > arr[j + 1]:\n                max_down[j] = max_down[j + 1] + 1\n                \n        return max(\n            x + y - 1 if x > 1 and y > 1 else 0 \n            for x, y in zip(max_up, max_down)\n        )",358        "solution_js": "var longestMountain = function(arr) {\n    let len=arr.length;\n    let climbUp=false;\n    let climbDown=false;\n    let countUp=0;\n    let countDown=0;\n    let distance=0;\n    let max=0; \n    if(len<3){\n        return 0;\n    }\n    for(i=0;i<len;i++){\n        if(arr[i-1]<arr[i]){\n        countUp++;\n        climbUp=true;   \n        }else if(arr[i-1]>arr[i] && climbUp){\n        countDown++; \n        climbDown=true;\n        }\n        if((arr[i-1]>=arr[i] && arr[i]<=arr[i+1]) || (i==len-1 && climbDown==true)){\n            distance=countUp+countDown+1;\n            if(max<distance && climbUp && climbDown){\n                max=distance;\n            }\n            countUp=0;\n            countDown=0;\n            climbUp=false;\n            climbDown=false;\n        }\n        if(arr[i+1]==arr[i]){\n            climbUp=false;\n            climbDown=false;\n        }\n    }\n   return(max<3?0:max)\n};",359        "solution_java": "class Solution {\n    public int longestMountain(int[] arr) {\n        if (arr.length < 3)\n            return 0;\n        int max = 0;\n        for (int i = 0; i < arr.length; i++) {\n            if (isPeak(arr, i)) {\n                int leftLength = left(arr, i);\n                int rightLength = right(arr, i);\n                max = Math.max(max, leftLength + rightLength + 1);\n            }\n        }\n        return max;\n    }\n\n    public int left(int[] arr, int i) {\n        int j = i - 1;\n        while (j >= 0 && arr[j] < arr[j + 1])\n            j--;\n        return i - (j + 1);\n    }\n\n    public int right(int[] arr, int i) {\n        int j = i + 1;\n        while (j < arr.length && arr[j - 1] > arr[j])\n            j++;\n        return j - (i + 1);\n    }\n\n    public boolean isPeak(int[] arr, int i) {\n        return i - 1 >= 0 && i + 1 < arr.length && arr[i - 1] < arr[i] && arr[i + 1] < arr[i];\n    }\n}",360        "solution_c": "class Solution {\npublic:\n    int longestMountain(vector<int>& arr) {\n     vector<int> v;\n        for(int i=0;i<arr.size()-1;i++)\n        {\n            if(arr[i+1]>arr[i])v.push_back(1);\n            else if(arr[i+1]<arr[i])v.push_back(-1);\n            else \n                v.push_back(0);\n        }\n        int i=0;\n        int ans=0;\n        while(i<v.size())\n        {\n            int c1=0,c2=0;\n            while(i<v.size() and v[i]==1)\n            {\n                c1++;\n                i++;\n            }\n            while(i<v.size() and v[i]==-1)\n            {\n                c2++;\n                i++;\n            }\n            while(i<v.size() and v[i]==0)\n            {\n                i++;\n            }\n            if(c1!=0 and c2!=0)\n            {\n                ans=max(ans,c1+c2+1);\n            }\n        }\n        return ans;\n    }\n};"361    },362    {363        "title": "Decode Ways II",364        "algo_input": "A message containing letters from A-Z can be encoded into numbers using the following mapping:\n\n'A' -&gt; \"1\"\n'B' -&gt; \"2\"\n...\n'Z' -&gt; \"26\"\n\n\nTo decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n\n\n\t\"AAJF\" with the grouping (1 1 10 6)\n\t\"KJF\" with the grouping (11 10 6)\n\n\nNote that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\n\nIn addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\". Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent.\n\nGiven a string s consisting of digits and '*' characters, return the number of ways to decode it.\n\nSince the answer may be very large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: s = \"*\"\nOutput: 9\nExplanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".\n\n\nExample 2:\n\nInput: s = \"1*\"\nOutput: 18\nExplanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\n\n\nExample 3:\n\nInput: s = \"2*\"\nOutput: 15\nExplanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is a digit or '*'.\n\n",365        "solution_py": "class Solution:\n    def numDecodings(self, s: str):\n        if s[0] == '0': return 0\n        cMap = {'0':0, '*': 9, '**': 15, '1*': 9, '2*': 6} #{char(s) : multiplier} mapping\n        for i in range(1, 27): cMap[str(i)] = 1\n        for i in range(0, 7): cMap['*'+str(i)] = 2\n        for i in range(7, 10): cMap['*'+str(i)] = 1\n        \n        dp = [0]*(len(s)+1)\n        dp[0], dp[-1] = cMap[s[0]] , 1\n        \n        for i in range(1, len(s)):\n            dp[i] += (cMap[s[i]]*dp[i-1] + cMap.get(s[i-1:i+1],0)*dp[i-2])%(10**9 + 7)\n            if not dp[i]: return 0\n            \n        return dp[-2]",366        "solution_js": "var numDecodings = function(s) {\n    let len = s.length;\n    if(len === 0) return s;\n    let mod = Math.pow(10,9)+7;\n    let dp = new Array(len+1).fill(0);\n    dp[0] = 1;\n    if(s[0] == 0) dp[1] = 0;\n    else if(s[0] == '*') dp[1] = 9;\n    else dp[1] = 1;\n    for(let i=2;i<=len;i++){\n        if(s[i-1] == '*'){\n            dp[i] += 9*dp[i-1];\n        } else if(s[i-1] != 0 && s[i-1] != '*'){\n            dp[i] += dp[i-1]; \n        }\n        if(s[i-2] == 1){\n            if(s[i-1] == '*') dp[i] += 9*dp[i-2];\n            else dp[i] += dp[i-2];\n        } else if(s[i-2] == 2){\n            if(s[i-1]<7) dp[i] += dp[i-2];\n            else if(s[i-1] == '*') dp[i] += 6*dp[i-2];            \n        } else if(s[i-2] == '*'){\n            if(s[i-1] == '*') dp[i] += 15*dp[i-2];\n            else if(s[i-1]>=0 && s[i-1]<=6) dp[i] += 2*dp[i-2];\n            else if(s[i-1] >=7) dp[i] += dp[i-2];\n        }\n        dp[i] = dp[i]%mod;\n    }\n    return dp[len]%mod;\n};",367        "solution_java": "class Solution {\n    public int numDecodings(String s) {\n        int[] dp = new int[s.length()+1];\n        dp[0]=1;\n        int M = (int)1e9+7;\n        for (int i = 1; i <= s.length(); i++){\n            for (int j = 1; j <= 26; j++){\n                if (j<10 && (s.charAt(i-1)-'0'==j||s.charAt(i-1)=='*')){ // 1 digit -> if they are equal or if *\n                    dp[i]+=dp[i-1];\n                    dp[i]%=M;\n                }\n                if (i>1&&j>=10&&ok(j,s.substring(i-2,i))){ // ok() function handles 2 digits\n                    dp[i]+=dp[i-2];\n                    dp[i]%=M;\n                }\n            }\n        }\n        return dp[s.length()];\n    }\n\n    private boolean ok(int val, String s){ // TRUE if the value s represents can equal to val.\n        return (s.equals(\"**\") && val%10 > 0\n             || s.charAt(0)=='*' && val%10==s.charAt(1)-'0'\n             || s.charAt(1)=='*' && val/10==s.charAt(0)-'0' && val % 10 > 0\n             || !s.contains(\"*\") && Integer.parseInt(s)==val);\n    }\n}",368        "solution_c": "class Solution {\npublic:\n    int numDecodings(string s) {\n        int n=s.size();\n        if(s[0]=='0')\n        {\n            return 0;\n        }\n        for(int i=0;i<n-1;++i)\n        {\n            if(s[i]==s[i+1]&&s[i]=='0')\n            {\n                return 0;\n            }\n        }\n        long long dp[n][2],mod=1e9+7;\n        //dp[i][0]-no of ways such that 0...i has been mapped with ith digit is mapped alone\n        //dp[i][1]-no of ways such that 0...i has been mapped with ith digit is mapped with previous digit\n        dp[0][0]=(s[0]=='*'?9:1);\n        dp[0][1]=0;\n        for(int i=1;i<n;++i)\n        {\n            if(s[i]!='0')\n            {\n                if(s[i]=='*')\n                {\n                    long long m=9;\n                    dp[i][0]=((m%mod)*((dp[i-1][0]+dp[i-1][1])%mod))%mod;\n                }\n                else\n                {\n                    dp[i][0]=(dp[i-1][0]+dp[i-1][1])%mod;\n                }\n            }\n            else\n            {\n                dp[i][0]=0;\n            }\n            \n            if(s[i-1]=='0')\n            {\n                dp[i][1]=0;\n            }\n            else\n            {\n                if(s[i-1]=='*'||s[i]=='*')\n                {\n                    long long m=1;\n                    if(s[i-1]=='*'&&s[i]=='*')\n                    {\n                        m=15;\n                    }\n                    else if(s[i-1]=='*')\n                    {\n                        int u=s[i]-'0';\n                        if(u>6)\n                        {\n                            m=1;\n                        }\n                        else\n                        {\n                            m=2;\n                        }\n                    }\n                    else\n                    {\n                        int v=s[i-1]-'0';\n                        if(v>2)m=0;\n                        else\n                        {\n                            if(v==1)m=9;\n                            else m=6;\n                        }\n                    }\n                    if(i-2>=0)dp[i][1]=((m%mod)*((dp[i-2][0]+dp[i-2][1])%mod))%mod;\n                    else dp[i][1]=m;\n                }\n                else\n                {\n                    int v=(s[i-1]-'0')*10+(s[i]-'0');\n                    if(v>=1&&v<=26)\n                    {\n                        if(i-2>=0)dp[i][1]=(dp[i-2][0]+dp[i-2][1])%mod;\n                        else dp[i][1]=1;\n                    }\n                    else\n                    {\n                        dp[i][1]=0;\n                    }\n                }\n                \n            }\n            \n        }\n        return (dp[n-1][0]+dp[n-1][1])%mod;\n    }\n};"369    },370    {371        "title": "Time Needed to Inform All Employees",372        "algo_input": "A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.\n\nEach employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.\n\nThe head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.\n\nThe i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).\n\nReturn the number of minutes needed to inform all the employees about the urgent news.\n\n&nbsp;\nExample 1:\n\nInput: n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput: 0\nExplanation: The head of the company is the only employee in the company.\n\n\nExample 2:\n\nInput: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput: 1\nExplanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= headID &lt; n\n\tmanager.length == n\n\t0 &lt;= manager[i] &lt; n\n\tmanager[headID] == -1\n\tinformTime.length == n\n\t0 &lt;= informTime[i] &lt;= 1000\n\tinformTime[i] == 0 if employee i has no subordinates.\n\tIt is guaranteed that all the employees can be informed.\n\n",373        "solution_py": "import queue\nclass Solution:\n\tdef numOfMinutes(self, n: int, headID: int, manager: List[int],time: List[int]) -> int:\n\t\tnodes = []\n\t\tfor i in range(n): nodes.append([])\n\t\tfor i in range(n): \n\t\t\tif i != headID: nodes[manager[i]].append(i)\n\n\t\tq = queue.LifoQueue()\n\t\tq.put([headID,0])\n\t\tans = 0\n\t\twhile not q.empty():\n\t\t\tcur = q.get()\n\t\t\tfor nxt in nodes[cur[0]]:\n\t\t\t\tq.put([nxt,cur[1]+time[cur[0]]])\n\t\t\t\tans = max(ans,cur[1]+time[cur[0]])\n\t\treturn ans",374        "solution_js": "var numOfMinutes = function(n, headID, manager, informTime) {\n\n// Build the tree structure\n    let tree = {}\n\n// {manager: direct employee}\n    for (let i = 0 ; i < manager.length ; i++){\n// the head of the company does not have a manager\n        if (i === headID){\n            continue\n        }\n        let m = manager[i]\n        if (!tree[m]){\n            tree[m] = []\n        }\n        tree[m].push(i)\n    }\n\n// BFS\n// [employee, time to inform the head]\n    let queue = [[headID, 0]]\n    let res = 0\n\n    while (queue.length){\n        let [emp, currTime] = queue.shift()\n        let children = tree[emp] || []\n        for (let child of children){\n            res = Math.max(res, informTime[emp] + currTime)\n            queue.push([child, informTime[emp] + currTime])\n        }\n    }\n\n    return res\n};",375        "solution_java": "class Solution {\n    public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {\n        Map<Integer, List<Integer>> graph = new HashMap<>();\n        for(int i=0; i<n; i++) {\n            graph.putIfAbsent(manager[i], new ArrayList<>());\n            graph.get(manager[i]).add(i);\n        }\n        return dfs(graph, headID, informTime);\n    }\n\n    int dfs(Map<Integer, List<Integer>> graph, int curHead, int[] informTime) {\n        int curMax = 0;\n        if(!graph.containsKey(curHead)){\n            return curMax;\n        }\n        for(int subordinate : graph.get(curHead)) {\n            curMax = Math.max(curMax, dfs(graph, subordinate, informTime));\n        }\n        return curMax + informTime[curHead];\n    }\n}",376        "solution_c": "class Solution {\npublic:\n    int ans = INT_MIN, tmp=0;\n    unordered_map<int, vector<int>> mp;//manager to each subordination\n    vector<int>* pInformTime;\n    int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {\n        pInformTime = &informTime;\n        for(int i = 0; i<n;i++) mp[manager[i]].push_back(i);\n        dfs(headID);\n        return ans;\n    }\n    void dfs(int i) {\n        if(mp.find(i) == mp.end()) {\n            ans = max(ans, tmp);\n        } else {\n            tmp+=(*pInformTime)[i];\n            for(auto&c: mp[i]) dfs(c);\n            tmp-=(*pInformTime)[i];\n        }\n    }\n};"377    },378    {379        "title": "Score After Flipping Matrix",380        "algo_input": "You are given an m x n binary matrix grid.\n\nA move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).\n\nEvery row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.\n\nReturn the highest possible score after making any number of moves (including zero moves).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\nOutput: 39\nExplanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\n\n\nExample 2:\n\nInput: grid = [[0]]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 20\n\tgrid[i][j] is either 0 or 1.\n\n",381        "solution_py": "class Solution:\n\n    def calcScore(self):\n        score = 0\n        \n        for row in self.grid:\n            for i in range(self.width):\n                score += row[i] * (2 ** (self.width - i - 1))\n        return score\n    \n    def flipRow(self, row):\n        for i in range(self.width):\n            self.grid[row][i] = int(not self.grid[row][i])\n        \n    def flipCol(self, col):\n        for i in range(self.height):\n            self.grid[i][col] = int(not self.grid[i][col])\n            \n    def colSum(self, col):\n        total = 0\n        \n        for i in range(self.height):\n            total += self.grid[i][col]\n            \n        return total\n    \n    def matrixScore(self, grid: List[List[int]]) -> int:\n        self.grid = grid\n        self.height = len(grid)\n        self.width = len(grid[0])\n        \n        for r in range(self.height):\n            if not self.grid[r][0]:\n                if not self.grid[r][0]:\n                    self.flipRow(r)\n                    \n        for c in range(1, self.width):\n            colSum = self.colSum(c)\n            \n            if colSum < ceil(self.height/2):\n                self.flipCol(c)\n            \n        return self.calcScore()\n        ",382        "solution_js": "var matrixScore = function(grid) {\nlet flip = (i,rowOrCol) => {// helper function for flipping row and column\n    if(rowOrCol){\n        for(let idx in grid[i]){\n            grid[i][idx] = grid[i][idx]===1 ? 0 : 1;\n        }\n    }\n    else{\n        for(let idx in grid){\n            grid[idx][i] = grid[idx][i]===1 ? 0 : 1;\n        }\n    }\n}\n\nfor(let i=0; i<grid.length; i++){// flip rows only if leftmost bit is 0\n    if(grid[i][0]!==1){\n        flip(i,true);\n    }\n}\n\nfor(let i=1; i<grid[0].length; i++){//flip column only if the number of 1s is less than 0s, as all bits hold equal values in a column\n    let ones = 0;\n    for(let j in grid){\n        ones += grid[j][i];\n    }\n    if(ones<grid.length/2) flip(i,false);\n}\n\nreturn grid.reduce((a,b) => a + parseInt(b.join(''),2),0);\n};",383        "solution_java": "class Solution {\n    public int matrixScore(int[][] grid) {\n        ArrayList<Integer> arr=new ArrayList<Integer>();\n        for(int i=0;i<grid.length;i++)\n        {\n            boolean flip=false;\n            if(grid[i][0]==0)\n            {\n                grid[i][0]^=1;\n                flip=true;\n            }\n            if(flip)\n            {\n             for(int j=1;j<grid[0].length;j++)\n            {\n                grid[i][j]^=1;\n            }\n            }\n        }\n        for(int i=1;i<grid[0].length;i++)\n        {\n            int zero=0;\n            int one=0;\n            for(int j=0;j<grid.length;j++)\n            {\n                if(grid[j][i]==0)\n                {\n                    zero++;\n                }\n                else\n                {\n                    one++;\n                }\n            }\n            if(zero>one)\n            {\n                arr.add(i);\n            }\n        }\n        for(int i:arr)\n        {\n            for(int j=0;j<grid.length;j++)\n            {\n                grid[j][i]^=1;\n            }\n        }\n        int sum=0;\n        for(int i=0;i<grid.length;i++)\n        {\n            String num=\"\";\n            for(int j=0;j<grid[0].length;j++)\n            {\n                num+=String.valueOf(grid[i][j]);\n            }\n            sum+=Integer.valueOf(num,2);\n        }\n        return sum;\n    }\n}",384        "solution_c": "class Solution {\npublic:\n    \n    int sum(vector<vector<int>> mat){\n        int score = 0;\n        \n        \n        \n        for(int i=0;i<mat.size();i++){\n            int p = mat[0].size()-1;\n            for(int j=0;j<mat[0].size();j++){\n                score+= mat[i][j]*pow(2,p);\n                p--;\n            }\n        }\n        \n        return score;\n    }\n    \n    int matrixScore(vector<vector<int>>& grid) {\n//         if(grid.size()==1){\n//             return ;\n//         }\n        \n        \n        for(int i=0;i<grid.size();i++){\n            if(grid[i][0]==0){\n               for(int j=0;j<grid[0].size();j++){\n                   if(grid[i][j]==0){\n                       grid[i][j]=1;\n                   }\n                   else{\n                        grid[i][j]=0;\n                   }\n               }\n            }\n        }\n        \n        \n        \n        \n        vector<int> ind;\n        \n        for(int i=1;i<grid[0].size();i++){\n            int ct=0;\n            for(int j=0;j<grid.size();j++){\n                ct+=grid[j][i];\n               \n            }\n            if(ct<=grid.size()/2){\n                ind.push_back(i);\n            }\n        }\n        for(auto v:ind){\n            cout<<v<<\" \";\n        }\n        \n        for(auto c:ind){\n            for(int j=0;j<grid.size();j++){\n                if(grid[j][c]==0){\n                       grid[j][c]=1;\n                   }\n                   else{\n                        grid[j][c]=0;\n                   }\n            }\n        }\n       \n        \n        \n        \n        \n        return sum(grid);\n        \n        \n        \n        \n        \n        \n       \n    }"385    },386    {387        "title": "Longest Substring with At Least K Repeating Characters",388        "algo_input": "Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aaabb\", k = 3\nOutput: 3\nExplanation: The longest substring is \"aaa\", as 'a' is repeated 3 times.\n\n\nExample 2:\n\nInput: s = \"ababbc\", k = 2\nOutput: 5\nExplanation: The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts consists of only lowercase English letters.\n\t1 &lt;= k &lt;= 105\n\n",389        "solution_py": "from collections import Counter\n\nclass Solution:\n    def longestSubstring(self, s: str, k: int) -> int:\n        return get_longest_substring(s, k)\n\ndef get_longest_substring(s, k):\n    if len(s) == 0: return 0\n    c = Counter(s)\n    low_freq_char = set([char for char, freq in c.items() if freq < k])\n    # base case\n    if len(low_freq_char) == 0:\n        return len(s)\n    # recursively split str into substr\n    division_points = [i for i in range(len(s)) if s[i] in low_freq_char]\n    substr_lst = []\n    # start\n    substr_lst.append(s[:division_points[0]])\n    # middle\n    for i in range(len(division_points) - 1):\n        substr_lst.append(s[division_points[i] + 1: division_points[i + 1]])\n    # end\n    substr_lst.append(s[division_points[-1] + 1:])\n    return max([get_longest_substring(substr, k) for substr in substr_lst])",390        "solution_js": "var longestSubstring = function(s, k) {\n    let n = s.length;\n    if(n == 0 || n < k)\n        return 0;\n    if(k == 1)\n        return n;\n    \n    const freq = {};  // object to store the freq of each character ex . { 'a' : 2 , 'b' : 1 ...}\n    \n\t// counting the freq. of each character\n    for(let i=0;i<n;i++)  \n    {\n        let char = s[i];\n        if(freq[char])    // if the character is already present , increase it's freq.\n            freq[char]++;\n        else\n            freq[char] = 1; // else assign the freq. as 1\n    }\n    let i = 0;\n    while(i < n && freq[s[i]] >= k)  // while loop continue till the freq. of character is greater than or equal to k\n        i++;\n    \n    if(i >= n-1) // if i == string.length\n        return i;\n    \n    let left1 = longestSubstring(s.substring(0,i),k);  // dividing the string at index where freq. of character is less than k and calling the func again on the substring\n    \n    while(i < n && freq[s[i]] < k) // ignore the char whose freq. is less than k\n        i++;\n    \n    let right1 = longestSubstring(s.substring(i),k); // second part of the string\n    \n    return Math.max(left1,right1);\n};",391        "solution_java": "// Solution 1: O(n^2) brute force\n// time O(n^2)\n// space O(1)\nclass Solution {\n    public int longestSubstring(String s, int k) {\n        if (s == null || s.isEmpty() || k > s.length()) {\n            return 0;\n        }\n        \n        int[] map = new int[26]; // letter -> freq\n        int n = s.length();\n        int max = 0; // length of longest substring T so far\n        for (int i = 0; i < n; i++) {\n            Arrays.fill(map, 0);\n            for (int j = i; j < n; j++) {\n                map[s.charAt(j) - 'a']++;                \n                if (isValid(s, i, j, k, map)) {\n                    max = Math.max(max, j - i + 1);\n                }\n            }\n        }\n        \n        return max;\n    }\n    \n    // return true if each distinct character in the substring s[left..right] appear >= k times\n    private boolean isValid(String s, int left, int right, int k, int[] map) {\n        int numLetters = 0; // number of distinct letters\n        int numLettersAtLeastK = 0;\n        for (int num : map) {\n            if (num > 0) {\n                numLetters++;\n            }\n            \n            if (num >= k) {\n                numLettersAtLeastK++;\n            }\n        }\n        \n        return numLettersAtLeastK == numLetters;\n    }\n}",392        "solution_c": "/*\n    https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/\n\n    TC: O(26 * n) ~ O(n)\n    SC: O(26)\n\n    At a glance even though it seems like it can be solved with sliding window, it's hard to come\n    up with window condition with the traditional sliding window approach.\n    Problem is what will be your valid window criteria? Since we dont know how many unique chars might\n    come up in the window, we dont know whether we should shrink the window or even though few of the\n    unique chars have at least k instances.\n\n    So we change the problem a bit. We change the window criteria:\n    Find the max length window with atmost X unique chars. This is easier problem to deal with.\n    The shrinking window criteria is clear, also we also keep track of chars in the window\n    with frequency >= k while solving this problem.\n\n    Now since we are limiting the no. of unique chars, we need to run the above |unique chars in s| times.\n*/\nclass Solution {\npublic:\n    int uniqueChars(string& s) {\n        unordered_set<char> chars(s.begin(), s.end());\n        return chars.size();\n    }\n\n    int longestSubstring(string s, int k) {\n        // find the no. of unique chars in string\n        int max_unique_chars = uniqueChars(s);\n        int max_len = 0, n = s.size();\n\n        for(int curr_unique_chars = 1; curr_unique_chars <= max_unique_chars; curr_unique_chars++) {\n            int start = 0, end = 0;\n            int atleast_k = 0;\n            unordered_map<char, int> freq;\n\n            // Process the max length window with at max curr_unique_chars unique chars\n            while(end < n) {\n                // attempt window expansion\n                if(++freq[s[end]] == k)\n                    ++atleast_k;\n                ++end;\n\n                // shrink the window if unique chars exceeds the limit\n                while(freq.size() > curr_unique_chars && start <= end) {\n                    // Current char contributed to atleast_k count, so it's count will be lesser than k now\n                    if(freq[s[start]] == k)\n                        --atleast_k;\n                    if(--freq[s[start]] == 0)\n                        freq.erase(s[start]);\n                    ++start;\n                }\n                // If the current window has required no. of chars and it also each unique\n                // chars have atleast k instances\n                if(freq.size() == curr_unique_chars && atleast_k == freq.size())\n                    max_len = max(max_len, end - start);\n            }\n        }\n        return max_len;\n    }\n};"393    },394    {395        "title": "Greatest Common Divisor of Strings",396        "algo_input": "For two strings s and t, we say \"t divides s\" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).\n\nGiven two strings str1 and str2, return the largest string x such that x divides both str1 and str2.\n\n&nbsp;\nExample 1:\n\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\n\n\nExample 2:\n\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\n\n\nExample 3:\n\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= str1.length, str2.length &lt;= 1000\n\tstr1 and str2 consist of English uppercase letters.\n\n",397        "solution_py": "class Solution:\n    def gcdOfStrings(self, str1: str, str2: str) -> str:\n\n        if len(str2) > len(str1):\n            str1, str2 = str2, str1\n\n        curr_str2 = str2\n        while True:\n\n            rep = len(str1)//len(curr_str2)\n\n            if curr_str2*rep == str1:\n                return curr_str2\n\n            found = False\n            for i in range(len(curr_str2)-1, 1, -1):\n                try_str2 = curr_str2[:i]\n                rep2 = len(str2)//len(try_str2)\n\n                if try_str2*rep2 == str2:\n                    curr_str2 = try_str2\n                    found = True\n                    break\n\n            if not found:\n                break\n        return \"\"",398        "solution_js": "/**\n * @param {string} str1\n * @param {string} str2\n * @return {string}\n */\nvar gcdOfStrings = function(str1, str2) {\n  const gcdOfNumber = (num1, num2) => {\n    while (num2 !== 0) {\n      const res = num2 % num1\n      num1 = num2\n      num2 = res\n    }\n    return num1\n  }\n  const gcd = gcdOfNumber(str1.length, str2.length)\n  const common = str1.slice(0, gcd)\n  return common.repeat(str1.length / gcd) === str1 &&\n    common.repeat(str2.length / gcd) === str2\n    ? common\n    : ''\n}",399        "solution_java": "class Solution {\n    public String gcdOfStrings(String str1, String str2) {\n        \n        int length1 = str1.length();\n        int length2 = str2.length();\n        String temp;\n        \n        for(int i=gcd(length1,length2); i>0 && length1 % i == 0 && length2 % i == 0; i--) {\n            if(str1.substring(0,i).equals(str2.substring(0,i))) {\n                if(doesRepeat(str1.substring(0,i),str1,str2))\n                    return str1.substring(0,i);\n            }\n        }\n        return \"\";\n        \n    }\n    public int gcd(int a, int b) {\n        if(b==0)\n            return a;\n        return gcd(b,a % b);\n    }\n    public boolean doesRepeat(String s, String str1, String str2) {\n        int sLength = s.length();\n        boolean bool1 = true, bool2 = true;\n        String temp = str1,temp2;\n        \n        while(sLength < temp.length()) {\n            temp2 = temp.substring(sLength,sLength*2);\n            \n            if(s.equals(temp2));\n            else\n                bool1 = false;\n            temp = temp.substring(sLength,temp.length());\n        }\n        temp = str2;\n        while(sLength < temp.length()) {\n            temp2 = temp.substring(sLength,sLength*2);\n            if(s.equals(temp2));\n            else\n                bool2 = false;\n            temp = temp.substring(sLength,temp.length());\n        }\n        return bool1 && bool2;\n    }\n    \n}",400        "solution_c": "class Solution {\npublic:\n    string gcdOfStrings(string str1, string str2) {\n        int m = str1.length(), n = str2.length();\n        int temp = __gcd(m, n);\n        string str;\n        if(str1 + str2 == str2 + str1) str = str1.substr(0, temp);\n        return str;\n    }\n};"401    },402    {403        "title": "Smallest Subtree with all the Deepest Nodes",404        "algo_input": "Given the root of a binary tree, the depth of each node is the shortest distance to the root.\n\nReturn the smallest subtree such that it contains all the deepest nodes in the original tree.\n\nA node is called the deepest if it has the largest depth possible among any node in the entire tree.\n\nThe subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.\n\n&nbsp;\nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.\n\n\nExample 2:\n\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree.\n\n\nExample 3:\n\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 500].\n\t0 &lt;= Node.val &lt;= 500\n\tThe values of the nodes in the tree are unique.\n\n\n&nbsp;\nNote: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/\n",405        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n\n        # find a set of deepest nodes first\n        deepest_nodes = [0]\n        self.find_deepest(root, 0, deepest_nodes)\n        \n        # extract the depth and also make a set out of the values\n        targets = set(deepest_nodes[1:])\n\n        # get the subtree\n        return self.find_merge(root, targets)[0]\n\n    def find_deepest(self, node, current_depth, deepest_nodes):\n\n        # make a check\n        if not node:\n            return\n        \n        # make a check if we are a deep node\n        if current_depth > deepest_nodes[0]:\n            deepest_nodes.clear()\n            deepest_nodes.append(current_depth)\n            deepest_nodes.append(node.val)\n        elif current_depth == deepest_nodes[0]:\n            deepest_nodes.append(node.val)\n        \n        # go deeper\n        self.find_deepest(node.left, current_depth+1, deepest_nodes)\n        self.find_deepest(node.right, current_depth+1, deepest_nodes)\n    \n    def find_merge(self, node, targets):\n\n        # make a check\n        if not node:\n            return None, set()\n\n        # check whether we are a target\n        found = set()\n        if node.val in targets:\n            found.add(node.val)\n\n        # go deeper and get result nodes\n        nleft, left = self.find_merge(node.left, targets)\n        if nleft is not None:\n            return nleft, set()\n        nright, right = self.find_merge(node.right, targets)\n        if nright is not None:\n            return nright, set()\n\n        # merge the found set\n        found = found | left | right\n\n        # check whether we found all\n        if not (targets - found):\n            return node, set()\n        else:\n            return None, found",406        "solution_js": "var subtreeWithAllDeepest = function(root) {\n    // keep track of deepest till now\n    // if left right has both deepest than it will be the ans;\n    let mx = 0, rm = 0, ans = null;\n    const compute = (r = root, d = 0) => {\n        if(!r) {\n            rm = Math.max(rm, d);\n            return d;\n        }\n        const ld = compute(r.left, d + 1);\n        const rd = compute(r.right, d + 1);\n        \n        if(ld == rd && ld == mx) {\n            ans = r;\n        }\n        if(mx < rm) {\n            ans = r;\n            mx = rm;\n        }\n        \n        return Math.max(ld, rd);\n    }\n    compute();\n    return ans;\n};",407        "solution_java": "class Solution {\n    public TreeNode subtreeWithAllDeepest(TreeNode root) {\n\t\tif (root.left == null && root.right == null) return root;\n        int depth = findDepth(root);\n        Queue<TreeNode> q = new LinkedList<>();\n        q.offer(root);\n        int count = 0;\n        while (!q.isEmpty()) {\n            int size = q.size();\n            count++;\n            if (count == depth) {\n                break;\n            }\n            for (int i = 0; i < size; i++) {\n                TreeNode cur = q.poll();\n                if (cur.left != null) q.offer(cur.left);\n                if (cur.right != null) q.offer(cur.right);\n            }\n        }\n        Set<Integer> set = new HashSet<>();\n        while (!q.isEmpty()) {\n            set.add(q.poll().val);\n        }\n        return find(root, set);\n    }\n    \n    public int findDepth(TreeNode root) {\n        if (root == null) return 0;\n        int left = findDepth(root.left);\n        int right = findDepth(root.right);\n        return 1 + Math.max(left, right);\n    }\n    \n    public TreeNode find(TreeNode root, Set<Integer> set) {\n        if (root == null) return root;\n        if (set.contains(root.val)) return root;\n        TreeNode left = find(root.left, set);\n        TreeNode right = find(root.right, set);\n        if (left != null && right != null) return root;\n        else if (left != null) return left;\n        else if (right != null) return right;\n        else return null;\n    }\n}",408        "solution_c": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    void help(TreeNode* root, TreeNode* par, map<TreeNode*,TreeNode*> &m)\n    {\n        if(root==NULL)\n            return;\n        m[root]=par;\n        help(root->left,root,m);\n        help(root->right,root,m);\n    }\n    TreeNode* subtreeWithAllDeepest(TreeNode* root) \n    {\n        TreeNode* r=root;\n        map<TreeNode*,TreeNode*>m;\n        help(r,NULL,m);\n        queue<TreeNode*>q;\n        vector<TreeNode*>ans;\n        q.push(root);  \n        while(!q.empty())\n        {\n            int s=q.size();\n            vector<TreeNode*>a;\n            for(int i=0;i<s;i++)\n            {\n                TreeNode* bgn=q.front();\n                q.pop();\n                a.push_back(bgn);\n                if(bgn->left!=NULL)\n                    q.push(bgn->left);\n                if(bgn->right!=NULL)\n                    q.push(bgn->right);\n            }\n            ans=a;\n        }\n        if(ans.size()==1)\n            return ans[0];\n        set<TreeNode*>s;\n        while(s.size()!=1)\n        {\n            s.clear();\n            for(int i=0;i<ans.size();i++)\n            {\n                ans[i]=m[ans[i]];\n            }\n            s.insert(ans.begin(),ans.end());\n        }\n        for(auto i : s)\n        {\n            return i;\n        }\n        return NULL;\n    }\n};"409    },410    {411        "title": "Uncommon Words from Two Sentences",412        "algo_input": "A sentence is a string of single-space separated words where each word consists only of lowercase letters.\n\nA word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.\n\nGiven two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.\n\n&nbsp;\nExample 1:\nInput: s1 = \"this apple is sweet\", s2 = \"this apple is sour\"\nOutput: [\"sweet\",\"sour\"]\nExample 2:\nInput: s1 = \"apple apple\", s2 = \"banana\"\nOutput: [\"banana\"]\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s1.length, s2.length &lt;= 200\n\ts1 and s2 consist of lowercase English letters and spaces.\n\ts1 and s2 do not have leading or trailing spaces.\n\tAll the words in s1 and s2 are separated by a single space.\n\n",413        "solution_py": "from collections import Counter\nclass Solution:\n    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:\n        x = dict(Counter(s1.split() + s2.split()))\n        ans = []\n        for key in x:\n            if x[key] == 1:\n                ans.append(key)\n                \n        return ans",414        "solution_js": "var uncommonFromSentences = function(s1, s2) {\n    return (s1+' '+s2).split(' ').filter((el,i,arr)=>arr.indexOf(el)===arr.lastIndexOf(el))\n};",415        "solution_java": "class Solution {\n    public String[] uncommonFromSentences(String s1, String s2) {\n        List<String> list=new LinkedList<>();\n        Map<String, Integer> map=new HashMap<>();\n        String[] arr1=s1.split(\" \");\n        String[] arr2=s2.split(\" \");\n        for(int i=0;i<arr1.length;i++){\n            map.put(arr1[i],map.getOrDefault(arr1[i],0)+1);\n        }\n        for(int i=0;i<arr2.length;i++){\n            map.put(arr2[i],map.getOrDefault(arr2[i],0)+1);\n        }\n        for(Map.Entry<String, Integer> entry:map.entrySet()){\n            if(entry.getValue()==1)\n                list.add(entry.getKey());\n        }\n        String[] res=new String[list.size()];\n        for(int i=0;i<res.length;i++){\n            res[i]=list.get(i);\n        }\n        return res;\n    }\n}",416        "solution_c": "class Solution {\npublic:\n    void uncommon(string s,unordered_map<string,int>&mp) {\n        string word=\"\";\n        for(int i=0; i<s.size(); i++) {\n                if(s[i]==' ') {\n                     mp[word]++;\n                     word=\"\";\n                }else {\n                     word+=s[i];\n                }\n        }\n        mp[word]++;\n    }\n    vector<string> uncommonFromSentences(string s1, string s2) {\n        vector<string> ans;\n        unordered_map<string,int> mp;\n        uncommon(s1,mp);\n        uncommon(s2,mp);\n        for(pair<string,int> p : mp) {\n            if(p.second==1) ans.push_back(p.first);\n        }\n        return ans;\n    }\n};"417    },418    {419        "title": "Find the Kth Largest Integer in the Array",420        "algo_input": "You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.\n\nReturn the string that represents the kth largest integer in nums.\n\nNote: Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"], \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer.\n\n&nbsp;\nExample 1:\n\nInput: nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\nOutput: \"3\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4th largest integer in nums is \"3\".\n\n\nExample 2:\n\nInput: nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\nOutput: \"2\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rd largest integer in nums is \"2\".\n\n\nExample 3:\n\nInput: nums = [\"0\",\"0\"], k = 2\nOutput: \"0\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2nd largest integer in nums is \"0\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 104\n\t1 &lt;= nums[i].length &lt;= 100\n\tnums[i] consists of only digits.\n\tnums[i] will not have any leading zeros.\n\n",421        "solution_py": "class Solution:\n    def kthLargestNumber(self, nums: List[str], k: int) -> str:\n        nums = sorted(map(int, nums), reverse=True)\n        return str(nums[k-1])",422        "solution_js": "var kthLargestNumber = function(nums, k) {\n    const n = nums.length;\n    k = n - k; \n    \n    return quickSelect(nums, k, 0, n - 1);\n    \n    \n    function quickSelect(arr, selectIdx, left, right) {\n        const pivotIdx = Math.floor(Math.random() * (right - left + 1) + left);\n        const pivotNum = arr[pivotIdx];\n        \n        swap(arr, pivotIdx, right);\n        \n        let swapIdx = left;\n        \n        for (let i = left; i < right; i++) {\n            if (compare(arr[i], pivotNum) < 0) {\n                swap(arr, swapIdx, i);\n                swapIdx++;\n            }\n        }\n        \n        swap(arr, swapIdx, right);\n        \n        if (swapIdx === selectIdx) return arr[selectIdx];\n        \n        if (swapIdx > selectIdx) return quickSelect(arr, selectIdx, left, swapIdx - 1);\n        if (swapIdx < selectIdx) return quickSelect(arr, selectIdx, swapIdx + 1, right);\n    }\n    \n    \n    function compare(numStr1, numStr2) {\n        if (numStr1.length > numStr2.length) return 1;\n        if (numStr2.length > numStr1.length) return -1;\n        \n        return numStr1.localeCompare(numStr2);\n    }\n    \n    function swap(arr, i, j) {\n        [arr[i], arr[j]] = [arr[j], arr[i]];\n    }\n};",423        "solution_java": "class Solution {\n    public String kthLargestNumber(String[] nums, int k) {\n        \n        int n=nums.length;\n        \n        Arrays.sort(nums,(a,b)->{\n            if(a.length()>b.length()) return 1;\n            else if(b.length()>a.length()) return -1;\n            else{\n              return isgreater(a,b);   \n            }\n        });\n        return nums[n-k];        \n    }\n    \n    public static int isgreater(String a,String b){\n        \n        int n=a.length();\n        \n        for(int i=0;i<n;i++){\n            int a1=Integer.parseInt(\"\"+a.charAt(i));\n            int b1=Integer.parseInt(\"\"+b.charAt(i));\n            if(a1>b1) return 1;\n            if(b1>a1) return -1;\n        }\n        return 0;\n    }\n}",424        "solution_c": "class Solution {\npublic:\n    static bool cmp(string &a,string &b)\n    {\n        if(a.size()==b.size())\n        {\n            return a<b;\n        }\n        return a.size()<b.size();\n    }\n    string kthLargestNumber(vector<string>& nums, int k)\n    {\n        sort(nums.begin(),nums.end(),cmp);\n        int n=nums.size();\n        return nums[n-k];\n    }\n};"425    },426    {427        "title": "Partition to K Equal Sum Subsets",428        "algo_input": "Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,3,2,3,5,2,1], k = 4\nOutput: true\nExplanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4], k = 3\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= nums.length &lt;= 16\n\t1 &lt;= nums[i] &lt;= 104\n\tThe frequency of each element is in the range [1, 4].\n\n",429        "solution_py": "class Solution:\n    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n        def dfs(idx,curr,cnt,limit):\n            if cnt == k:\n                return True\n            if curr ==limit:\n                return dfs(0,0,cnt+1,limit)\n\n            i = idx\n            while i < len(nums):\n                if visited[i] or nums[i]+curr > limit:\n                    i += 1\n                    continue\n                visited[i] = True\n                if dfs(i+1,curr+nums[i],cnt,limit):\n                    return True\n                visited[i] = False\n\n                while i+1 < len(nums) and nums[i] == nums[i+1]: #pruning1\n                    i += 1\n                if curr == 0 or curr + nums[i] == limit: #pruning2\n                    return False\n                i += 1\n            return False\n\n        if len(nums) < k or sum(nums) % k:\n            return False\n        numSum = sum(nums)\n\n        for i in range(len(nums)):\n            if nums[i] > numSum//k:\n                return False\n\n        visited = [False]*len(nums)\n        return dfs(0,0,0,numSum//k)",430        "solution_js": "var canPartitionKSubsets = function(nums, k) {\n    const sum = nums.reduce((sum, num) => sum + num);\n    const divide = sum / k;\n    if (!Number.isInteger(divide)) return false;\n    const subsets = Array(k).fill(0);\n    const dfs = (index = 0) => {\n        if (index >= nums.length) return true;\n        const visited = new Set();\n        const num = nums[index];\n\n        for (let sub = 0; sub < k; sub++) {\n            const subset = subsets[sub];\n            if (visited.has(subset) || subset + num > divide) continue;\n\n            visited.add(subset);\n            subsets[sub] += num;\n            if (dfs(index + 1)) return true;\n            subsets[sub] -= num;\n        }\n        return false;\n    };\n\n    nums.sort((a, b) => b - a);\n    return dfs();\n};",431        "solution_java": "class Solution {\n    private final List<Set<Integer>> allSubsets = new ArrayList<>();\n    public boolean canPartitionKSubsets(int[] nums, int k) {\n        int sum = Arrays.stream(nums).sum();\n        if(sum % k != 0) return false;\n        getAllSubsets(nums.length, sum / k, new HashSet<>(), nums, false);\n        return allSubsets.size() >= k && canPartition(allSubsets.size(), k, nums.length, new HashSet<>());\n    }\n\n    private boolean canPartition(int n, int k, int size, Set<Integer> current) {\n        if(k == 0 && current.size() == size) return true;\n        if(n == 0 || k < 0) return false;\n        boolean addSet = false;\n        if(allUnique(current, allSubsets.get(n-1))) {\n            current.addAll(allSubsets.get(n - 1));\n            addSet = canPartition(n - 1, k - 1, size, current);\n            current.removeAll(allSubsets.get(n - 1));\n        }\n        return addSet || canPartition(n - 1, k, size, current);\n    }\n\n    private void getAllSubsets(int n, int targetSum, Set<Integer> subsets, int[] nums, boolean lol) {\n        if(targetSum == 0) {\n            allSubsets.add(new HashSet<>(subsets));\n            return;\n        }\n        if (n == 0 || targetSum < 0) return;\n        subsets.add(n-1);\n        getAllSubsets(n-1, targetSum - nums[n-1], subsets, nums, true);\n        subsets.remove(n-1);\n        getAllSubsets(n-1, targetSum, subsets, nums, false);\n    }\n    \n    private boolean allUnique(Set<Integer> set1, Set<Integer> set2) {\n        for (Integer num: set1) if(set2.contains(num)) return false;\n        return true;\n    }\n}",432        "solution_c": "class Solution {\npublic:\n    unordered_map<string, int> dp;\n    int solve(vector<int>& nums, int target, int remain, int i, int vis, int k){\n        if( k == 1) return 1;\n\n        //memorization addition\n        string t = to_string(i)+\"_\"+to_string(remain)+\"_\"+to_string(k)+\"_\"+to_string(vis);\n        if(dp.find(t) != dp.end()) return dp[t];\n\n        if(remain == 0){\n            return dp[t] = solve(nums, target, target, nums.size()-1, vis, k - 1);\n        }\n        for(int j = i; j >= 0; --j){\n            if(((vis>>j)& 1) || remain - nums[j] < 0) continue;\n            vis = vis | (1 << j );\n            if(solve(nums, target, remain - nums[j], j - 1, vis, k) ) return dp[t] = 1;\n            vis = vis & ~(1<<j);\n        }\n        return dp[t] = 0;\n    }\n    bool canPartitionKSubsets(vector<int>& nums, int k) {\n        int sum = accumulate(nums.begin(), nums.end(), 0);\n        if(sum%k != 0) return false;\n        int vis = 0;\n        return solve(nums, sum/k, sum/k, nums.size()-1, vis, k);\n    }\n};"433    },434    {435        "title": "Find Array Given Subset Sums",436        "algo_input": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).\n\nReturn the array ans of length n representing the unknown array. If multiple answers exist, return any of them.\n\nAn array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.\n\nNote: Test cases are generated such that there will always be at least one correct answer.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput: [1,2,-3]\nExplanation: [1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.\n\n\nExample 2:\n\nInput: n = 2, sums = [0,0,0,0]\nOutput: [0,0]\nExplanation: The only correct answer is [0,0].\n\n\nExample 3:\n\nInput: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput: [0,-1,4,5]\nExplanation: [0,-1,4,5] is able to achieve the given subset sums.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 15\n\tsums.length == 2n\n\t-104 &lt;= sums[i] &lt;= 104\n\n",437        "solution_py": "class Solution:\n    def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n        res = [] # Result set\n        sums.sort()\n\n        while len(sums) > 1:\n            num = sums[-1] - sums[-2] # max - secondMax\n            countMap = Counter(sums) # Get count of each elements\n            excluding = [] # Subset sums that do NOT contain num\n            including = [] # Subset sums that contain num\n\n            for x in sums:\n                if countMap.get(x) > 0:\n                    excluding.append(x)\n                    including.append(x+num)\n                    countMap[x] -= 1\n                    countMap[x+num] -= 1\n\n            # Check validity of excluding set\n            if 0 in excluding:\n                sums = excluding\n                res.append(num)\n            else:\n                sums = including\n                res.append(-1*num)\n\n        return res",438        "solution_js": "/**\n * @param {number} n\n * @param {number[]} sums\n * @return {number[]}\n */\nvar recoverArray = function(n, sums) {\n    sums.sort((a, b) => a - b);\n    let result = [];\n    \n    while (sums.length > 1) {\n        let num = sums[sums.length - 1] - sums[sums.length - 2],\n            excluding = [],\n            including = [],\n            counter = new Map();\n        for (let item of sums) {\n            let count = counter.get(item);\n            if (count) {\n                counter.set(item, count + 1);\n            } else {\n                counter.set(item, 1);\n            }\n        }\n        \n        for (let item of sums) {\n            if (counter.get(item) > 0) {\n                excluding.push(item);\n                including.push(item + num);\n                counter.set(item, counter.get(item) - 1);\n                counter.set(item + num, counter.get(item + num) - 1);\n            }\n        }\n        \n        if (excluding.indexOf(0) !== -1) {\n            sums = excluding;\n            result.push(num);\n        } else {\n            sums = including;\n            result.push(-1 * num);\n        }\n    }\n    \n    return result;\n};",439        "solution_java": "class Solution {\n    public int[] recoverArray(int n, int[] sums) {\n        Arrays.sort(sums);\n        int m = sums.length;\n        int[] res = new int[n], left = new int[m / 2], right = new int[m / 2];\n        for (int i = 0; i < n; ++i) {\n            int diff = sums[1] - sums[0], hasZero = 0, p = -1, q = -1, k = 0;\n            for (int j = 0; j < m; ++j) {\n                if (k <= q && right[k] == sums[j]) k++;\n                else {\n                    if (0 == sums[j]) hasZero = 1;\n                    left[++p] = sums[j];\n                    right[++q] = sums[j] + diff;\n                }\n            }\n            if (1 == hasZero) {\n                res[i] = diff;\n                sums = left;\n            } else {\n                res[i] = -diff;\n                sums = right;\n            }\n            m /= 2;\n        }\n        return res;\n    }\n}",440        "solution_c": "class Solution {\npublic:\n    vector<int> recoverArray(int n, vector<int>& sums) {\n        sort(sums.begin(), sums.end());\n\n        vector<int> ans;\n        while (n--) {\n            int diff = sums[1] - sums[0];\n            unordered_map<int, int> freq;\n            vector<int> ss0, ss1;\n            bool on = false;\n            for (auto& x : sums)\n                if (!freq[x]) {\n                    ss0.push_back(x);\n                    freq[x+diff]++;\n                    if (x == 0) on = true;\n                } else {\n                    ss1.push_back(x);\n                    freq[x]--;\n                }\n            if (on) {\n                ans.push_back(diff);\n                sums = ss0;\n            } else {\n                ans.push_back(-diff);\n                sums = ss1;\n            }\n        }\n        return ans;\n    }\n};"441    },442    {443        "title": "Add Digits",444        "algo_input": "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.\n\n&nbsp;\nExample 1:\n\nInput: num = 38\nOutput: 2\nExplanation: The process is\n38 --&gt; 3 + 8 --&gt; 11\n11 --&gt; 1 + 1 --&gt; 2 \nSince 2 has only one digit, return it.\n\n\nExample 2:\n\nInput: num = 0\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 231 - 1\n\n\n&nbsp;\nFollow up: Could you do it without any loop/recursion in O(1) runtime?\n",445        "solution_py": "class Solution:\n    def addDigits(self, num: int) -> int:\n        while num > 9:\n            num = num % 10 + num // 10\n        return num",446        "solution_js": "var addDigits = function(num) {\n    return 1 + (num - 1) % 9;\n};",447        "solution_java": "class Solution {\n    public int addDigits(int num) {\n        if(num == 0) return 0;\n        else if(num % 9 == 0) return 9;\n        else return num % 9;\n    }\n}",448        "solution_c": "class Solution {\npublic:\n    int addDigits(int n) {\n        return n < 10 ? n : addDigits(n / 10 + n % 10);\n    }\n};"449    },450    {451        "title": "Tag Validator",452        "algo_input": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.\n\nA code snippet is valid if all the following rules hold:\n\n\n\tThe code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\n\tA closed tag (not necessarily valid) has exactly the following format : &lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;. Among them, &lt;TAG_NAME&gt; is the start tag, and &lt;/TAG_NAME&gt; is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.\n\tA valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.\n\tA valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched &lt;, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.\n\tA start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.\n\tA &lt; is unmatched if you cannot find a subsequent &gt;. And when you find a &lt; or &lt;/, all the subsequent characters until the next &gt; should be parsed as TAG_NAME (not necessarily valid).\n\tThe cdata has the following format : &lt;![CDATA[CDATA_CONTENT]]&gt;. The range of CDATA_CONTENT is defined as the characters between &lt;![CDATA[ and the first subsequent ]]&gt;.\n\tCDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.\n\n\n&nbsp;\nExample 1:\n\nInput: code = \"&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;\"\nOutput: true\nExplanation: \nThe code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.\n\n\nExample 2:\n\nInput: code = \"&lt;DIV&gt;&gt;&gt;  ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;\"\nOutput: true\nExplanation:\nWe first separate the code into : start_tag|tag_content|end_tag.\nstart_tag -&gt; \"&lt;DIV&gt;\"\nend_tag -&gt; \"&lt;/DIV&gt;\"\ntag_content could also be separated into : text1|cdata|text2.\ntext1 -&gt; \"&gt;&gt;  ![cdata[]] \"\ncdata -&gt; \"&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;\", where the CDATA_CONTENT is \"&lt;div&gt;]&gt;\"\ntext2 -&gt; \"]]&gt;&gt;]\"\nThe reason why start_tag is NOT \"&lt;DIV&gt;&gt;&gt;\" is because of the rule 6.\nThe reason why cdata is NOT \"&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;\" is because of the rule 7.\n\n\nExample 3:\n\nInput: code = \"&lt;A&gt;  &lt;B&gt; &lt;/A&gt;   &lt;/B&gt;\"\nOutput: false\nExplanation: Unbalanced. If \"&lt;A&gt;\" is closed, then \"&lt;B&gt;\" must be unmatched, and vice versa.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= code.length &lt;= 500\n\tcode consists of English letters, digits, '&lt;', '&gt;', '/', '!', '[', ']', '.', and ' '.\n\n",453        "solution_py": "class Solution:\n    def isValid(self, code: str) -> bool:\n        if code[0] != '<' or code[-1] != '>': return False\n        i, n = 0, len(code)\n        stk = []\n        while i < n:\n            if code[i] == '<':\n                if i != 0 and code[i: i + 9] == '<![CDATA[':\n                    if not stk: return False\n                    j = i + 9\n                    while j + 3 <= n and code[j: j + 3] != ']]>': j += 1\n                    if code[j: j + 3] == ']]>': i = j + 3\n                    else: return False\n                else:\n                    start = i\n                    isend = False\n                    i += 1\n                    if i >= n: return False\n                    if code[i] == r'/':\n                        isend = True\n                        i += 1\n                    if i >= n: return False\n                    tag = ''\n                    while i < n and code[i] != '>':\n                        if not code[i].isupper(): return False\n                        tag += code[i]\n                        i += 1\n                    if i >= n or len(tag) == 0 or len(tag) > 9: return False\n                    if isend:\n                        if not stk or stk[-1] != tag: return False\n                        stk.pop(-1)\n                    else:\n                        if start != 0 and not stk: return False\n                        stk.append(tag)\n                    i += 1\n            else:\n                if not stk: return False\n                while i < n and code[i] != '<': i += 1\n        return not stk",454        "solution_js": "class Solution {\n    class Tag {\n    public:\n        string value;\n        bool isStart;\n        Tag():value(\"\"), isStart(true){}\n        Tag(string value, bool isStart):value(value), isStart(isStart){}\n    };\n    \n    pair<int, bool> parseCData(string& s, int pos) {\n        //cout << \"Parse cdata \" << s.substr(pos) << endl;  \n        const string startPattern = \"<![CDATA[\";\n        if (s.find(startPattern, pos) != pos) {\n            return {pos, false};\n        }\n        \n        const string endPattern = \"]]>\";\n        int end = s.find(endPattern, pos);\n        if (end == -1) {\n            return {pos, false};\n        }\n        return {end+3, true};\n    }\n    \n    pair<Tag, bool> parseTag(string& s, int& pos) {\n        //cout << \"Parse tag \" << s.substr(pos) << endl;\n        Tag res;\n        if (pos+1 == s.length()) return {res, false};\n        if (s[pos+1] == '/') {\n            res.isStart = false;\n            pos++;\n        }\n        pos++;\n        int end = s.find(\">\", pos);\n        if (end == -1 || end-pos < 1 || end-pos > 9) return {res, false};\n        string name = s.substr(pos, end-pos);\n        for (char& c : name) {\n            if (c < 'A' || c > 'Z') return {res, false};\n        }\n        res.value = name;\n        pos = end+1;\n        return {res, true};\n    }\n    bool isValid(vector<Tag>& tags, int start, int end) {\n        //cout << start << \" \" << end << endl;\n        if (start > end) return true;\n        if (!tags[start].isStart) return false;\n        int k = start+1;\n        int c = 1;\n        while (k <= end && c > 0) {\n            if (tags[k].value == tags[start].value) {\n                c += (tags[k].isStart) ? 1 : -1;\n            }\n            k++;\n        }\n        if (c != 0) return false;\n        k--;\n        return isValid(tags, start+1, k-1) && isValid(tags, k+1, end);\n    }\npublic:\n    bool isValid(string code) {\n        vector<Tag> tags;\n        int n = code.length();\n        int i = 0;\n        while (i < n) {\n            int k = i;\n            while (k < n && code[k] != '<') {\n                k++;\n            }\n            if (k > i) {\n                if (i == 0) return false;\n                i = k;\n                if (i == n) return false;\n            } else {\n                if (code[k+1] == '!') {\n                    if (i == 0) return false;\n                    auto cdata = parseCData(code, k);\n                    if (!cdata.second) return false;\n                    i = cdata.first;\n                    if (i == n) return false;\n                } else {\n                    auto tag = parseTag(code, i);\n                    if (!tag.second) return false;\n                    if (i == n && tag.first.isStart) return false;\n                    tags.push_back(tag.first);\n                }\n            }\n        }\n        if (tags.size() < 2) return false;\n        int m = tags.size();\n        if (tags[0].value != tags[m-1].value || !tags[0].isStart || tags[m-1].isStart){\n            return false;\n        }\n        return isValid(tags, 1, m-2);\n    }\n};",455        "solution_java": "class Solution {\n    // for the ease to check CDATA starting tag\n    private static final char[] CDATA_TAG = {'[','C','D','A','T','A','['};\n    public boolean isValid(String code) {\n        // make sure it is possible to have a start tag and an end tag\n        if (!code.startsWith(\"<\") || !code.endsWith(\">\")) {\n            return false;\n        }\n        Deque<String> stack = new ArrayDeque<>();\n        for (int i = 0; i < code.length(); ++i) {\n            char ch = code.charAt(i);\n            // if it is a special tag\n            if (ch == '<') {\n                if (i == code.length() - 1) {\n                    return false;\n                }\n                ch = code.charAt(++i);\n                // is end tag\n                if (ch == '/') {\n                    // we should have a start tag to match the end tag\n                    if (stack.isEmpty()) {\n                        return false;\n                    }\n                    // get the end tag\n                    StringBuilder sb = new StringBuilder();\n                    // build tag and move i to the > for the next round\n                    i = buildTag(code, i + 1, sb);\n                    // if tag is unmatch, return false\n                    if (!stack.pop().equals(sb.toString())) {\n                        return false;\n                    }\n                    // if no start tag left and we are not at the end. The rest content is not enclosed. -> false\n                    if (stack.isEmpty() && i < code.length() - 1) {\n                        return false;\n                    }\n                } else if (ch == '!') { // is CDATA tag\n                    // check if CDATA is encoded in a tag\n                    if (stack.isEmpty()) {\n                        return false;\n                    }\n                    // check CDATA and move i to the end of ]]> for the next round\n                    i = validAndMoveCDATA(code, i + 1);\n                    // the above function return -1 if CDATA is not valid\n                    if (i < 0) {\n                        return false;\n                    }\n                } else { // start tag\n                    // TAG_NAME should not empty\n                    if (ch == '>') {\n                        return false;\n                    }\n                    StringBuilder sb = new StringBuilder();\n                    i = buildTag(code, i , sb);\n                    // TAG_NAME should less than 9\n                    if (sb.isEmpty() || sb.length() > 9) {\n                        return false;\n                    }\n                    stack.push(sb.toString());\n                }\n            }\n        }\n        return stack.isEmpty();\n    }\n\n    private int buildTag(String code, int start, StringBuilder sb) {\n        int i = start;\n        // we only go to 10 because the max length is 9\n        for (; i < start + 10 && i < code.length(); ++i) {\n            char ch = code.charAt(i);\n            // find the end;\n            if (ch == '>') {\n                break;\n            }\n            // TAG_NAME should be in uppercase only\n            if (!Character.isUpperCase(ch)) {\n                // clear the string builder for invalid TAG_NAME\n                sb.setLength(0);\n                break;\n            }\n            sb.append(ch);\n        }\n        return i;\n    }\n\n    private int validAndMoveCDATA(String code, int start) {\n        // the length of [CDATA[]]> is 10 we need at least 10 characters left\n        if (code.length() - start < 10) {\n            return -1;\n        }\n        // check the start part\n        int i = start;\n        for (int j = 0; j < CDATA_TAG.length; ++j) {\n            char ch = code.charAt(i++);\n            if (ch != CDATA_TAG[j]) {\n                return -1;\n            }\n        }\n        // keep the last two characters for identifying the end\n        char prev0 = '\\0';\n        char prev1 = '\\0';\n\n        for (; i < code.length(); ++i) {\n            char ch = code.charAt(i);\n            if (ch == '>' && prev1 == ']' && prev0 == ']') {\n                return i;\n            }\n            prev0 = prev1;\n            prev1 = ch;\n        }\n        // no end found\n        return -1;\n    }\n}",456        "solution_c": "class Solution {\n    class Tag {\n    public:\n        string value;\n        bool isStart;\n        Tag():value(\"\"), isStart(true){}\n        Tag(string value, bool isStart):value(value), isStart(isStart){}\n    };\n\n    pair<int, bool> parseCData(string& s, int pos) {\n        //cout << \"Parse cdata \" << s.substr(pos) << endl;\n        const string startPattern = \"<![CDATA[\";\n        if (s.find(startPattern, pos) != pos) {\n            return {pos, false};\n        }\n\n        const string endPattern = \"]]>\";\n        int end = s.find(endPattern, pos);\n        if (end == -1) {\n            return {pos, false};\n        }\n        return {end+3, true};\n    }\n\n    pair<Tag, bool> parseTag(string& s, int& pos) {\n        //cout << \"Parse tag \" << s.substr(pos) << endl;\n        Tag res;\n        if (pos+1 == s.length()) return {res, false};\n        if (s[pos+1] == '/') {\n            res.isStart = false;\n            pos++;\n        }\n        pos++;\n        int end = s.find(\">\", pos);\n        if (end == -1 || end-pos < 1 || end-pos > 9) return {res, false};\n        string name = s.substr(pos, end-pos);\n        for (char& c : name) {\n            if (c < 'A' || c > 'Z') return {res, false};\n        }\n        res.value = name;\n        pos = end+1;\n        return {res, true};\n    }\n    bool isValid(vector<Tag>& tags, int start, int end) {\n        //cout << start << \" \" << end << endl;\n        if (start > end) return true;\n        if (!tags[start].isStart) return false;\n        int k = start+1;\n        int c = 1;\n        while (k <= end && c > 0) {\n            if (tags[k].value == tags[start].value) {\n                c += (tags[k].isStart) ? 1 : -1;\n            }\n            k++;\n        }\n        if (c != 0) return false;\n        k--;\n        return isValid(tags, start+1, k-1) && isValid(tags, k+1, end);\n    }\npublic:\n    bool isValid(string code) {\n        vector<Tag> tags;\n        int n = code.length();\n        int i = 0;\n        while (i < n) {\n            int k = i;\n            while (k < n && code[k] != '<') {\n                k++;\n            }\n            if (k > i) {\n                if (i == 0) return false;\n                i = k;\n                if (i == n) return false;\n            } else {\n                if (code[k+1] == '!') {\n                    if (i == 0) return false;\n                    auto cdata = parseCData(code, k);\n                    if (!cdata.second) return false;\n                    i = cdata.first;\n                    if (i == n) return false;\n                } else {\n                    auto tag = parseTag(code, i);\n                    if (!tag.second) return false;\n                    if (i == n && tag.first.isStart) return false;\n                    tags.push_back(tag.first);\n                }\n            }\n        }\n        if (tags.size() < 2) return false;\n        int m = tags.size();\n        if (tags[0].value != tags[m-1].value || !tags[0].isStart || tags[m-1].isStart){\n            return false;\n        }\n        return isValid(tags, 1, m-2);\n    }\n};"457    },458    {459        "title": "Delete Operation for Two Strings",460        "algo_input": "Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.\n\nIn one step, you can delete exactly one character in either string.\n\n&nbsp;\nExample 1:\n\nInput: word1 = \"sea\", word2 = \"eat\"\nOutput: 2\nExplanation: You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".\n\n\nExample 2:\n\nInput: word1 = \"leetcode\", word2 = \"etco\"\nOutput: 4\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word1.length, word2.length &lt;= 500\n\tword1 and word2 consist of only lowercase English letters.\n\n",461        "solution_py": "class Solution:\n    def minDistance(self, word1: str, word2: str) -> int:\n        m = len(word1)\n        n = len(word2)\n        a = []\n        for i in range(m+1):\n            a.append([])\n            for j in range(n+1):\n                a[-1].append(0)\n        \n        for i in range(m):\n            for j in range(n):\n                if word1[i]==word2[j]:\n                    a[i+1][j+1] = 1 + a[i][j]\n                else:\n                    a[i+1][j+1] = max( a[i][j+1], a[i+1][j])\n\t\t\t\t\t\n        return m + n - ( 2 * a [-1][-1] )",462        "solution_js": "var minDistance = function(word1, word2) {\n\tconst WORD1_LEN = word1.length;\n\tconst WORD2_LEN = word2.length;\n\tconst dp = Array(WORD1_LEN + 1).fill('').map(() => Array(WORD2_LEN + 1).fill(0));\n\n\tfor (let index = 1; index <= WORD1_LEN; index++) {\n\t\tfor (let j = 1; j <= WORD2_LEN; j++) {\n\t\t\tdp[index][j] = word1[index - 1] === word2[j - 1]\n\t\t\t\t? dp[index - 1][j - 1] + 1\n\t\t\t\t: Math.max(dp[index - 1][j], dp[index][j - 1]);\n\t\t}\n\t}\n\n\treturn WORD1_LEN + WORD2_LEN - 2 * dp[WORD1_LEN][WORD2_LEN];\n};",463        "solution_java": "class Solution {\n    public int minDistance(String word1, String word2) {\n        int n = word1.length();\n        int m = word2.length();\n\n        int[][]dp = new int[n+1][m+1];\n\n        for(int i = 0; i<n; i++){\n            dp[i][0] = 0;\n        }\n\n        for(int i = 0; i<m; i++){\n            dp[0][i] = 0;\n        }\n\n        for(int i = 1; i<=n; i++){\n            for(int j = 1; j<=m; j++){\n                if(word1.charAt(i-1) == word2.charAt(j-1)){\n                    dp[i][j] = 1+dp[i-1][j-1];\n                }else{\n                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n                }\n            }\n        }\n\n        int common = dp[n][m];\n        return (n+m)-(2*common);\n\n    }\n}",464        "solution_c": "class Solution {\npublic:\n    int tabulation(string s1, string s2){\n        vector<vector<int>> table(s1.length() + 1, vector<int>(s2.length() + 1));\n        for(int i=1; i<s1.length()+1; i++){\n            for(int j=1; j<s2.length()+1; j++){\n                if(s1[i-1] == s2[j-1]){\n                    table[i][j] = 1 + table[i-1][j-1];\n                }\n                else{\n                    table[i][j] = max(table[i-1][j], table[i][j-1]);\n                }\n            }\n        }\n        return table[s1.length()][s2.length()];\n    }\n    \n    int minDistance(string word1, string word2) {\n        int lcs = tabulation(word1, word2);\n        return (word1.length() - lcs) + (word2.length() - lcs);\n    }\n};"465    },466    {467        "title": "Word Break",468        "algo_input": "Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.\n\nNote that the same word in the dictionary may be reused multiple times in the segmentation.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leetcode\", wordDict = [\"leet\",\"code\"]\nOutput: true\nExplanation: Return true because \"leetcode\" can be segmented as \"leet code\".\n\n\nExample 2:\n\nInput: s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]\nOutput: true\nExplanation: Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.\n\n\nExample 3:\n\nInput: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 300\n\t1 &lt;= wordDict.length &lt;= 1000\n\t1 &lt;= wordDict[i].length &lt;= 20\n\ts and wordDict[i] consist of only lowercase English letters.\n\tAll the strings of wordDict are unique.\n\n",469        "solution_py": "class Solution:\n    def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n        memo = {}\n\n\n        def can_construct(target, strings_bank, memo):    \n            if target in memo:\n                return memo[target]\n            if target == \"\":\n                return True\n            for element in strings_bank: # for every element in our dict we check if we can start constructing the string \"s\"\n                if element == target[0:len(element)]: # the remaining of the string \"s\" (which is the suffix) is the new target \n                    suffix = target[len(element):]\n                    if can_construct(suffix, strings_bank, memo):\n                        memo[target] = True\n                        return True\n            memo[target] = False\n            return False\n\n\n        return can_construct(s, wordDict, memo)",470        "solution_js": "/**\n * @param {string} s\n * @param {string[]} wordDict\n * @return {boolean}\n */\nvar wordBreak = function(s, wordDict) {\n    var dp = new Array(s.length + 1).fill(false);\n    dp[s.length] = true;\n\n    for (var i = s.length - 1; i >= 0; i--) {\n        for (const word of wordDict) {\n            if ((i + word.length) <= s.length\n                && s.substring(i, i + word.length) === word) {\n                dp[i] = dp[i + word.length];\n            }\n\n            if(dp[i]) break;\n        }\n    }\n\n    return dp[0];\n};\n\n// naive approach, take each word from the set and check if they match\n/// O(n ^ 2 * m)\n// considering m as the dictionary size\n/*\nvar dict = new Set();\nfor (const word of wordDict) {\n    dict.add(word);\n}\n\nreturn canSegment(s, dict, 0);\n\nfunction canSegment (str, dict, index) {\n    if (index >= str.length) return true;\n\n    var success = false;\n    for (const word of dict.values()) {\n\n        if ((index + word.length) <= str.length) {\n            var substring = str.substring(index, index + word.length);\n\n            if (dict.has(substring)) {\n                success = success | canSegment(str, dict, index + word.length);\n            }\n        }\n    }\n\n    return success;\n}\n*/",471        "solution_java": "class Solution {\n     Map<String,Boolean>map= new HashMap<>();\n    public boolean wordBreak(String s, List<String> wordDict) {\n\n       if(wordDict.contains(s)){\n           return true;\n       }\n        if(map.containsKey(s)){\n           return map.get(s);\n        }\n        for(int i=0;i<s.length();++i){\n            String left=s.substring(0,i);\n            if(wordDict.contains(left) && wordBreak(s.substring(i),wordDict)){\n                map.put(s,true);\n                return true;\n            }\n        }\n        map.put(s,false);\n        return false;\n    }\n}",472        "solution_c": "class Solution {\npublic:\n    bool wordBreak(string s, vector<string>& wordDict) {\n        int m = wordDict.size();\n        int n = s.size();\n        vector<int> dp(n+1,0);\n        dp[0] = 1;\n        for(int i = 1; i <= n; i++)\n        {\n            for(int j = 0; j < m; j++)\n            {\n                if(i >= wordDict[j].size())\n                {\n                    for(int k = 0; k < wordDict[j].size(); k++)\n                    {\n                        if(s[i-wordDict[j].size()+k] != wordDict[j][k])\n                            goto cnt;\n                    }\n                    if(dp[i-wordDict[j].size()] == 1) \n                        dp[i] = 1;\n                    if(dp[n] == 1) \n                        return true;\n                    cnt:;\n                }\n            }\n        }\n        return dp[n];\n    }\n};"473    },474    {475        "title": "Minimum Garden Perimeter to Collect Enough Apples",476        "algo_input": "In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.\n\nYou will buy an axis-aligned square plot of land that is centered at (0, 0).\n\nGiven an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.\n\nThe value of |x| is defined as:\n\n\n\tx if x &gt;= 0\n\t-x if x &lt; 0\n\n\n&nbsp;\nExample 1:\n\nInput: neededApples = 1\nOutput: 8\nExplanation: A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.\n\n\nExample 2:\n\nInput: neededApples = 13\nOutput: 16\n\n\nExample 3:\n\nInput: neededApples = 1000000000\nOutput: 5040\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= neededApples &lt;= 1015\n\n",477        "solution_py": "class Solution:\n    def minimumPerimeter(self, nap: int) -> int:\n        \n        \n#         here for n = 2 , there are two series :  \n#         (1) Diagnal points for n=3 , diagnal apples = 2*n = 6\n#         (2) there is series =   2,3,3 =  2+ (sigma(3)-sigma(2))*2\n        \n#         how to solve:\n            \n#             here 3  =  sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) =  0.5*2n*(2n-1)-0.5*n*n-1\n#         (3) so our final 2,3,3 =   3*2+2 =   (0.5*2n*(2n-1)-0.5*n*n-1)*2+n\n#         (4) so final 2,3,3 =  3*n*n - 2*n\n#         (5) we have 4 times repitation of (2,3,3)  = 4*(2,3,3)  =   4*(3*n*n - 2*n)   =  12*n*n - 8*n\n#         (6) we have 4 diagnal points so their sum(4 diagnal)  = 4*(2*n)\n#         (7)  so final sum(total) = 4 diagnal sum + 4(2,3,3)    =   4(2*n)   + 12*n*n - 8*n    =  12*n*n\n        \n#         so at nth distance we have total  12*n*n  apples at the circumfrance\n        \n#         so net sum =  sigma(12*n*n)  = 2*n*(n+1)*(2*n+1)\n        \n        \n        n=1\n        val=2*n*(n+1)*(2*n+1)\n        while(val<nap):\n            n+=1\n            val=val=2*n*(n+1)*(2*n+1)\n        return n*8",478        "solution_js": "/**\n * @param {number} neededApples\n * @return {number}\n */\nvar minimumPerimeter = function(neededApples) {\n    \n    \n    let start = 2, n = 1, dp = [0];\n    \n    while(true){\n        let cur = start, res = dp[n-1];\n\t\t\n\t\t//Add the X and Y axis apples multiplied with 4 \n        res += (cur + cur - n)*4;\n        \n\t\t// Add the interior apples using and AP formula of  ( n - 1 ) / 2 * (2a + ( n-1 ) * d ) & multiplying it by 8 as count is 8  \n        res += ( ((n-1)/2) *  ( ( 2 * (cur - 1) ) + ( (n-2) * -1 ) )  ) * 8\n        \n\t\t//Setting the result to DP\n        dp[n] = res;\n\t\t\n\t\t//If current state is greater than or equal to needed then return the perimeter\n        if(neededApples <= res) return 8*n;\n        n++;\n        start +=2;\n        \n    }\n};",479        "solution_java": "class Solution {\n    public long minimumPerimeter(long neededApples) {\n        long n = 0;\n        long count = 0;\n        while(count < neededApples) {\n            n++;\n            count += (12 * n * n);\n        }\n        return n * 8;\n    }\n}",480        "solution_c": "class Solution {\npublic:\n    long long minimumPerimeter(long long neededApples) {\n        long long i = 0;\n        long long x = 0;\n \n        while(x < neededApples){   \n            x += (long long) 12*pow(i,2); \n            ++i;\n        }\n        return (long long) (i-1)*8;\n    }\n};"481    },482    {483        "title": "Number of Valid Words for Each Puzzle",484        "algo_input": "With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:\n\n\tword contains the first letter of puzzle.\n\tFor each letter in word, that letter is in puzzle.\n\t\n\t\tFor example, if the puzzle is \"abcdefg\", then valid words are \"faced\", \"cabbage\", and \"baggage\", while\n\t\tinvalid words are \"beefed\" (does not include 'a') and \"based\" (includes 's' which is not in the puzzle).\n\t\n\t\n\nReturn an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].\n&nbsp;\nExample 1:\n\nInput: words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\nOutput: [1,1,3,2,4,0]\nExplanation: \n1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\n\n\nExample 2:\n\nInput: words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\nOutput: [0,1,3,2,0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 105\n\t4 &lt;= words[i].length &lt;= 50\n\t1 &lt;= puzzles.length &lt;= 104\n\tpuzzles[i].length == 7\n\twords[i] and puzzles[i] consist of lowercase English letters.\n\tEach puzzles[i] does not contain repeated characters.\n\n",485        "solution_py": "class Solution:\n    def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n        look_up=collections.defaultdict(int)\n        def get_mask(word):\n            mask=0\n            for c in word:\n                mask |= 1<<(ord(c)-ord('a'))\n            return mask\n        for word in words:\n            mask=get_mask(word)\n            look_up[mask]+=1\n        ans=[]\n        def solve(puzzle_idx,mask,c_idx):\n            if c_idx==len(puzzles[puzzle_idx]):\n                ans[-1]+=look_up[mask]\n                return\n            #take this c_idx\n            solve(puzzle_idx,mask | 1<<(ord(puzzles[puzzle_idx][c_idx])-ord('a')),c_idx+1)\n            #dont take this c_idx\n            solve(puzzle_idx,mask,c_idx+1)\n        for i,puzzle in enumerate(puzzles):\n            ans.append(0)\n            solve(i,1<<(ord(puzzle[0])-ord('a')),1)\n        return ans",486        "solution_js": "var findNumOfValidWords = function(words, puzzles) {\n\t// Form map of word's bitmasks\n    const wordsMaskMap = words.reduce((map, word) => addToMap(map, getMask(word)), new Map())\n\n    return puzzles.map(puzzle => {\n        const pMask = getMask(puzzle)\n        const pFirstMask = getFirstMask(puzzle)\n        let count = 0\n        \n\t\t// Verify each bitmask against a given puzzle\n        for (let wMask of wordsMaskMap.keys()) {\n            if((wMask & pFirstMask) && (!((wMask | pMask) ^ pMask))) {\n                count += wordsMaskMap.get(wMask)\n            }\n        }\n        return count\n    })\n}\n\n// Transform a char into a bit index\nvar getBit = (char) => 1 << char.charCodeAt(0) - 'a'.charCodeAt(0)\n\n// Transform a word into a bitmask\nvar getMask = (word) => word.split('').reduce((acc, c) => acc | getBit(c), 0)\n\n// Get a bitmask for the first letter of a word\nvar getFirstMask = (word) => getBit(word[0])\n\n// Helper function to count hashes in a Map object \nvar addToMap = (map, val) => map.has(val) ? map.set(val, map.get(val) + 1) : map.set(val, 1)",487        "solution_java": "class Solution {\n\npublic List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {\n    \n    Map<Integer, Integer> map = new HashMap<>();\n    \n    for(String w : words){\n        int mask = 0;\n        for(int i = 0; i < w.length(); i++){\n            mask |= 1 << (w.charAt(i) - 'a');\n        }\n        map.put(mask, map.getOrDefault(mask, 0) + 1);\n    }\n    \n    List<Integer> res = new ArrayList<>();\n    \n    for(String p : puzzles){\n        int mask = 0;\n        for(int i = 0; i < p.length(); i++){\n            mask |= 1 << (p.charAt(i) - 'a');\n        }\n        int c = 0;\n        int sub = mask;\n        int first = 1 << (p.charAt(0) - 'a');\n        while(true){\n            if((sub & first) == first && map.containsKey(sub)){\n                c += map.get(sub);\n            }\n            \n            if(sub == 0) break;\n            \n            sub = (sub - 1) & mask; // get the next substring\n        }\n        \n        res.add(c);\n    }\n    \n    return res;\n}\n}",488        "solution_c": "class Solution {\npublic:\n    vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) {\n        unordered_map<int, int> maskCnt;\n        for(const auto& w: words) ++maskCnt[bitmask(w)];\n        vector<int> ans(puzzles.size(), 0);\n        for(int i = 0; i < puzzles.size(); i++){\n            int mask, subMask = mask = bitmask(puzzles[i]), first = bitmask(puzzles[i].substr(0,1));\n            do{\n                if( (first & subMask) == first && maskCnt.count(subMask)) ans[i] += maskCnt[subMask]; //ok\n            }while(subMask = (subMask - 1) & mask);\n        }\n        return ans;\n    }\n\nprivate:\n    int bitmask(const string& word, int mask = 0){\n        for(auto c: word) mask |= (1 << (c - 'a'));\n        return mask;\n    }\n};"489    },490    {491        "title": "Capitalize the Title",492        "algo_input": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:\n\n\n\tIf the length of the word is 1 or 2 letters, change all letters to lowercase.\n\tOtherwise, change the first letter to uppercase and the remaining letters to lowercase.\n\n\nReturn the capitalized title.\n\n&nbsp;\nExample 1:\n\nInput: title = \"capiTalIze tHe titLe\"\nOutput: \"Capitalize The Title\"\nExplanation:\nSince all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.\n\n\nExample 2:\n\nInput: title = \"First leTTeR of EACH Word\"\nOutput: \"First Letter of Each Word\"\nExplanation:\nThe word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\n\n\nExample 3:\n\nInput: title = \"i lOve leetcode\"\nOutput: \"i Love Leetcode\"\nExplanation:\nThe word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= title.length &lt;= 100\n\ttitle consists of words separated by a single space without any leading or trailing spaces.\n\tEach word consists of uppercase and lowercase English letters and is non-empty.\n\n",493        "solution_py": "class Solution:\n    def capitalizeTitle(self, title: str) -> str:\n        li = title.split()\n        for i,l in enumerate(li):\n            if len(l) <= 2:\n                li[i] = l.lower()\n            else:\n                li[i] = l[0].upper() + l[1:].lower()\n        return ' '.join(li)",494        "solution_js": "var capitalizeTitle = function(title) {\n    const words = title.toLowerCase().split(' ');\n    \n    for (let i = 0; i < words.length; i++) {\n        if (words[i].length > 2) {\n            words[i] = words[i][0].toUpperCase() + words[i].slice(1);\n        }\n    }\n    \n    return words.join(' ');\n};",495        "solution_java": "class Solution {\n\tpublic String capitalizeTitle(String title) {\n\n\t\tchar[] ch = title.toCharArray();\n\t\tint len = ch.length;\n\n\t\tfor(int i = 0; i < len; ++i) {\n\n\t\t\tint firstIndex = i; // store the first index of the word\n\n\t\t\twhile(i < len && ch[i] != ' ') {\n\t\t\t\tch[i] = Character.toLowerCase(ch[i]); // converting the character at ith index to lower case ony by one\n\t\t\t\t++i;\n\t\t\t}\n\t\t\t\n\t\t\t// if word is of length greater than 2, then turn the first character of the word to upper case\n\t\t\tif(i - firstIndex > 2) {\n\t\t\t\tch[firstIndex] =  Character.toUpperCase(ch[firstIndex]); // converting the first character of the word to upper case\n\t\t\t}\n\t\t}\n\n\t\treturn String.valueOf(ch); // return the final result by converting the char array into string\n\t}\n}",496        "solution_c": "class Solution {\npublic:\n    string capitalize(string s){\n        transform(s.begin(), s.end(), s.begin(), ::tolower);\n        if(s.length() <= 2){\n            return s;\n        }\n        s[0] = s[0] - 'a' + 'A';\n        return s;\n    }\n    string capitalizeTitle(string title) {\n        string str = \"\";\n        string ans = \"\";\n        for(int i = 0; i < title.length(); i++){\n            if(title[i] != ' '){\n                str.push_back(title[i]);\n            }\n            else{\n                str = capitalize(str);\n                ans += str + \" \";\n                str = \"\";\n            }\n        }\n        str = capitalize(str);\n        ans += str;\n        return ans;\n    }\n};"497    },498    {499        "title": "Reorder List",500        "algo_input": "You are given the head of a singly linked-list. The list can be represented as:\n\nL0 → L1 → … → Ln - 1 → Ln\n\n\nReorder the list to be on the following form:\n\nL0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …\n\n\nYou may not modify the values in the list's nodes. Only nodes themselves may be changed.\n\n&nbsp;\nExample 1:\n\nInput: head = [1,2,3,4]\nOutput: [1,4,2,3]\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5]\nOutput: [1,5,2,4,3]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 5 * 104].\n\t1 &lt;= Node.val &lt;= 1000\n\n",501        "solution_py": "class Solution:\n    def reverse(self , head):\n        prev = None\n        after = None\n        curr = head\n        while(curr):\n            after = curr.next\n            curr.next = prev\n            prev = curr\n            curr = after\n        return prev\n            \n    def find_middle(self , head):\n        slow = head\n        fast = head\n        while(fast and fast.next):\n            fast = fast.next.next\n            slow = slow.next\n        return slow\n        \n    def reorderList(self, head: Optional[ListNode]) -> None:\n        mid = self.find_middle(head)\n        rev = self.reverse(mid)\n        first = head\n        second = rev\n        \n        while(second.next):\n            temp = first.next\n            first.next = second\n            first = temp\n            \n            temp = second.next\n            second.next = first\n            second = temp\n            ",502        "solution_js": "var reorderList = function(head) {\n    const dummyL = new ListNode(-1);\n    const dummyR = new ListNode(-1);\n\n    let currL = dummyL;\n    let currR = dummyR;\n    let past = false;\n\n    let fast = head;\n    let slow = head;\n    while (slow) {\n        if (!fast?.next) {\n            past = true\n        }\n\n        if (past) {\n            currR.next = slow;\n            currR = slow;\n        } else {\n            currL.next = slow\n            currL = slow;\n        }\n\n        if (fast) {\n            fast = fast.next?.next || null;\n        }\n        slow = slow.next\n    }\n    currL.next = null;\n    currR.next = null;\n\n    dummyR.next = reverse(dummyR.next);\n    return merge(dummyL.next, dummyR.next);\n};\n\nconst merge = (l, r) => {\n    const dummy = new ListNode(-1);\n\n    let currL = l;\n    let currR = r;\n    let last = dummy;\n\n    let count = 0;\n    while (currL && currR) {\n        if (count % 2 === 0) {\n            last.next = currL;\n            last = currL;\n            currL = currL.next\n        } else {\n            last.next = currR;\n            last = currR;\n            currR = currR.next\n        }\n\n        count++\n    }\n\n    last.next = (currL || currR);\n    return dummy.next;\n}\n\nconst reverse = (head) => {\n    let prev = null;\n    let curr = head;\n    while (curr) {\n        const tempPrev = curr.next;\n        curr.next = prev;\n        prev = curr;\n        curr = tempPrev;\n    }\n\n    return prev;\n}",503        "solution_java": "class Solution {\n    public void reorderList(ListNode head) {\n        if (head == null) return;\n\t\t\n\t\t// Find start of second list\n        ListNode slow = head, fast = head;\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n\t\t\n        ListNode list1 = head;\n        ListNode list2 = reverseList(slow.next); // slow.next is start of list2\n        \n        // Break first list from second list!\n        slow.next = null; \n        \n\t\t// Merge list1 and list2\n        while (list2 != null) {\n            ListNode l1Next = list1.next;\n            ListNode l2Next = list2.next;\n            list2.next = list1.next;\n            list1.next = list2;\n            list1 = l1Next;\n            list2 = l2Next;\n        }\n    }\n    \n    private ListNode reverseList(ListNode node) {\n        if (node == null) return node;\n        ListNode newHead = null, currNode = node;\n        while (currNode != null) {\n            ListNode backup = currNode.next;\n            currNode.next = newHead;\n            newHead = currNode;\n            currNode = backup;\n        }\n        return newHead;\n    }\n}",504        "solution_c": "class Solution {\npublic:\n    ListNode* solve(ListNode* head,ListNode* temp){\n        if(temp==NULL)return head;\n        ListNode* curr=solve(head,temp->next);\n        if(!curr)return NULL;\n        if(curr==temp){\n            curr->next=NULL;\n            return nullptr;\n        }\n        if(curr->next==temp){\n            temp->next=nullptr;\n            return NULL;\n        }\n        temp->next=curr->next;\n        curr->next=temp;\n        curr=temp->next;\n        return curr;\n    }\n    void reorderList(ListNode* head) {\n        solve(head,head);\n    }\n};"505    },506    {507        "title": "Rotting Oranges",508        "algo_input": "You are given an m x n grid where each cell can have one of three values:\n\n\n\t0 representing an empty cell,\n\t1 representing a fresh orange, or\n\t2 representing a rotten orange.\n\n\nEvery minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.\n\nReturn the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput: 4\n\n\nExample 2:\n\nInput: grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput: -1\nExplanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.\n\n\nExample 3:\n\nInput: grid = [[0,2]]\nOutput: 0\nExplanation: Since there are already no fresh oranges at minute 0, the answer is just 0.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 10\n\tgrid[i][j] is 0, 1, or 2.\n\n",509        "solution_py": "class Solution:\n    def orangesRotting(self, grid: List[List[int]]) -> int:\n        visited = set()\n        res = 0\n        def bfs(grid):\n            que = collections.deque()\n            for i in range(len(grid)):\n                for j in range(len(grid[0])):\n                    if grid[i][j] == 2:\n                        que.append((i,j))\n            que.append(None)\n            count = 0    \n            while len(que)>0:\n                left , right = 0,0\n\t\t\t\t# This other while loop is to make sure that we traverse from all the rotten oranges in one turn.\n                while que[0] != None:\n                    r,c = que.popleft()\n                    for Cols in [-1,1]:\n                        if c+Cols>=0 and c+Cols<len(grid[0]) and grid[r][c+Cols]==1:\n                            grid[r][c+Cols] = 2\n                            left += 1\n                            que.append((r,c+Cols))\n                    \n                    for Rows in [-1,1]:\n                        if r+Rows>=0 and r+Rows<len(grid) and grid[r+Rows][c]==1:\n                            grid[r+Rows][c] = 2\n                            right += 1\n                            que.append((r+Rows,c))\n\t\t\t\t'''\n\t\t\t\tif either left or right or both is incremented it means that we have moved in either direction,\n\t\t\t\tand then this will be counted as a turn(or minute as per the problem description.).\n\t\t\t\t\n\t\t\t\t'''\n                if left is not 0 or right is not 0:\n                    count+=1\n                que.popleft()\n                if len(que)>0:\n\t\t\t\t    '''\n\t\t\t\t    This is required to terminate the loop and prevent infinite loop.\n\t\t\t\t    This only appends a None if there is still some values in the que, \n\t\t\t\t    else we have completed our traversal and we can stop going any futher.\n\t\t\t\t    '''\n                    que.append(None)\n            return count\n        res = bfs(grid)\n        for i in range(len(grid)):\n                for j in range(len(grid[0])):\n                    if grid[i][j] == 1:\n                        return -1\n        return res",510        "solution_js": "let convertAdjacentCellsToRotten = (grid, locations, rottenOranges) => {\n    let didConvertAny = false;\n    let newLocations = [];\n    for(let i=0;i<locations.length;i++){\n        let loci = locations[i][0]\n        let locj = locations[i][1]\n        \n        if(loci+1 < grid.length && grid[loci+1][locj] === 1) {\n            grid[loci+1][locj] = 2;\n            newLocations.push([loci+1,locj])\n            didConvertAny = true;\n            rottenOranges++\n        }\n        if(loci-1 >= 0 && grid[loci-1][locj] === 1) {\n            grid[loci-1][locj] = 2;\n            newLocations.push([loci-1,locj])\n\n            didConvertAny = true;\n            rottenOranges++\n        }\n        if(locj+1 < grid[0].length && grid[loci][locj+1] === 1) {\n            grid[loci][locj+1] = 2;\n            newLocations.push([loci,locj+1])\n            didConvertAny = true;\n            rottenOranges++\n        }\n        if(locj-1 >= 0 && grid[loci][locj-1] === 1) {\n            grid[loci][locj-1] = 2;\n            newLocations.push([loci,locj-1])\n            didConvertAny = true;\n            rottenOranges++\n        }\n    }\n    \n    return {didConvertAny:didConvertAny, rottenOranges,locations:[...newLocations]}\n}\nvar orangesRotting = function(grid) {\n    let rottenLocation = [];\n    let rottenOranges = 0;\n    let totalOranges = 0;\n    let minutes = 0;\n    for(let i=0;i<grid.length;i++) {\n        for(let j=0;j<grid[0].length;j++) {\n            if(grid[i][j]===2) {\n                rottenLocation.push([i,j])\n                rottenOranges++;\n            }\n            if(grid[i][j]!==0) totalOranges++;\n        }\n    }\n    \n    while (1) {\n        let gridConversionResult = convertAdjacentCellsToRotten(grid,rottenLocation,rottenOranges);\n        if (gridConversionResult.didConvertAny) {\n            rottenLocation = gridConversionResult.locations;\n            minutes++;\n            rottenOranges = gridConversionResult.rottenOranges;\n        }\n        else break\n    }\n    if(totalOranges===rottenOranges) return minutes;\n    else return -1\n    \n};",511        "solution_java": "class Solution {\n    class Pair{\n        int i;\n        int j;\n        int t;\n        \n        public Pair(int i,int j,int t){\n            this.i = i;\n            this.j = j;\n            this.t = t;\n        }\n    }\n    int ans = 0;\n    final int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};\n    public int orangesRotting(int[][] grid) {\n        int countFresh = 0;\n        Queue<Pair> q = new LinkedList<>();\n        for(int i=0;i<grid.length;i++){\n            for(int j = 0;j<grid[0].length;j++){\n                if(grid[i][j] == 2){\n                    q.offer(new Pair(i,j,0));\n                }else if(grid[i][j] == 1){\n                    countFresh++;\n                }\n            }\n        }\n        int count = 0;\n        while(q.size() != 0){\n            Pair temp = q.poll();\n            ans = Math.max(ans,temp.t);\n            for(int[] d : dir){\n                int r = temp.i + d[0];\n                int c = temp.j + d[1];\n                int t = temp.t +1;\n                if(r >= 0 && c >= 0 && r <grid.length && c < grid[0].length && grid[r][c] == 1){\n                    q.offer(new Pair(r,c,t));\n                    grid[r][c] = 2;\n                    count++;\n                }\n            }\n        }\n        if(count != countFresh) return -1;\n        return ans;\n    }\n}",512        "solution_c": "class Solution {\npublic:\n    int orangesRotting(vector<vector<int>>& grid) {\n        int R = grid.size();\n        int C = grid[0].size();\n        queue<vector<int>> nextOrangesToRot;\n        for(int r = 0; r < R; ++r)\n            for(int c = 0; c < C; ++c)\n                if(grid[r][c] == 2)\n                    nextOrangesToRot.push({r, c});\n        \n        vector<int> xDir {-1, 0, 0, 1};\n        vector<int> yDir {0, 1, -1, 0};\n        int totalTime = 0;\n        while(!nextOrangesToRot.empty())\n        {\n            int size = nextOrangesToRot.size();\n            while(size--)\n            {\n                vector<int>& currOrangeCell =  nextOrangesToRot.front();\n                \n                for(int i = 0; i < 4; ++i)\n                {\n                    int nextR = currOrangeCell[0] + xDir[i];\n                    int nextC = currOrangeCell[1] + yDir[i];\n                    if(nextR >= 0 && nextR < R && \n                       nextC >= 0 && nextC < C && grid[nextR][nextC] == 1)\n                    {\n                        grid[nextR][nextC] = 2; //rotted\n                        nextOrangesToRot.push({nextR, nextC});\n                    }\n                }\n                nextOrangesToRot.pop();\n            }\n            if(nextOrangesToRot.size())\n                totalTime++;\n        }\n        for(int r = 0; r < R; ++r)\n            for(int c = 0; c < C; ++c)\n                if(grid[r][c] == 1)\n                   return -1;\n        return totalTime;\n    }\n};"513    },514    {515        "title": "Maximum Number of Words Found in Sentences",516        "algo_input": "A sentence is a list of words that are separated by a single space&nbsp;with no leading or trailing spaces.\n\nYou are given an array of strings sentences, where each sentences[i] represents a single sentence.\n\nReturn the maximum number of words that appear in a single sentence.\n\n&nbsp;\nExample 1:\n\nInput: sentences = [\"alice and bob love leetcode\", \"i think so too\", \"this is great thanks very much\"]\nOutput: 6\nExplanation: \n- The first sentence, \"alice and bob love leetcode\", has 5 words in total.\n- The second sentence, \"i think so too\", has 4 words in total.\n- The third sentence, \"this is great thanks very much\", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.\n\n\nExample 2:\n\nInput: sentences = [\"please wait\", \"continue to fight\", \"continue to win\"]\nOutput: 3\nExplanation: It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentences.length &lt;= 100\n\t1 &lt;= sentences[i].length &lt;= 100\n\tsentences[i] consists only of lowercase English letters and ' ' only.\n\tsentences[i] does not have leading or trailing spaces.\n\tAll the words in sentences[i] are separated by a single space.\n\n",517        "solution_py": "class Solution:\n    def mostWordsFound(self, ss: List[str]) -> int:\n        return max(s.count(\" \") for s in ss) + 1",518        "solution_js": "/**\n * @param {string[]} sentences\n * @return {number}\n */\nvar mostWordsFound = function(sentences) {\n    let max = 0;\n    let temp = 0;\n    for (let i = 0; i < sentences.length; i++) {\n        temp = sentences[i].split(\" \").length;\n        if (temp > max) {\n            max = temp;\n        }\n    }\n\n    return max;\n};",519        "solution_java": "class Solution {\n    public int mostWordsFound(String[] sentences) {\n        int max=0;\n        for(int i=0; i<sentences.length; i++) {\n            max = Math.max(max,(sentences[i].split(\" \")).length);\n        }\n        return max;\n    }\n}",520        "solution_c": "class Solution {\npublic:\n    int mostWordsFound(vector<string>& sentences) {\n        int res = 0;\n        for (auto const &s: sentences) {\n            int n = count(s.begin(), s.end(), ' ');\n            res = max(res, n + 1);\n        }\n        return res;\n    }\n};"521    },522    {523        "title": "Sort Even and Odd Indices Independently",524        "algo_input": "You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:\n\n\n\tSort the values at odd indices of nums in non-increasing order.\n\n\t\n\t\tFor example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order.\n\t\n\t\n\tSort the values at even indices of nums in non-decreasing order.\n\t\n\t\tFor example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.\n\t\n\t\n\n\nReturn the array formed after rearranging the values of nums.\n\n&nbsp;\nExample 1:\n\nInput: nums = [4,1,2,3]\nOutput: [2,3,4,1]\nExplanation: \nFirst, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].\n\n\nExample 2:\n\nInput: nums = [2,1]\nOutput: [2,1]\nExplanation: \nSince there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",525        "solution_py": "class Solution(object):\n    def sortEvenOdd(self, nums):\n        \"\"\"\n        :type nums: List[int]\n        :rtype: List[int]\n        \"\"\"\n        nums[::2], nums[1::2] = sorted(nums[::2]), sorted(nums[1::2], reverse=True)\n        return nums",526        "solution_js": "var sortEvenOdd = function(nums) {\n\nlet odd= nums.filter((num,i,arr)=> i%2!=0).sort((a,b)=> b-a);  //decreasing order\nlet even= nums.filter((num,i,arr)=> i%2==0).sort((a,b)=> a-b); //increasing order\nlet x=0,y=0;\n    \n   nums.forEach((num,i,nums)=> {\n        nums[i]= i%2==0 ? even[x++] : odd[y++];       //refilling the array \n    });\n    return nums;\n};",527        "solution_java": "class Solution {\n    public int[] sortEvenOdd(int[] nums) {\n        int[] even = new int[101];\n        int[] odd = new int[101];\n        int length = nums.length;\n        for (int i = 0; i < length; ++i) {\n            if (i % 2 == 0) {\n                even[nums[i]]++;\n            } else {\n                odd[nums[i]]++;\n            }\n        }\n        int e = 0;\n        int o = 100;\n        for (int i = 0; i < length; ++i) {\n            if (i % 2 == 0) {\n                // check even\n                while (even[e] == 0) {\n                    ++e;\n                }\n                nums[i] = e;\n                even[e]--;\n            } else {\n                while(odd[o] == 0) {\n                    --o;\n                }\n                nums[i] = o;\n                odd[o]--;\n            }\n        }\n        return nums;\n    }\n}",528        "solution_c": "class Solution {\npublic:\n    vector<int> sortEvenOdd(vector<int>& nums) {\n        vector<int> odd, even;\n        for(int i = 0; i < nums.size(); i++) {\n            if(i & 1) {\n                odd.push_back(nums[i]);\n            } else {\n                even.push_back(nums[i]);\n            }\n        }\n        sort(odd.begin(), odd.end(), greater<int>());\n        sort(even.begin(), even.end());\n        for(int i = 0; i < nums.size(); i++) {\n            if(i & 1) {\n                nums[i] = odd[0];\n                odd.erase(odd.begin());\n            } else {\n                nums[i] = even[0];\n                even.erase(even.begin());\n            }\n        }\n        return nums;\n    }\n};"529    },530    {531        "title": "Happy Number",532        "algo_input": "Write an algorithm to determine if a number n is happy.\n\nA happy number is a number defined by the following process:\n\n\n\tStarting with any positive integer, replace the number by the sum of the squares of its digits.\n\tRepeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.\n\tThose numbers for which this process ends in 1 are happy.\n\n\nReturn true if n is a happy number, and false if not.\n\n&nbsp;\nExample 1:\n\nInput: n = 19\nOutput: true\nExplanation:\n12 + 92 = 82\n82 + 22 = 68\n62 + 82 = 100\n12 + 02 + 02 = 1\n\n\nExample 2:\n\nInput: n = 2\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",533        "solution_py": "class Solution(object):\n    def isHappy(self, n):\n        hset = set()\n        while n != 1:\n            if n in hset: return False\n            hset.add(n)\n            n = sum([int(i) ** 2 for i in str(n)])\n        else:\n            return True",534        "solution_js": "var isHappy = function(n) {\n    if(n<10){\n        if(n === 1 || n === 7){\n            return true\n        }\n        return false\n    }\n    let total = 0\n    while(n>0){\n        let sq = n % 10\n        total += sq**2\n        n -= sq\n        n /= 10\n    }\n    if(total === 1){\n        return true\n    }\n    return isHappy(total)\n};",535        "solution_java": "class Solution {\n    public boolean isHappy(int n) {\n        // Create a hash set...\n        Set<Integer> hset = new HashSet<Integer>();\n        // If the number is not in the HashSet, we should add it...\n        while (hset.add(n)) {\n            // Initialize the total...\n            int total = 0;\n            // Create a while loop...\n            while (n > 0) {\n                // Process to get happy number...\n                // We use division and modulus operators to repeatedly take digits off the number until none remain...\n                // Then squaring each removed digit and adding them together...\n                total += (n % 10) * (n % 10);\n                n /= 10;\n                // Each new converted number must not had occurred before...\n            }\n            // If total is equal to 1 return true.\n            if (total == 1)\n                return true;\n            // Insert the current number into the set s...\n            // Replace the current number with total of the square of its digits.\n            else\n                n = total;\n        }\n        // If current number is already in the HashSet, that means we're in a cycle and we should return false..\n        return false;\n    }\n}",536        "solution_c": "class Solution {\npublic:\n    bool isHappy(int n) {\n        // Create a set...\n        set<int> hset;\n        while(hset.count(n) == 0) {\n            // If total is equal to 1 return true.\n            if(n == 1)\n                return true;\n            // Insert the current number in hset...\n            hset.insert(n);\n            // Initialize the total...\n            int total=0;\n            // Create a while loop...\n            while(n) {\n                // Process to get happy number...\n                // We use division and modulus operators to repeatedly take digits off the number until none remain...\n                // Then squaring each removed digit and adding them together.\n                total += (n % 10) * (n % 10);\n                n /= 10;\n                // Each new converted number must not had occurred before...\n            }\n            // Insert the current number into the set s...\n            // Replace the current number with total of the square of its digits.\n            n = total;\n        }\n        // If current number is already in the HashSet, that means we're in a cycle and we should return false..\n        return false;\n    }\n};"537    },538    {539        "title": "Similar String Groups",540        "algo_input": "Two strings X&nbsp;and Y&nbsp;are similar if we can swap two letters (in different positions) of X, so that&nbsp;it equals Y. Also two strings X and Y are similar if they are equal.\n\nFor example, \"tars\"&nbsp;and \"rats\"&nbsp;are similar (swapping at positions 0 and 2), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\", \"rats\", or \"arts\".\n\nTogether, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"}.&nbsp; Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.&nbsp; Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\n\nWe are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?\n\n&nbsp;\nExample 1:\n\nInput: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\nOutput: 2\n\n\nExample 2:\n\nInput: strs = [\"omv\",\"ovm\"]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= strs.length &lt;= 300\n\t1 &lt;= strs[i].length &lt;= 300\n\tstrs[i] consists of lowercase letters only.\n\tAll words in strs have the same length and are anagrams of each other.\n\n",541        "solution_py": "class Solution: #839. Similar String Groups\n    def numSimilarGroups(self, strs: List[str]) -> int:\n        #memo\n        visited = set()\n        count = 0\n        for i in range(len(strs)):\n            if i not in visited:\n                #dfs\n                self.dfs(strs, i, visited)\n                #add a new connected area\n                count += 1\n        return count\n\n    #dfs to search the similar string from 0 to n-1\n    def dfs(self, strs, i, visited):\n        #add current string to memo\n        visited.add(i)\n        for j in range(len(strs)):\n            if self.isSimilar(strs[i], strs[j]) and j not in visited:\n                self.dfs(strs, j , visited)\n\n    # calculate the similarity of two strings\n    def isSimilar(self, str1, str2):\n        diff_count = 0\n        for i in range(len(str1)):\n            if str1[i] != str2[i]:\n                diff_count += 1\n        return diff_count <= 2",542        "solution_js": "var numSimilarGroups = function(strs) {\n    const len = strs.length;\n    \n    // dsu logic\n    const dsu = new Array(len).fill(0).map((_, idx) => idx);\n    const find = (x) => {\n        if(x == dsu[x]) return x;\n        return dsu[x] = find(dsu[x]);\n    }\n    const union = (i, j) => {\n        const pi = find(i);\n        const pj = find(j);\n        if(pi != pj) {\n            dsu[pi] = pj;\n        }\n    }\n    \n    \n    const similar = (a, b) => {\n        let c = 0, i = 0, len = a.length;\n        while(i < len) {\n            if(a[i] != b[i]) c++;\n            i++;\n            if(c > 2) return false;\n        }\n        return true;\n    }\n    \n    for(let i = 0; i < len; i++) {\n        for(let j = i + 1; j < len; j++) {\n            if(similar(strs[i], strs[j])) {\n                union(i, j);\n            }\n        }\n    }\n    for(let i = 0; i < len; i++) find(i);\n    const s = new Set();\n    for(let i = 0; i < len; i++) s.add(dsu[i]);\n    return s.size;\n};",543        "solution_java": "class Solution {\n    public int numSimilarGroups(String[] strs) {\n        boolean[] visited = new boolean[strs.length]; // record the word that we checked\n        int res = 0;\n        for (int i = 0; i < strs.length; i++) {\n            if (!visited[i]) {\n                res++;\n                dfs(strs, visited, i);\n            }\n        }\n        return res;\n    }\n    \n    void dfs(String[] strs, boolean[] visited, int index) { // explore all similar words we can explore\n        visited[index] = true;\n        String curr = strs[index];\n        for (int i = 0; i < strs.length; i++) {\n            if (!visited[i] && isSimilar(curr, strs[i])) {\n                dfs(strs, visited, i);\n            } \n        }\n    }\n    \n    boolean isSimilar(String a, String b) {\n        int diff = 0;\n        for (int i = 0; i < a.length(); i++) {\n            if (a.charAt(i) != b.charAt(i)) {\n                diff++;\n                if (diff > 2) return false;\n            }\n        }\n        return true;\n    }\n}",544        "solution_c": "class Solution {\npublic:\n\n    bool similar(string s1,string s2)\n    {\n        int n=s1.size();\n        int i=0,j=n-1;\n       int missMatch=0;\n        for(i=0;i<n;i++)\n        {\n            if(s1[i]!=s2[i] and ++missMatch>2)return 0;\n        }\n        return 1;\n    }\n\n    void dfs(string x,unordered_map<string,vector<string>>&adj,unordered_set<string>&visited)\n    {\n        visited.insert(x);\n        for(auto nbr:adj[x])\n        {\n            if(visited.find(nbr)==visited.end())\n            {\n\n                dfs(nbr,adj,visited);\n            }\n        }\n    }\n\n    int numSimilarGroups(vector<string>& strs) {\n        int n = strs.size();\n        unordered_map<string,vector<string>>adj;\n        for(int i=0;i<n;i++)\n        {\n            string s1 = strs[i];\n            for(int j=i+1;j<n;j++)\n            {\n                string s2 = strs[j];\n                if(similar(s1,s2))\n                {\n                    adj[s1].push_back(s2);\n                    adj[s2].push_back(s1);\n\n                }\n            }\n\n        }\n\n        int count=0;\n        unordered_set<string>visited;\n        for(auto x:strs)\n        {\n            if(visited.find(x)==visited.end())\n            {\n                //cout<<x<<endl;\n                dfs(x,adj,visited);\n                count++;\n            }\n        }\n        return count;//(strs[0],strs[2]);\n\n    }\n};"545    },546    {547        "title": "Check If Word Is Valid After Substitutions",548        "algo_input": "Given a string s, determine if it is valid.\n\nA string s is valid if, starting with an empty string t = \"\", you can transform t into s after performing the following operation any number of times:\n\n\n\tInsert string \"abc\" into any position in t. More formally, t becomes tleft + \"abc\" + tright, where t == tleft + tright. Note that tleft and tright may be empty.\n\n\nReturn true if s is a valid string, otherwise, return false.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aabcbc\"\nOutput: true\nExplanation:\n\"\" -&gt; \"abc\" -&gt; \"aabcbc\"\nThus, \"aabcbc\" is valid.\n\nExample 2:\n\nInput: s = \"abcabcababcc\"\nOutput: true\nExplanation:\n\"\" -&gt; \"abc\" -&gt; \"abcabc\" -&gt; \"abcabcabc\" -&gt; \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.\n\n\nExample 3:\n\nInput: s = \"abccba\"\nOutput: false\nExplanation: It is impossible to get \"abccba\" using the operation.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 2 * 104\n\ts consists of letters 'a', 'b', and 'c'\n\n",549        "solution_py": "class Solution:\n    def isValid(self, s: str) -> bool:\n        \n        \n        ans = ''\n        for i in s:\n            ans+=i\n            while len(ans)>=3:\n                if ans[-3:]==\"abc\":\n                    ans=ans[0:-3]\n                else:\n                    break\n            \n        if ans=='':\n            return True\n        else:\n            return False",550        "solution_js": "var isValid = function(s) {\n    const stack = [];\n    for(let c of s) {\n        if(c !== 'c') {\n            stack.push(c);\n        }else {\n            if(stack.pop() !== 'b') return false;\n            if(stack.pop() !== 'a') return false;\n        }\n    }\n\n    return stack.length === 0;\n};",551        "solution_java": "class Solution {\n    public boolean isValid(String s) {\n        \n        //Lets see how we can solve that as we know we have only abc in string.\n        //Like           aabcbc\n        // See as that   ((b)b) Think a is '(' and c is ')'.\n        // If a string is made by using abc only we can remove abc to make it empty also.\n        \n        //Think in Reverse Way.\n        \n        \n        \n        Stack<Character> stack = new Stack<>();\n        char[] arr = s.toCharArray();\n        for (int i = 0; i < arr.length; i++) {\n            \n            // We have to work only when we get ')' means c.\n            \n            if(arr[i] == 'c')\n            {\n                // If we at c means we have 2 elements before us a and b.\n                // When we first pop we get b at second pop we get a\n                \n            // If this all hold true we will delete a and b we are not adding c so c also\n                \n                if(stack.size()>=2 && stack.pop() == 'b' && stack.pop() == 'a')\n                {\n\n                }\n                else\n                {\n                    \n                    // If anywhere we get false in any condition that means this is not a                          valid set i.e. abc pattern is not present.\n                    \n                    return false;\n                }\n            }\n            else\n            {\n                // For a and b we simply add.\n                \n                stack.push(arr[i]);\n            }\n        }\n        \n        //If we have only abc pattern the stack will become empty.\n        \n        return stack.size()==0;\n    }\n}",552        "solution_c": "class Solution {\npublic:\n    bool isValid(string s) {\n        stack<char>st;\n        for(int i=0;i<s.length();i++){\n            if(s[i]=='a')\n                st.push(s[i]);\n            else if(s[i]=='b'){\n                if(st.empty() || st.top()!='a')\n                return false;\n                else\n                    st.push(s[i]);\n            }\n            else if(s[i]=='c'){\n                if(st.empty() ||  st.top()!='b')\n                    return false;\n                else{\n                    for(int i=0;i<2;i++)\n                        st.pop();\n                }\n            }\n        }\n        return st.size()==0;\n    }\n};"553    },554    {555        "title": "Accounts Merge",556        "algo_input": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.\n\nNow, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.\n\nAfter merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.\n\n&nbsp;\nExample 1:\n\nInput: accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput: [[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:\nThe first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\n\n\nExample 2:\n\nInput: accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput: [[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= accounts.length &lt;= 1000\n\t2 &lt;= accounts[i].length &lt;= 10\n\t1 &lt;= accounts[i][j].length &lt;= 30\n\taccounts[i][0] consists of English letters.\n\taccounts[i][j] (for j &gt; 0) is a valid email.\n\n",557        "solution_py": "class Solution:\n    def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n        def merge(accounts):\n            res = []\n            ls = []\n            for i in range(len(accounts)):\n                temp = list(set(accounts[i][1:]))\n                temp.sort()\n                temp = [accounts[i][0]] + temp\n                if i in ls:\n                    continue\n                for j in range(len(accounts[i:])):\n                    s = i+j\n                    if i == s:\n                        continue\n                    if accounts[i][0] != accounts[s][0]:\n                        continue\n                    temp3 = list(set(accounts[s][1:]))\n                    uni = list(set(temp[1:]) | set(temp3))\n                    if len(uni) < len(temp[1:]) + len(temp3):\n                        temp1 = list(set(temp[1:]) | set(temp3))\n                        temp = [temp[0]] + temp1 \n                        ls.append(s)\n                temp0 = temp[1:]\n                temp0.sort()\n                temp = [temp[0]]+temp0\n                res.append(temp)\n            return res\n        merged = merge(accounts)\n        while merge(merged) != merged:\n            merged = merge(merged)\n\n        return merged",558        "solution_js": "/**\n * @param {string[][]} accounts\n * @return {string[][]}\n */\n\nvar accountsMerge = function(accounts) {\n\n    let graph = {};\n    let nameDict = {};\n\n    for (let acc of accounts) {\n        let name = acc[0];\n        nameDict[acc[1]] = name;\n        for (let i=1;i<acc.length;i++) {\n            if (!graph[acc[i]]) graph[acc[i]] = new Set();\n            nameDict[acc[i]] = name;\n            if (i != 1) {\n                graph[acc[1]].add(acc[i]);\n                graph[acc[i]].add(acc[1]);\n            }\n        }\n    }\n\n    let res = [];\n    let visited = new Set();\n\n    let dfs = function (key) {\n        visited.add(key);\n        let emails = [key];\n        graph[key].forEach((e)=>{\n            if (!visited.has(e)) {\n                emails.push(...dfs(e));\n            }\n        })\n\n        return emails;\n    }\n\n    for (let key in graph) {\n        if (!visited.has(key)) {\n            let temp = dfs(key);\n            temp.sort();\n            temp.unshift(nameDict[temp[0]]);\n            res.push(temp);\n        }\n    }\n\n    return res;\n};",559        "solution_java": "class Solution {\n    public List<List<String>> accountsMerge(List<List<String>> accounts) {\n        \n        int l = accounts.size();\n        UnionFind uf = new UnionFind(l);\n        \n        Map<String, Integer> emailToNameId = new HashMap<>();\n        \n        for(int i=0; i<l; i++) {\n            List<String> account = accounts.get(i);\n            for(int j=1; j<account.size(); j++) {\n                String email = account.get(j);\n                int currentNameId = i;\n                if (emailToNameId.containsKey(email)) {\n                    int oldNameId = emailToNameId.get(email);\n                    // Join new and old name ids so that we can know which emails can be merged together. Emails in a single component can be merged together.\n                    uf.union(currentNameId, oldNameId);\n                } else {\n                    emailToNameId.put(email, currentNameId);\n                }\n            }\n        }\n        // emailToNameId = {johnnybravo@mail.com=3, johnsmith@mail.com=0, john00@mail.com=1, john_newyork@mail.com=0, mary@mail.com=2}\n\n        // Use TreeSet for alphabetical order. \n        Map<Integer, TreeSet<String>> nameIdToEmails = new HashMap<>();\n        for(int i=0; i<l; i++) {\n            int root = uf.find(i);\n            nameIdToEmails.putIfAbsent(root, new TreeSet<>());\n            List<String> account = accounts.get(i);\n            List<String> emails = account.subList(1, account.size());\n            nameIdToEmails.get(root).addAll(emails);\n        }\n        // nameIdToEmails = {1=[john00@mail.com, john_newyork@mail.com, johnsmith@mail.com], 2=[mary@mail.com], 3=[johnnybravo@mail.com]}\n\n        List<List<String>> out = new ArrayList<>();\n        for(int id : nameIdToEmails.keySet()) {\n            String name = accounts.get(id).get(0);\n            List<String> emails = new ArrayList<>(nameIdToEmails.get(id));\n            emails.add(0, name);\n            out.add(emails);\n        }\n        return out;\n    }\n    \n    class UnionFind {\n        int[] parent;\n        int[] rank;\n        \n        UnionFind(int size) {\n            parent = new int[size];\n            rank = new int[size];\n            for(int i=0; i<size; i++) {\n                parent[i] = i;\n                rank[i] = 1;\n            }\n        }\n        \n        public void union(int x, int y) {\n            int rootX = find(x);\n            int rootY = find(y);\n            if (rootX != rootY) {\n                if (rank[rootX] > rank[rootY]) {\n                    parent[rootY] = rootX;\n                } else if (rank[rootX] < rank[rootY]) {\n                    parent[rootX] = rootY;\n                } else {\n                    parent[rootY] = rootX;\n                    rank[rootX] += 1;\n                }\n            }\n        }\n        \n        public int find(int x) {\n            if (x == parent[x]) {\n                return x;\n            }\n            return parent[x] = find(parent[x]);\n        }\n        \n        \n    }\n}",560        "solution_c": "class Solution {\npublic:\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        map<string,int>stop;\n        map<int,string>name;\n        int count=0;\n        vector<int>par(1005,0),sz(1005,1);\n        for(int i=1;i<=1000;i++)\n        {\n            par[i]=i;\n        }\n        function<int(int)> findpar = [&](int a) -> int {\n            if(a==par[a])return par[a];\n            return par[a]=findpar(par[a]);\n        };\n        function<void(int,int)> dounion =[&](int a,int b) ->void {\n            a=findpar(a);\n            b=findpar(b);\n            if(a!=b)\n            {\n                if(sz[a]<sz[b]) swap(a,b);\n                par[b]=a;\n                sz[a]+=sz[b];\n            }\n        };\n        \n        for(auto it:accounts){\n            \n            int n=it.size();\n            vector<int>curpar;\n            for(int i=1;i<n;i++)\n            {\n                if(stop[it[i]])\n                    curpar.push_back(stop[it[i]]);\n            }\n            if(curpar.size()==0) // if no par present \n            {\n                count++;\n                for(int i=1;i<n;i++)\n                {\n                    stop[it[i]]=count;\n                }\n                name[count]=it[0];\n            }\n            else{ // if par present then do union\n                int first=curpar[0];\n                for(int i=1;i<n;i++) \n                {\n                    stop[it[i]]=first;\n                }\n                \n                for(int j=1;j<curpar.size();j++) // union for all child\n                {\n                    int id=curpar[j];\n                    dounion(first,id);\n                }\n            }\n        }\n        \n        vector<vector<string>>ans;\n        \n        for(int i=1;i<=1000;i++)\n        {\n            vector<string> cur;\n            if(findpar(i)==i)\n            {\n                for(auto it:stop)\n                {\n                    if(findpar(it.second)==i){\n                        cur.push_back(it.first);\n                    }\n                }\n            }\n            if(cur.size()>0)\n            {\n                cur.insert(cur.begin(),name[i]);\n                ans.push_back(cur);\n            }\n        }\n        return ans;\n    }\n};"561    },562    {563        "title": "Minimum Area Rectangle II",564        "algo_input": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\n\nReturn the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0.\n\nAnswers within 10-5 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,2],[2,1],[1,0],[0,1]]\nOutput: 2.00000\nExplanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.\n\n\nExample 2:\n\nInput: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput: 1.00000\nExplanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.\n\n\nExample 3:\n\nInput: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput: 0\nExplanation: There is no possible rectangle to form from these points.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 50\n\tpoints[i].length == 2\n\t0 &lt;= xi, yi &lt;= 4 * 104\n\tAll the given points are unique.\n\n",565        "solution_py": "class Solution:\n    def minAreaFreeRect(self, points: List[List[int]]) -> float:\n        N = len(points)\n        \n        seen = set()\n        for point in points:\n            seen.add(tuple(point))\n\n        # length^2\n        def length2(a, b):\n            return (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])\n        \n        best = 1e30\n        for i in range(N):\n            for j in range(N):\n                if i == j:\n                    continue\n                \n                lij = length2(points[i], points[j])\n                for k in range(N):\n                    if i == k or j == k:\n                        continue\n                    \n                    # given i->j line, add to k to find l\n                    dx, dy = points[j][0] - points[i][0], points[j][1] - points[i][1]\n                    \n                    pl = (points[k][0] + dx, points[k][1] + dy)\n                    if pl not in seen:\n                        continue\n                    \n                    lik = length2(points[i], points[k])\n                    ljk = length2(points[j], points[k])\n\n                    lil = length2(points[i], pl)\n                    ljl = length2(points[j], pl)\n                    lkl = length2(points[k], pl)\n                    \n                    if lij == lkl and lik == ljl and lil == ljk:\n                        best = min(best, sqrt(lij * lik * lil) / sqrt(max(lij, lik, lil)))\n                    \n        if best >= 1e29:\n            return 0\n        return best",566        "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\nvar minAreaFreeRect = function(points) {\n    let len = points.length;\n    \n    if (len < 4) return 0;\n    \n    // Helper function to calculate distance\n    // between two points, optionally return \n    // without sqrt if want to use as key\n    const getDistance = (a, b, isKey = false) => {\n        let [xa, ya] = a;\n        let [xb, yb] = b;\n        \n        const distance = (xa - xb) * (xa - xb) + (ya - yb) * (ya - yb);\n        return isKey ? distance : Math.sqrt(distance);\n    }\n    \n    let map = new Map();\n    \n    // let's loop over all points and find all possible\n    // diagonals and calc - dis with midpoints and \n    // save as key with co-ordinates as values\n    for (let i = 0; i < len; i += 1) {\n        for (let j = i + 1; j < len; j += 1) {\n            let disKey = getDistance(points[i], points[j], true);\n            let [xa, ya] = points[i];\n            let [xb, yb] = points[j];\n            \n            let x = (xa + xb) / 2;\n            let y = (ya + yb) / 2;\n            \n            let key = `${disKey}-${x}-${y}`;\n            \n            let list = [];\n            \n            if (!map.has(key)) {\n                map.set(key, list)\n            } else list = map.get(key);\n            \n            list.push([i, j]);\n            \n            map.set(key, list);\n        }\n    }\n    \n    // console.log(map);\n    let res = Number.MAX_VALUE;\n    \n    // loop over map of keys above and\n    // only iterate through the list where at least \n    // 2 set of co-ordinates have been found above\n    map.forEach((list, key) => {\n        if (list.length > 1) {\n            for (let i = 0; i < list.length; i += 1) {\n                for (let j = i + 1; j < list.length; j += 1) {\n                    let p1 = list[i][0];\n                    let p2 = list[j][0];\n                    let p3 = list[j][1];\n                    \n                    let l = getDistance(points[p1], points[p2]);\n                    let b = getDistance(points[p1], points[p3]);\n                    res = Math.min(res, l * b);\n                }\n            }\n        }\n    })\n    \n    return res === Number.MAX_VALUE ? 0 : res;\n    \n};",567        "solution_java": "class Solution {\n    public double minAreaFreeRect(int[][] points) {\n        Map<Pair<Double, Double>, Map<Double, List<int[][]>>> map = new HashMap<>();\n\n        double res = Double.MAX_VALUE;\n        for (int i = 0; i < points.length; i++) {\n            int[] p1 = points[i];\n            for (int j = i+1; j < points.length; j++) {\n                int[] p2 = points[j];\n                // get mid point\n                Pair<Double, Double> pm = new Pair((p1[0]+p2[0])/2d, (p1[1]+p2[1])/2d);\n                if (!map.containsKey(pm))\n                    map.put(pm, new HashMap<>());\n                // get diagonal length\n                double dist2 = dist2(p1, p2);\n                if (!map.get(pm).containsKey(dist2))\n                    map.get(pm).put(dist2, new ArrayList<>());\n\n                // calculate area for each pair of p3/p4 and check min\n                // Worst case is each pair has same mid point with same length\n                // At worst case, below operation costs O(N)\n                for (int[][] ps : map.get(pm).get(dist2)) {\n                    double d1 = dist2(p1, ps[0]);\n                    double d2 = dist2(p1, ps[1]);\n                    res = Math.min(res, Math.sqrt(d1 * d2));\n                }\n                map.get(pm).get(dist2).add(new int[][]{p1, p2});\n            }\n        }\n\n        return res == Double.MAX_VALUE ? 0 : res;\n    }\n\n    private double dist2(int[] p1, int[] p2) {\n        return (p2[0]-p1[0])*(p2[0]-p1[0]) + (p2[1]-p1[1])*(p2[1]-p1[1]);\n    }\n}",568        "solution_c": "#define x1 points[i][0]\n#define y1 points[i][1]\n#define x2 points[j][0]\n#define y2 points[j][1]\n#define x3 points[k][0]\n#define y3 points[k][1]\n\nclass Solution {\npublic:\n  double minAreaFreeRect(vector<vector<int>>& points) {\n    int ans = INT_MAX;\n    sort(points.begin(),points.end());\n    set<pair<int,int>>st;\n    for(auto &p: points) st.insert({p[0], p[1]});\n    \n    for(int i = 0; i != points.size() && ans != 1; i++)\n      for(int j = i+1; j != points.size() && ans != 1; j++)\n        for(int k = j+1; k != points.size() && ans != 1; k++)\n          if( (x1-x2)*(x2-x3)+(y1-y2)*(y2-y3) == 0 && st.count({x1+x3-x2, y1+y3-y2}))\n          ans = min(ans, abs( (y1-y2)*(x3-x2) - (x1-x2)*(y3-y2)));\n         \n    return ans == INT_MAX ? 0.0 : double(ans);\n  }\n};"569    },570    {571        "title": "Queries on Number of Points Inside a Circle",572        "algo_input": "You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.\n\nYou are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.\n\nFor each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.\n\nReturn an array answer, where answer[j] is the answer to the jth query.\n\n&nbsp;\nExample 1:\n\nInput: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\nOutput: [3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\n\n\nExample 2:\n\nInput: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\nOutput: [2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 500\n\tpoints[i].length == 2\n\t0 &lt;= x​​​​​​i, y​​​​​​i &lt;= 500\n\t1 &lt;= queries.length &lt;= 500\n\tqueries[j].length == 3\n\t0 &lt;= xj, yj &lt;= 500\n\t1 &lt;= rj &lt;= 500\n\tAll coordinates are integers.\n\n\n&nbsp;\nFollow up: Could you find the answer for each query in better complexity than O(n)?\n",573        "solution_py": "class Solution:\n\tdef countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n\t\tcircle = []\n\t\tfor x2, y2, radius in queries:\n\t\t\tcount = 0\n\t\t\tfor x1, y1 in points:\n\t\t\t\tdis = ((x2-x1)**2+(y2-y1)**2)**0.5 # Use the Distance Formula...\n\t\t\t\tif dis <= radius:\n\t\t\t\t\tcount += 1\n\t\t\tcircle.append(count)\n\t\treturn circle",574        "solution_js": "var countPoints = function(points, queries) {\n    const getDistance = (x1,y1,x2,y2) => {\n        return Math.sqrt((x1-x2) * (x1-x2) + (y1-y2) * (y1-y2));\n    }\n    \n    let output = [];\n    \n    queries.forEach(([a,b,r]) => {\n        let count = 0;\n        points.forEach(([x,y]) => {\n            if(getDistance(a,b,x,y) <= r) count += 1;\n        });\n        output.push(count);\n    });\n \n    return output;\n};",575        "solution_java": "class Solution {\n    public int[] countPoints(int[][] points, int[][] queries) {\n        int len = queries.length;\n        int[] ans = new int[len];\n\n        for(int i=0;i<len;i++){\n            int count = 0;\n            int radius2 = queries[i][2] * queries[i][2];\n            for(int p=0; p<points.length;p++){\n                int[] point = points[p];\n                if(radius2(point,queries[i]) <= radius2){\n                    count += 1;\n                }\n            }\n            ans[i] = count;\n        }\n\n        return ans;\n    }\n\n    private int radius2(int[] point, int[] center){\n        int x = point[0] - center[0];\n        int y = point[1] - center[1];\n        return x*x + y*y;\n    }\n}",576        "solution_c": "class Solution {\n    void buildTree(vector<vector<int>>& p, int depth, int i, int j) {\n        if (j - i <= 1) return;\n        \n        int k = 1 - depth & 1, m = i + (j - i) / 2;\n        nth_element(p.begin() + i, p.begin() + m, p.begin() + j,\n                    [k](auto &a, auto& b) { return a[k] < b[k]; });\n        partition(p.begin() + i, p.begin() + j,\n                  [k, m, &p](auto &a){ return a[k] < p[m][k]; });\n\n        buildTree(p, depth+1, i, m);\n        buildTree(p, depth+1, m+1, j);\n    }\n    \n    inline bool isPointInside(const vector<int> &p, const vector<int> &c) {\n        return (p[0] - c[0]) * (p[0] - c[0]) + (p[1] - c[1]) * (p[1] - c[1]) <= c[2] * c[2];\n    }\n\n    int pointsInside(const vector<vector<int>> &t, const vector<int> &q, int depth,\n                    int i, int j) {\n        if (j == i) return 0;\n        else if (j - i == 1) return isPointInside(t[i], q);\n        \n        int k = 1 - depth & 1, m = i + (j - i) / 2, diff = t[m][k] -  q[k];\n        if (diff > q[2]) return pointsInside(t, q, depth+1, i, m);\n        else if (diff < -q[2]) return pointsInside(t, q, depth+1, m+1, j);\n        else\n            return pointsInside(t, q, depth+1, i, m)\n                + isPointInside(t[m], q)\n                + pointsInside(t, q, depth+1, m+1, j);\n    }\npublic:\n    vector<int> countPoints(vector<vector<int>>& points, vector<vector<int>>& queries) {\n        buildTree(points, 0, 0, points.size());\n\n        vector<int> res(queries.size());\n        for (size_t i = 0; i < queries.size(); ++i)\n            res[i] = pointsInside(points, queries[i], 0, 0, points.size());\n        return res;\n    }\n};"577    },578    {579        "title": "Course Schedule IV",580        "algo_input": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.\n\n\n\tFor example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.\n\n\nPrerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.\n\nYou are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.\n\nReturn a boolean array answer, where answer[j] is the answer to the jth query.\n\n&nbsp;\nExample 1:\n\nInput: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput: [false,true]\nExplanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.\n\n\nExample 2:\n\nInput: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput: [false,false]\nExplanation: There are no prerequisites, and each course is independent.\n\n\nExample 3:\n\nInput: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput: [true,true]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= numCourses &lt;= 100\n\t0 &lt;= prerequisites.length &lt;= (numCourses * (numCourses - 1) / 2)\n\tprerequisites[i].length == 2\n\t0 &lt;= ai, bi &lt;= n - 1\n\tai != bi\n\tAll the pairs [ai, bi] are unique.\n\tThe prerequisites graph has no cycles.\n\t1 &lt;= queries.length &lt;= 104\n\t0 &lt;= ui, vi &lt;= n - 1\n\tui != vi\n\n",581        "solution_py": "class Solution:\n    \"\"\"\n    one approach I can think of is, given a graph, \n    the query[a, b] will be true if there exists a path from a to b in the graph\n    else a will not be a prerequisite of b\n    but this approach may not scale as the # of queries will increase\n    \"\"\"\n    def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n        graph = {node: set() for node in range(numCourses)}\n        for pre in prerequisites:\n            graph[pre[0]].add(pre[1])\n        \n        def path(cur_node, node_b):\n            if cur_node == node_b:\n                return True\n            for neighbor in graph[cur_node]:\n                if path(neighbor, node_b):\n                    return True\n            return False\n            \n        ans = []\n        for query in queries:\n            # see if there is a path from query[0] to query[1]\n            ans.append(path(query[0], query[1]))\n        return ans",582        "solution_js": "var checkIfPrerequisite = function(numCourses, prerequisites, queries) {\n    let adj = {};\n    for (let [from, to] of prerequisites) {\n        if (!adj[from]) {\n            adj[from] = [];\n        }\n        \n        adj[from].push(to);\n    }\n    \n    let set = {};\n    Object.keys(adj).forEach(key => dfs(key));\n    return queries.map(([a,b]) => set[a]?.has(b) || false);\n    \n    function dfs(cur) {\n        if (set[cur]) {\n            return set[cur];\n        }\n        \n        if (!set[cur]) {\n            set[cur] = new Set();\n        }\n        \n        for (let n of (adj[cur] || [])) {\n            set[cur].add(n);\n            dfs(n);\n            set[n].forEach(set[cur].add, set[cur]);\n        }\n    }\n    \n};",583        "solution_java": "class Solution {\n    public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {\n        // Generating Map\n        Map<Integer, List<Integer>> graph = new HashMap<>();\n        for(int e[]: prerequisites){\n            graph.putIfAbsent(e[0], new ArrayList<>());\n            graph.get(e[0]).add(e[1]);\n        }\n\n        List<Boolean> list = new ArrayList<>();\n        // Appling DFS for every query to get result\n        for(int[] q: queries){\n            list.add(isPre(q[0], q[1], graph, new HashSet<>()));\n        }\n        return list;\n    }\n    // Check if src comes before dst using DFS\n    private boolean isPre(int src, int dst, Map<Integer, List<Integer>> adj, Set<Integer> visited){\n        if(visited.contains(src)) return false;\n        visited.add(src);\n        for(int neigh: adj.getOrDefault(src, new ArrayList<>())){\n            if(neigh == dst || isPre(neigh, dst, adj, visited)) return true;\n        }\n        return false;\n    }\n}",584        "solution_c": "// question similar to find all ancestors of current node\n\nclass Solution {\n\npublic:\n\n    void dfs(vector<vector<int>>&adj,vector<set<int>>&Anc,int u,int par,vector<int>&vis)\n    {\n        if( vis[u] != 0 )\n            return ;\n\n        vis[u] = 1 ;\n\n        for(auto&v:adj[u])\n        {\n            if( vis[v] == 0 )\n            {\n                Anc[v].insert(par) ;\n                dfs(adj,Anc,v,par,vis) ;\n            }\n        }\n\n        return ;\n    }\n\n    vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {\n\n        int n = numCourses ;\n        vector<vector<int>>adj(n);\n        vector<set<int>>Anc(n);\n        vector<bool>ans;\n\n        for(auto&edge:prerequisites)\n        {\n            adj[edge[0]].push_back(edge[1]) ;\n        }\n\n        for(int i=0;i<n;i++)\n        {\n            vector<int>vis(n,0);\n            dfs(adj,Anc,i,i,vis) ;\n        }\n\n        for(auto&EachQuery:queries)\n        {\n            if( Anc[EachQuery[1]].find(EachQuery[0]) != Anc[EachQuery[1]].end() )\n                ans.push_back(true);\n            else\n                ans.push_back(false) ;\n        }\n        return ans ;\n    }\n\n};"585    },586    {587        "title": "K-Concatenation Maximum Sum",588        "algo_input": "Given an integer array arr and an integer k, modify the array by repeating it k times.\n\nFor example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].\n\nReturn the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.\n\nAs the answer can be very large, return the answer modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,2], k = 3\nOutput: 9\n\n\nExample 2:\n\nInput: arr = [1,-2,1], k = 5\nOutput: 2\n\n\nExample 3:\n\nInput: arr = [-1,-2], k = 7\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= k &lt;= 105\n\t-104 &lt;= arr[i] &lt;= 104\n\n",589        "solution_py": "class Solution:\n    def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n        \n        dp = [0] * len(arr) # sum of the best subarry ends at i\n        dp[0] = arr[0]\n        total = arr[0] # total sum \n        right = arr[0] # sum of the best subarray starts at 0\n        \n        p = 1 \n        while p < len(arr):\n            dp[p] = max(arr[p], dp[p-1] + arr[p])\n            total += arr[p] \n            right = max(right, total)\n            \n            p += 1\n        \n        isolated = max(dp + [0]) # max sum\n        left = dp[-1] # sum of the best subarray ends at n-1\n        \n        if k == 1:\n            \n            return isolated  % (10**9 + 7)\n        \n        return max(left + right + max(0,(k-2) * total), isolated) % (10**9 + 7)",590        "solution_js": "var kConcatenationMaxSum = function(arr, k) {\n    var MOD = 1000000007;\n    let sum = arr.reduce((a,b)=>a+b);\n    if(k>1) arr.push(...arr);\n    let temp = 0, result = 0;\n     for(i=0;i<arr.length;i++){\n          temp = Math.max(arr[i],arr[i]+temp);\n          if(temp>result) result = temp;\n        }\n    return (sum>0&&k>2) ? (result+sum*(k-2))%MOD : result%MOD;\n};",591        "solution_java": "class Solution {\n    int mod = 1000000007;\n    \n    public int kadane(int[] a ){\n        int curr = 0;\n        int max = Integer.MIN_VALUE;\n        for(int i: a )\n        {\n            curr+=i;\n            if(curr<0 )\n                curr =0;\n            max = Math.max(max,curr );\n            \n        }\n        \n        return max%mod ;\n    }\n    public int kConcatenationMaxSum(int[] arr, int k) {\n        \n        int n = arr.length;\n        if(k==1 ) \n            return kadane(arr);\n        int[] temp = new int[2*n]; \n        for(int i=0;i<n;i++){\n            temp[i]=arr[i];\n            temp[n+i] =arr[i];\n        }\n        if(k==2 )\n            return kadane(temp)%mod;\n        \n        long sum = 0;\n        for(int i: arr) \n            sum+=i;\n        \n        if(sum>=0 )\n            return (int)( (kadane(temp)%mod)+ ((sum%mod) * (k-2)%mod) %mod);\n        else\n            return (kadane(temp)%mod );\n    }\n}",592        "solution_c": "class Solution {\npublic:\n\n    // Compute max score across all cases\n    //  1. (arr_sum * k) [array sum is positive]\n    //  2. (subarray_sum) [k == 1]\n    //  3. if k > 1:\n    //          if k == 2: lm + rm\n    //          else: lm + (arr_sum * (k-2)) + rm\n\n    // For case:3, instead of running over the entire modified array,\n    //  we can just add (arr_sum * (k-2)) to the 's' instead.\n\n    int kConcatenationMaxSum(vector<int>& arr, int k) {\n        \n        const int n = arr.size();\n        int64_t s{}, min_s{}, max_score{INT_MIN};\n        \n        // This loop computes the answer for case:2\n        for(int i=0; i<n; i++){\n            s += arr[i];\n            max_score = max(max_score, s - min_s);\n            min_s = min(min_s, s);\n        }\n        \n        if(k > 1){\n            // Condition for case:3 part:2\n            // At this point, 's' holds the sum of all numbers in 'arr'\n            if(k > 2) s = max(s, s + s * (k - 2));\n            // Base logic for case:3 part:1\n            for(int i=0; i<n; i++){\n                s += arr[i];\n                max_score = max(max_score, s - min_s);\n                min_s = min(min_s, s);\n            }\n        }\n\n        // If all numbers are positive, case:1 is automatically computed with\n        //  the method given above.\n        //  Because (for an array with all positive elements):\n        //      (max_score [after first loop]) == (arr_sum)\n        //      s is updated to (s + s * (k - 2))\n        //      Finally, s (and subsequently max_score) is also updated to (arr_sum * k)\n\n        // Apply modulo on answer and convert to int\n        int ans = static_cast<int>(max_score % (1000000000 + 7));\n        // Subarray can have length == 0 (and sum == 0)\n        if(ans < 0) return 0;\n        else return ans;\n    }\n};"593    },594    {595        "title": "Stone Game",596        "algo_input": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].\n\nThe objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.\n\nAlice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.\n\nAssuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.\n\n&nbsp;\nExample 1:\n\nInput: piles = [5,3,4,5]\nOutput: true\nExplanation: \nAlice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.\n\n\nExample 2:\n\nInput: piles = [3,7,2,3]\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= piles.length &lt;= 500\n\tpiles.length is even.\n\t1 &lt;= piles[i] &lt;= 500\n\tsum(piles[i]) is odd.\n\n",597        "solution_py": "class Solution:\n    def stoneGame(self, piles: List[int]) -> bool:\n        return True",598        "solution_js": "var stoneGame = function(piles) {\n    return true;\n};",599        "solution_java": "class Solution {\n    \n    //This is the Easy One..\n    //The main Thing is We(Alice) have to take win\n    \n    //alice going to check the even sum and the odd sum if even sum> odd sum alice start with 0 else start with n-1.\n    public boolean stoneGame(int[] piles) {\n        return true;\n    }\n}",600        "solution_c": "class Solution {\npublic:\n\n    int solve(vector<int>&piles, int i, int j, vector<vector<int>>&dp){\n\n        if(i==j)\n            return piles[i];\n\n        if(dp[i][j]!=-1)\n            return dp[i][j];\n\n        return dp[i][j] = max((piles[i] + solve(piles, i+1, j, dp)), (piles[j] + solve(piles, i, j-1, dp)));\n\n    }\n\n    bool stoneGame(vector<int>& piles) {\n        int n = piles.size();\n        vector<vector<int>>dp(n, vector<int>(n,-1));\n        return solve(piles, 0, n-1, dp);\n    }\n};"601    },602    {603        "title": "Convert Sorted Array to Binary Search Tree",604        "algo_input": "Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.\n\nA height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.\n\n&nbsp;\nExample 1:\n\nInput: nums = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: [0,-10,5,null,-3,null,9] is also accepted:\n\n\n\nExample 2:\n\nInput: nums = [1,3]\nOutput: [3,1]\nExplanation: [1,null,3] and [3,1] are both height-balanced BSTs.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-104 &lt;= nums[i] &lt;= 104\n\tnums is sorted in a strictly increasing order.\n\n",605        "solution_py": "class Solution:\n    def formNodes(self,nums, l,r):\n        if l > r:\n            return None\n        else:\n            mid = l+(r-l)//2\n            node = TreeNode(nums[mid])\n            node.left = self.formNodes(nums, l,mid-1)\n            node.right = self.formNodes(nums, mid+1,r)\n            return node\n        \n        \n    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:\n        return self.formNodes(nums, 0,len(nums)-1)",606        "solution_js": "var sortedArrayToBST = function(nums) {\n    if (nums.length === 0) return null;\n    // array length - 1 divided by 2\n    let mid = (nums.length - 1) >> 1;\n    let node = new TreeNode(nums[mid]);\n    node.left = sortedArrayToBST(nums.slice(0, mid));\n    node.right = sortedArrayToBST(nums.slice(mid + 1));\n    return node;\n};",607        "solution_java": "class Solution {\n    public TreeNode sortedArrayToBST(int[] nums) {\n        if (nums.length == 0) return null;\n        var mid = nums.length / 2;\n        var root = new TreeNode(nums[mid]);\n        var left_array = Arrays.copyOfRange(nums, 0, mid);\n        var right_array = Arrays.copyOfRange(nums, mid + 1, nums.length);\n        root.left = sortedArrayToBST(left_array);\n        root.right = sortedArrayToBST(right_array);\n        return root;\n    }\n}",608        "solution_c": "class Solution {\npublic:\n    TreeNode* sortedArrayToBST(vector<int>& nums) {\n        \n        int n = nums.size(); \n        if(n==0) //if no elements are present\n            return NULL;\n        if(n==1) //if only one element is present\n            return new TreeNode(nums[0]); //create the root node with that element\n        \n        int mid = n/2; //finding the position of the middle element in the array\n        TreeNode* root = new TreeNode(nums[mid]); //create root node with mid element\n        \n        vector<int> l (nums.begin(), nums.begin()+mid); //left subarray\n        vector<int> r (nums.begin()+mid+1, nums.end()); //right subarray\n        \n        //using recursion to form the rest of the nodes :\n        \n        //the left nodes of the root must be smaller than root\n        root->left = sortedArrayToBST(l); \n        \n        //the right nodes of the root must be greater than root\n        root->right = sortedArrayToBST(r);\n        \n        return root;\n    }\n};"609    },610    {611        "title": "Count Special Quadruplets",612        "algo_input": "Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:\n\n\n\tnums[a] + nums[b] + nums[c] == nums[d], and\n\ta &lt; b &lt; c &lt; d\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,6]\nOutput: 1\nExplanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.\n\n\nExample 2:\n\nInput: nums = [3,3,6,4,5]\nOutput: 0\nExplanation: There are no such quadruplets in [3,3,6,4,5].\n\n\nExample 3:\n\nInput: nums = [1,1,1,3,5]\nOutput: 4\nExplanation: The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5\n\n\n&nbsp;\nConstraints:\n\n\n\t4 &lt;= nums.length &lt;= 50\n\t1 &lt;= nums[i] &lt;= 100\n\n",613        "solution_py": "class Solution:\n    def countQuadruplets(self, nums: List[int]) -> int:\n        return sum([1 for a, b, c, d in combinations(nums, 4) if a + b + c == d])",614        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countQuadruplets = function(nums) {\n    const map = new Map();\n    \n    for(let i = 0; i < nums.length; i++) {\n        let n = nums[i];\n        \n        if(map.has(n)) {\n            let t = map.get(n);\n            t.push(i);\n            map.set(n, t);\n        } else {\n            map.set(n, [i]);\n        }\n    }\n    \n    let count = 0;\n    \n    for(let a = 0;a < nums.length - 3; a++) {\n        for(let b = a + 1; b < nums.length - 2; b++) {\n            for(let c = b + 1; c < nums.length - 1;c++) {\n                let sum = nums[a] + nums[b] + nums[c];\n                \n                let indexes = map.get(sum) || [];\n\t\t\t\t//t is the d index that might exist\n                let t = c + 1;\n                \n                let low = 0;\n                let high = indexes.length - 1;\n                let ans = -1;\n                \n                while(low <= high) {\n                    let mid = low + Math.floor((high - low)/2);\n                    \n                    if(indexes[mid] === t) {\n                        ans = mid;\n                        break;\n                    }\n                    \n                    if(indexes[mid] < t) {\n                        low = mid + 1;\n                    } else {\n                        ans = mid;\n                        high = mid - 1;\n                    }\n                }\n                \n                if(ans !== -1) {\n                    count += indexes.length - ans;\n                }\n            }\n        }\n    }\n    \n    return count;\n};",615        "solution_java": "class Solution {\n    public int countQuadruplets(int[] nums) {\n        int res = 0;\n        int len = nums.length;\n        \n        Map<Integer, Integer> count = new HashMap<>();\n        count.put(nums[len-1] - nums[len-2], 1);\n        \n        for (int b = len - 3; b >= 1; b--) {\n            for (int a = b - 1; a >= 0; a--) {\n                res += count.getOrDefault(nums[a] + nums[b], 0);\n            }\n            \n            for (int x = len - 1; x > b; x--) {\n                count.put(nums[x] - nums[b], count.getOrDefault(nums[x] - nums[b], 0) + 1);\n            }\n        }\n        \n        return res;\n    }\n}",616        "solution_c": "class Solution {\npublic:\n    int countQuadruplets(vector<int>& nums) {\n        int n=nums.size();\n        unordered_map<int,int> m;\n        int ans=0;\n        for(int i=1;i<n-2;i++){\n            for(int j=0;j<i;j++){\n                m[nums[i]+nums[j]]++;\n            }\n            for(int k=i+2;k<n;k++){\n               ans+= m[nums[k]-nums[i+1]];\n            }\n        }\n        return ans;\n    }\n};"617    },618    {619        "title": "Delete Columns to Make Sorted II",620        "algo_input": "You are given an array of n strings strs, all of the same length.\n\nWe may choose any deletion indices, and we delete all the characters in those indices for each string.\n\nFor example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\n\nSuppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] &lt;= strs[1] &lt;= strs[2] &lt;= ... &lt;= strs[n - 1]). Return the minimum possible value of answer.length.\n\n&nbsp;\nExample 1:\n\nInput: strs = [\"ca\",\"bb\",\"ac\"]\nOutput: 1\nExplanation: \nAfter deleting the first column, strs = [\"a\", \"b\", \"c\"].\nNow strs is in lexicographic order (ie. strs[0] &lt;= strs[1] &lt;= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.\n\n\nExample 2:\n\nInput: strs = [\"xc\",\"yb\",\"za\"]\nOutput: 0\nExplanation: \nstrs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] &lt;= strs[0][1] &lt;= ...)\n\n\nExample 3:\n\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: We have to delete every column.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == strs.length\n\t1 &lt;= n &lt;= 100\n\t1 &lt;= strs[i].length &lt;= 100\n\tstrs[i] consists of lowercase English letters.\n\n",621        "solution_py": "class Solution:\n    def minDeletionSize(self, strs: List[str]) -> int:\n        n = len(strs)\n        col_size = len(strs[0])\n        # a b c d e f g h i j k l m n o p q r s t u v w x y z\n        \n        i = 0\n        ans = 0\n        \n        def getRemoved(idx):\n             # removing the idx column \n            for x in range(n):           \n                strs[x] = strs[x][:idx] + strs[x][idx+1:]\n        \n        while i < col_size:\n            tmp = strs[0][:i+1]\n            flag = True\n            similar = False\n            \n            for j in range(1,n):                 \n                if  strs[j][:i+1] < tmp :\n                    # previous element is larger ( unsorted )\n                    flag = False\n                    break\n                \n                elif strs[j][:i+1] > tmp : \n                    # previous element is smaller ( sorted )\n                    tmp = strs[j][:i+1]\n                \n                else:\n                    # previous element is equal ( not clear )\n                    tmp = strs[j][:i+1]\n                    similar = True\n            \n            if flag == True and similar == False:\n                # all are sorted and we are ready to return ans\n                return ans\n            \n            elif flag == True and similar == True:\n                # all are sorted but can't be decided for further columns. check for next col\n                i += 1\n            \n            elif flag == False:\n                # unsorted column = removal\n                getRemoved(i)\n                # increment the answer and since we removed i th col decrement col_size\n                ans += 1\n                col_size -= 1\n        \n        return ans",622        "solution_js": "var minDeletionSize = function(strs) {\n    const length = strs.length;\n    let inOrder = true, count = 0, deleteIndex = 0;\n    while(strs[0].length > 0) {\n        inOrder = true;\n        for(let i=0; i<length; i++) {\n            if(strs[i] > strs[i+1]) {\n                inOrder = false;\n                for(let index = 0; index<strs[i].length;index++) {\n                    if(strs[i][index] > strs[i+1][index]) {\n                        deleteIndex = index;\n                        break;\n                    }\n                }\n            }\n        }\n        for(let i=0; i<length; i++) {\n            strs[i] = strs[i].substring(0,deleteIndex) + strs[i].substring(deleteIndex+1);\n        }\n        if(inOrder) {\n            break;\n        } \n        else {\n            count++;\n        }\n    }\n    return count;    \n};",623        "solution_java": "class Solution {\n    public int minDeletionSize(String[] strs) {\n       boolean[] sorted = new boolean[strs.length];\n        int res = 0;\n        for(int i = 0;i<strs[0].length();i++){\n            int j = 0;\n           for(;j<strs.length-1;j++){\n              if(!sorted[j]&&strs[j].charAt(i)>strs[j+1].charAt(i)){\n                  res++;\n                  break;\n              }  \n            }\n            if(j<strs.length-1){\n                continue;\n            }\n            j = 0;\n            for(;j<strs.length-1;j++){\n                if(strs[j].charAt(i)<strs[j+1].charAt(i)){\n                    sorted[j] = true;\n                }\n            }\n        }\n        return res;\n}\n}",624        "solution_c": "// in this i have iterated for every column and then for every string\n// i have used array arr[101] in order to store wich indices are valid and which are not\n// i have taken an array of positions(vector) done[101] to find at which previous locations i found this particular (jth index string ) to be smaller than its successor\n\nclass Solution {\npublic:\n     int arr[101]={0}; // arr is to check which columns are valid(0) and invalid(-1)\n    vector<int> done[101]; // where u found string j was greater than string j+1 ,u put it into vector\n\n // below is a helper function in order to check all the locations (at which string j has been classified as done ) are still present or not\n    bool check(vector<int>& a){\n      for(int i:a){\n          if(arr[i]!=-1){\n              return 1;\n          }\n      }\n        return 0;\n    }\nint minDeletionSize(vector<string>& strs) {\n\n        int ans=0;\n// for iterating columns\n     for(int i=0;i<strs[0].size();i++){\n   // for iterating the strings\n         for(int j=0;j<strs.size()-1;j++){\n\n           if((done[j].size()==0 || check(done[j])==0) && strs[j][i]>strs[j+1][i]){\n\n                ans++;\n               arr[i]=-1; // make the column invalid\n                break;\n            }\n             if(strs[j][i]<strs[j+1][i]){\n\n                 done[j].push_back(i); // here we are storing at which index (i) said string j is ok\n             }\n         }\n\n     }\n\n        return ans;\n    }\n\n};"625    },626    {627        "title": "Minimum Cost to Move Chips to The Same Position",628        "algo_input": "We have n chips, where the position of the ith chip is position[i].\n\nWe need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:\n\n\n\tposition[i] + 2 or position[i] - 2 with cost = 0.\n\tposition[i] + 1 or position[i] - 1 with cost = 1.\n\n\nReturn the minimum cost needed to move all the chips to the same position.\n\n&nbsp;\nExample 1:\n\nInput: position = [1,2,3]\nOutput: 1\nExplanation: First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.\n\n\nExample 2:\n\nInput: position = [2,2,2,3,3]\nOutput: 2\nExplanation: We can move the two chips at position  3 to position 2. Each move has cost = 1. The total cost = 2.\n\n\nExample 3:\n\nInput: position = [1,1000000000]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= position.length &lt;= 100\n\t1 &lt;= position[i] &lt;= 10^9\n\n",629        "solution_py": "class Solution:\n    def minCostToMoveChips(self, position: List[int]) -> int:\n        count_even=0\n        count_odd=0\n        for i in position:\n            if i%2==0:\n                count_even+=1\n            else:\n                count_odd+=1\n        return min(count_even,count_odd)",630        "solution_js": "var minCostToMoveChips = function(position) {\n    const hashMap = new Map();\n    let odd = 0, even = 0;\n    for(const chip of position){\n        if(hashMap.has(chip)) hashMap.set(chip, hashMap.get(chip)+1);\n        else hashMap.set(chip, 1);\n    }\n    for(const [key, value] of hashMap){\n        if(key%2===0) even+=value;\n        else odd+=value;\n    }\n    return Math.min(odd, even);\n};",631        "solution_java": "class Solution {\n    public int minCostToMoveChips(int[] position) {\n        int even = 0;\n        int odd = 0;\n        for(int i=0;i<position.length;i++){\n            if(position[i]%2==0){\n                even++;\n            }else{\n                odd++;\n            }\n        }\n        return Math.min(even,odd);\n    }\n}",632        "solution_c": "class Solution {\npublic:\n    int minCostToMoveChips(vector<int>& position) {\n        int even=0,odd=0;\n        for(int i=0;i<position.size();i++)\n        {\n                if(position[i]%2==0)\n                    even++;\n                else\n                    odd++;\n\n        }\n        return min(odd,even);\n    }\n};"633    },634    {635        "title": "Maximum Number of Vowels in a Substring of Given Length",636        "algo_input": "Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.\n\nVowel letters in English are 'a', 'e', 'i', 'o', and 'u'.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abciiidef\", k = 3\nOutput: 3\nExplanation: The substring \"iii\" contains 3 vowel letters.\n\n\nExample 2:\n\nInput: s = \"aeiou\", k = 2\nOutput: 2\nExplanation: Any substring of length 2 contains 2 vowels.\n\n\nExample 3:\n\nInput: s = \"leetcode\", k = 3\nOutput: 2\nExplanation: \"lee\", \"eet\" and \"ode\" contain 2 vowels.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase English letters.\n\t1 &lt;= k &lt;= s.length\n\n",637        "solution_py": "class Solution:\n    def maxVowels(self, s: str, k: int) -> int:\n        \n        def find_count_vowels(string):\n            lst_vowels= ['a', 'e', 'i', 'o', 'u']\n            c=0\n            for i in string:\n                if i in lst_vowels:\n                    c+=1\n            return c\n            \n        \n        lst_vowels= ['a', 'e', 'i', 'o', 'u']\n        if k>len(s):\n            return find_count_vowels(s)\n        dp = [0]*(len(s)-k+1)\n        dp[0] = find_count_vowels(s[:k])\n        for i in range(1,len(s)-k+1):\n            \n           \n            if s[i-1] in lst_vowels and s[i+k-1] in lst_vowels:\n                dp[i] = dp[i-1]\n            elif s[i-1] in lst_vowels and s[i+k-1] not in lst_vowels:\n                dp[i] = dp[i-1] - 1\n\n            elif s[i-1] not in lst_vowels and s[i+k-1] in lst_vowels:\n                dp[i] = dp[i-1] + 1\n            else:\n                dp[i] = dp[i-1]\n        return max(dp)\n                ",638        "solution_js": "var maxVowels = function(s, k) {\n    let vowels = ['a', 'e', 'i', 'o', 'u'];\n    let maxCount = 0;\n    let start = 0; // the left edge of the window\n    let count = 0; // count of vowels for current substring\n\t// expanding the right edge of the window one character at a time\n    for (let end = 0; end < s.length; end++) {\n\t    // increment count of vowels for current substring if the current character is present in vowels array\n        if (vowels.includes(s[end])) {\n            count +=1;\n        }\n        // if substring is longer than K, let's shrink the window by moving left edge\n        if (end - start + 1 > k) {\n\t\t\t// reduce the current count by one if the character on the left edge is vowel\n            if(vowels.includes(s[start])) {\n                count -=1;\n            }\n\t\t\t//shrinking the left edge of the window\n            start +=1;\n        }\n\t\t// checking if current count is larger than current maximum count\n        maxCount = Math.max(maxCount, count)\n\t\t// if maxCount is equal to K, no need to check further, it is the max possible count\n        if (maxCount == k) return maxCount;\n    }\n    return maxCount;\n};",639        "solution_java": "class Solution {\n    public int maxVowels(String s, int k) {\n        int max=0,cnt=0;\n        for(int i=0,j=0;j<s.length();j++){\n            if(j-i+1<k){\n                if(s.charAt(j)=='a' ||s.charAt(j)=='e' || s.charAt(j)=='i' || s.charAt(j)=='o' || s.charAt(j)=='u' ){\n                    cnt++;\n                }\n            }\n            else{\n                if(s.charAt(j)=='a' ||s.charAt(j)=='e' || s.charAt(j)=='i' || s.charAt(j)=='o' || s.charAt(j)=='u'){\n                    cnt++;\n                }\n                max=Math.max(max,cnt);\n                if(s.charAt(i)=='a' ||s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){\n                    cnt--;\n                }\n                i++;\n            }\n            \n        }\n        return max;\n    }\n}",640        "solution_c": "class Solution {\npublic:\n    bool checkVowel(char c){\n        if(c == 'a' || c == 'e' || c =='i' || c == 'o' || c == 'u') return true;\n        return false;\n    }\n    int maxVowels(string s, int k) {\n        int count = 0;\n        int ans = 0;\n        for(int i = 0; i < k; i++){\n            if(checkVowel(s[i])) count++;\n        }\n        ans = count;\n        int j = 0;\n        for(int i = k; i<s.size(); i++){\n            if(checkVowel(s[i])) count++;\n            if(checkVowel(s[j])) count--;\n            j++;\n            ans = max(ans, count);\n        }\n        return ans;\n    }\n};"641    },642    {643        "title": "Maximum Sum Circular Subarray",644        "algo_input": "Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.\n\nA circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].\n\nA subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i &lt;= k1, k2 &lt;= j with k1 % n == k2 % n.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,-2,3,-2]\nOutput: 3\nExplanation: Subarray [3] has maximum sum 3.\n\n\nExample 2:\n\nInput: nums = [5,-3,5]\nOutput: 10\nExplanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\n\n\nExample 3:\n\nInput: nums = [-3,-2,-3]\nOutput: -2\nExplanation: Subarray [-2] has maximum sum -2.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 3 * 104\n\t-3 * 104 &lt;= nums[i] &lt;= 3 * 104\n\n",645        "solution_py": "class Solution:\n\n    def kadanes(self,nums):\n\n        #kadanes algo\n\n        max_till_now = nums[0]\n        curr_max = nums[0]\n\n        for i in range(1,len(nums)):\n            curr_max = max(curr_max+nums[i],nums[i])\n            max_till_now = max(max_till_now,curr_max)\n\n        return max_till_now\n\n    def maxSubarraySumCircular(self, nums: List[int]) -> int:\n\n        #there will be 2 case\n        #case 1 : our max subarray is not wrapping i.e not circular\n        #case 2: our max subarray is wrapping i.e circular\n\n        # case 1 is easy to find\n        # to find case 2 what we can do is if we multiply each nums element by -1 and\n        # on that find kadanes then we will get sum of elements which is not part of maxsubarray in case2 (not part because we negate)\n        # now subtract this newmax in case 2 from total nums sum, we get wrapping sum\n        # max of case1 and case is our ans\n\n        total = sum(nums)\n\n        nonwrappingsum = self.kadanes(nums)\n\n        # edge case when all elements are -ve then return max negative\n        if nonwrappingsum<0:\n            return nonwrappingsum\n\n        #negate\n        for i in range(len(nums)):\n            nums[i]*=-1\n\n        wrappingsum = total-(-self.kadanes(nums)) #-ve because originally it was negated\n\n        return max(nonwrappingsum,wrappingsum)",646        "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxSubarraySumCircular = function(nums) {\n    let n = nums.length;\n\n    // Kadane for single interval\n    let curr = nums[0]; // dp[j] Maximum sum subbarray till j\n    let ans = nums[0]; // Maximum of all dps till j i.e. max(dp[0], dp[1], ... dp[i], ...dp[j]);\n\n    for(let i = 1; i < n; i++) {\n        curr = nums[i] + Math.max(0, curr);\n        ans = Math.max(ans, curr);\n    }\n\n    /**\n    * If we don't find answer using kadane using above logic then that means only one thing\n    * some answer is present in 1st half and second in other half (since it is circular array)\n    **/\n\n    let rightSum = new Array(n); // Sum from Right, used to represent 2nd half of the solution\n\n    rightSum[n - 1] = nums[n - 1];\n\n    for(let i = n - 2; i >= 0; i--) {\n        rightSum[i] = rightSum[i + 1] + nums[i];\n    }\n\n    let maxRightSum = new Array(n); // Used to fast fetch max right sum till given point\n    maxRightSum[n - 1] = rightSum[n - 1];\n\n    for(let i = n - 2; i >= 0; i--) {\n        maxRightSum[i] = Math.max(maxRightSum[i + 1], rightSum[i]);\n    }\n\n    /**\n    * Now solution is max of:\n    * [Sum of [A0 --- Ai] + Maximum [Ai+2 --- An]]\n    * Considering i + 1 will be equivalent to kadane which we already discussed above.\n    **/\n    let leftSum = 0;\n    for(let i = 0; i < n - 2; i++) {\n        leftSum += nums[i];\n        ans = Math.max(ans, leftSum + maxRightSum[i + 2]);\n    }\n    return ans;\n\n};",647        "solution_java": "class Solution {\n    public int maxSubarraySumCircular(int[] nums) {\n        int ans = kadane(nums);\n        int sum = 0;\n        for (int i = 0; i < nums.length; i++) {\n            sum += nums[i];\n            nums[i] = -nums[i];\n        }\n        int kadane_sum = kadane(nums) + sum;\n        if (kadane_sum == 0) {\n            return ans;\n        }\n        return Math.max(ans, kadane_sum);\n    }\n    public int kadane(int[] nums) {\n        int sum = 0;\n        int ans = Integer.MIN_VALUE;\n        for (int i : nums) {\n            sum += i;\n            ans = Math.max(ans, sum);\n            if (sum < 0) {\n                sum = 0;\n            }\n        }\n        return ans;\n    }\n}",648        "solution_c": "class Solution {\npublic:\n    int maxSubarraySumCircular(vector<int>& nums) {\n        int n=nums.size();\n    int currsummin=nums[0],ansmin=nums[0],currsummax=nums[0],ansmax=nums[0],sum=nums[0];\n        for(int i=1;i<n;i++)\n        {\n            sum+=nums[i];\n            \n            currsummin=min(nums[i],currsummin+nums[i]);\n            ansmin=min(ansmin,currsummin);\n            \n            currsummax=max(currsummax+nums[i],nums[i]);\n            ansmax=max(ansmax,currsummax);\n        }\n        return ansmax>0 ? max(ansmax,sum-ansmin) : ansmax;\n    }\n};"649    },650    {651        "title": "Number of Digit One",652        "algo_input": "Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.\n\n&nbsp;\nExample 1:\n\nInput: n = 13\nOutput: 6\n\n\nExample 2:\n\nInput: n = 0\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 109\n\n",653        "solution_py": "class Solution:\n    def countDigitOne(self, n: int) -> int:\n        num = str(n)[::-1]\n        count = 0\n        for i in range(len(num)-1, -1, -1):\n            pv = 10**i # placevalue\n            # mulitplicity of current digit (how many times it will be repeated)\n            mul = n//(pv*10)\n            rem = n % pv # remainder of current place value\n            count += mul * pv # count for number of times 1 occurs in this place when the current digit is considered to be less than 1\n            # if the current digit is greater than 1 then additional number of 1's are added to the count (equivalent to the place value)\n            if num[i] > '1':\n                count += pv\n            # if the current digit is equal to 1 then additional number of 1's are added to the count (equivalent to the number modded by the current place value)\n            if num[i] == '1':\n                count += rem + 1\n        return count",654        "solution_js": "var countDigitOne = function(n) {\n    if(n <= 0) return 0;\n    if(n < 10) return 1;\n    var base = Math.pow(10, n.toString().length - 1);\n    var answer = parseInt(n / base);\n    return countDigitOne(base - 1) * answer + (answer === 1 ? (n - base + 1) : base) + countDigitOne(n % base);\n};",655        "solution_java": "  class Solution {\n\tint max(int a, int b){\n\t\tif(a>b)\n\t\t\treturn a;\n\t\telse\n\t\t\treturn b;\n\t}\n\n\tint min(int a, int b){\n\t\tif(a>b)\n\t\t\treturn b;\n\t\telse\n\t\t\treturn a;\n\t}\n\n\tpublic int countDigitOne(int n) {\n\t\tint c = 0;\n\t\tfor(int i=1; i<=n; i*=10){\n\t\t\tint divider = i*10;\n\t\t\tc += (n/divider)*i + min(max((n%divider -i + 1), 0),i);\n\t\t}\n\t\treturn c;\n\t}\n}\n\n// T.C.  - O(log n)",656        "solution_c": "class Solution {\npublic:\n\tint countDigitOne(int n) {\n\t\tint c = 0;\n\t\tfor(int i=1; i<=n; i++){\n\t\t\tstring s = to_string(i);\n\t\t\tc += count(s.begin(), s.end(), '1');\n\t\t}\n\t\treturn c;\n\t}\n};\n\n// T.C. --> O(n * log(n))\n// S.C. --> O(log(n))"657    },658    {659        "title": "Fibonacci Number",660        "algo_input": "The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,\n\nF(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n &gt; 1.\n\n\nGiven n, calculate F(n).\n\n&nbsp;\nExample 1:\n\nInput: n = 2\nOutput: 1\nExplanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n\n\nExample 2:\n\nInput: n = 3\nOutput: 2\nExplanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n\n\nExample 3:\n\nInput: n = 4\nOutput: 3\nExplanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 30\n\n",661        "solution_py": "class Solution:\n    def fib(self, n: int) -> int:\n        fa = [0, 1]\n\n        for i in range(2, n + 1):\n            fa.append(fa[i-2] + fa[i-1])\n\n        return fa[n]",662        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\n // Recursion and memomization approach\nvar fib = function(n,cache ={}) {\n    if (n <= 0) return 0\n    if(n in cache) {\n        return cache[n]\n    }\n    if(n == 1 || n == 2) {\n        return 1;\n    }\n    cache[n] = fib(n-1,cache) + fib(n-2,cache)\n    return cache[n]\n};\n//Tabulation approach\nvar fib = function(n) {\n    const table = new Array(n + 1).fill(0);\n    table[1] = 1;\n    for(let i = 0;i<=n;i++) {\n            table[i+1] += table[i];\n            table[i+2] += table[i];\n    }\n    return table[n]\n};",663        "solution_java": "class Solution {\n    public int fib(int n) {\n\n        int[] fiboArray = new int[n+2];\n\n        fiboArray[0] = 0;\n        fiboArray[1] = 1;\n\n        for(int i=2; i<=n; i++) {\n            fiboArray[i] = fiboArray[i-1] + fiboArray[i-2];\n        }\n\n        return fiboArray[n];\n\n    }\n}",664        "solution_c": "class Solution {\npublic:\n    int fib(int n) {\n        if(n<=1) return n;\n        return fib(n-1)+fib(n-2);\n    }\n};"665    },666    {667        "title": "Longest Path With Different Adjacent Characters",668        "algo_input": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.\n\nYou are also given a string s of length n, where s[i] is the character assigned to node i.\n\nReturn the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.\n\n&nbsp;\nExample 1:\n\nInput: parent = [-1,0,0,1,1,2], s = \"abacbe\"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -&gt; 1 -&gt; 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions. \n\n\nExample 2:\n\nInput: parent = [-1,0,0,0], s = \"aabc\"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters is the path: 2 -&gt; 0 -&gt; 3. The length of this path is 3, so 3 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == parent.length == s.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= parent[i] &lt;= n - 1 for all i &gt;= 1\n\tparent[0] == -1\n\tparent represents a valid tree.\n\ts consists of only lowercase English letters.\n\n",669        "solution_py": "class Solution:\n    def longestPath(self, parent: list[int], s: str) -> int:\n        def l_path_and_chain(tree: dict[int, list[int]], s: str, root: int) -> tuple[int, int]:\n            lp = lc1 = lc2 = 0\n            for child, path, chain in ((c, *l_path_and_chain(tree, s, c)) for c in tree[root]):\n                lp = max(lp, path)\n                if s[child] != s[root]: *_, lc2, lc1 = sorted((chain, lc2, lc1))\n\n            return max(lp, lc1 + lc2 + 1), lc1 + 1\n\n        t = defaultdict(list)\n        for c, p in enumerate(parent): t[p].append(c)\n        return l_path_and_chain(t, s, 0)[0]",670        "solution_js": "var longestPath = function(parent, s) {\n  const adjList = parent.reduce((adjList, parent, node) => {\n    if (parent < 0) return adjList;\n    adjList[parent].push(node);\n    return adjList;\n  }, new Array(parent.length).fill(0).map(() => []));\n  \n  let longest = 1;\n  \n  const getLongest = (node) => {\n    let maxChild1 = 0;\n    let maxChild2 = 0;\n    \n    adjList[node].forEach((child) => {\n      const childLength = getLongest(child);\n    \n\t  // child letter matches our node, so we can't use it\n      if (s[child] === s[node]) return;\n      \n\t  // compare and update the longest two child paths\n      if (childLength > maxChild1) {\n        maxChild2 = maxChild1;\n        maxChild1 = childLength;\n      } else if (childLength > maxChild2) {\n        maxChild2 = childLength;\n      }\n    });\n    \n\t// longest loop\n    longest = Math.max(longest, maxChild1 + maxChild2 + 1);\n    \n\t// return longest path up the tree\n    return 1 + maxChild1;\n  }\n  \n  getLongest(0);\n  \n  return longest;\n};",671        "solution_java": "class Solution {\n    int longestPathValue = 1; // variable to store the length of the longest path\n\n    public int longestPath(int[] parent, String s) {\n        // create an adjacency list representation of the tree\n        Map<Integer, List<Integer>> adj = new HashMap<>();\n        for(int i = 1; i < parent.length; i++){\n            int j = parent[i];\n            adj.putIfAbsent(j, new LinkedList<>());\n            adj.get(j).add(i);\n        }\n        // call dfs on the root of the tree\n        dfs(0, adj, s);\n        return longestPathValue;\n    }\n\n    public int dfs(int node, Map<Integer, List<Integer>> adj, String s){\n        // if the node is a leaf node, return 1\n        if(!adj.containsKey(node)) return 1;\n        int max = 0, secondMax = 0;\n        // for each neighbor of the node\n        for(int nbrNode : adj.get(node)){\n            int longestPathFromNbrNode = dfs(nbrNode , adj, s);\n            // if the characters at the current node and its neighbor are the same, ignore the neighbor\n            if(s.charAt(node) == s.charAt(nbrNode)) continue;\n            // update max and secondMax with the longest path from the neighbor node\n            if(longestPathFromNbrNode > max){\n                secondMax = max;\n                max = longestPathFromNbrNode;\n            }else if(longestPathFromNbrNode > secondMax){\n                secondMax = longestPathFromNbrNode;\n            }\n        }\n        // update longestPathValue with the longest path that includes the current node\n        longestPathValue = Math.max(longestPathValue, max+secondMax+1);\n        return max+1;\n    }\n}",672        "solution_c": "class Solution {\npublic:\n    vector<vector<int>>g;\n    int ans=0;\n   int dfs(int node,int par, string &s){\n       // vector to store max length & second max length that we get from children of node at v[1] & v[0] respectively\n        vector<int>v(2,0);\n       for(auto child:g[node]){\n           if(child != par){\n               int x = dfs(child,node,s);\n\t\t\t   // if char at node != char at child then node can be included in our ans\n               if(s[node] != s[child]){\n                   if(v[1]<x){\n                       v[0]=v[1];\n                       v[1]=x;\n                       \n                   }else{\n                       v[0]=max(v[0],x);\n                   }\n               }\n               \n           }\n       }\n       // update our ans every time we return to node\n       ans = max(ans, v[0]+v[1]+1);\n\t   //return the max length up till here including node\n       return max(v[0],v[1])+1;\n        \n    }\n    int longestPath(vector<int>& parent, string s) {\n        int n = s.size();\n        \n        ans =0;\n        g.assign(n+1,{});\n        for(int i=1;i<parent.size();i++){\n           g[parent[i]].push_back(i);\n           g[i].push_back(parent[i]);\n        }\n\t\t// run dfs and calculate max \n        ans = max(ans, dfs(0,-1,s));\n        return ans;\n        \n    }\n};"673    },674    {675        "title": "Remove All Occurrences of a Substring",676        "algo_input": "Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:\n\n\n\tFind the leftmost occurrence of the substring part and remove it from s.\n\n\nReturn s after removing all occurrences of part.\n\nA substring is a contiguous sequence of characters in a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"daabcbaabcbc\", part = \"abc\"\nOutput: \"dab\"\nExplanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".\n\n\nExample 2:\n\nInput: s = \"axxxxyyyyb\", part = \"xy\"\nOutput: \"ab\"\nExplanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\t1 &lt;= part.length &lt;= 1000\n\ts​​​​​​ and part consists of lowercase English letters.\n\n",677        "solution_py": "class Solution:\n    def removeOccurrences(self, s: str, part: str) -> str:\n        n=len(part)\n        while part in s:\n            i=s.index(part)\n            s=s[:i]+s[i+n:]\n        return s",678        "solution_js": "var removeOccurrences = function(s, part) {\n    let n =part.length\n    const reduceString = (s)=>{\n        let searchPart =s.indexOf(part)\n        if (searchPart<0)\n            return s\n        s= s.split('')\n        s.splice(searchPart, n)\n        s=s.join('')\n        return reduceString(s)\n\n    }\n    return reduceString(s)\n};",679        "solution_java": "class Solution {\n    public String removeOccurrences(String s, String part) {\n        // s.replace(part,\"\");\n        // System.out.println(s);\n        \n        while(s.contains(part))\n        {\n            s=s.replaceFirst(part,\"\");\n        }\n        return s;\n    }\n}",680        "solution_c": "class Solution {\npublic:\n    bool check(stack<char> st, string part){\n        int n2 = part.length();\n        int j = n2-1;\n        while( j >=0 and st.top() == part[j]){\n            st.pop();\n            j--;\n        }\n        return (j == -1);\n    }\n    string removeOccurrences(string s, string part) {\n        int n1 = s.length() , n2 = part.length();\n        stack<char>st;\n        string str = \"\" ;\n        for(int i=0;i<n1;++i){\n            st.push(s[i]);\n            if(st.size() >= n2){\n                if(check(st,part)){\n                    int ct = n2;\n                    while(ct--){\n                        st.pop();\n                    }\n                }\n            }\n        }\n        string res = \"\";\n        while(!st.empty()){\n            res += st.top();\n            st.pop();\n        }\n        reverse(res.begin(),res.end());\n        return res;\n    }\n};"681    },682    {683        "title": "Sum of Even Numbers After Queries",684        "algo_input": "You are given an integer array nums and an array queries where queries[i] = [vali, indexi].\n\nFor each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.\n\nReturn an integer array answer where answer[i] is the answer to the ith query.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput: [8,6,2,4]\nExplanation: At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n\n\nExample 2:\n\nInput: nums = [1], queries = [[4,0]]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 104\n\t-104 &lt;= nums[i] &lt;= 104\n\t1 &lt;= queries.length &lt;= 104\n\t-104 &lt;= vali &lt;= 104\n\t0 &lt;= indexi &lt; nums.length\n\n",685        "solution_py": "class Solution:\n# O(n) || O(1)\n    def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n        totalEvenNumSum = sum([num for num in nums if num % 2 == 0])\n        result = []\n\n        for val, idx in queries:\n            oldVal = nums[idx]\n            nums[idx] += val\n\n            if oldVal % 2 == 0:\n                totalEvenNumSum -= oldVal\n\n            if nums[idx] % 2 == 0:\n                totalEvenNumSum += nums[idx]\n\n            result.append(totalEvenNumSum)\n\n        return result",686        "solution_js": "/**\n * @param {number[]} nums\n * @param {number[][]} queries\n * @return {number[]}\n */\nvar sumEvenAfterQueries = function(nums, queries) {\n    let sumEven = 0, ans = []\n    for (let i = 0; i < nums.length; i++) {\n        if (nums[i] % 2 == 0) sumEven += nums[i]\n    }\n\n    for (let [val, idx] of queries) {\n        if (nums[idx] % 2 == 0) {\n            if (val % 2 == 0) sumEven += val\n            else sumEven -= nums[idx]\n        } else {\n            // odd + odd\n            if (val % 2 !== 0) sumEven += nums[idx] + val\n        }\n        nums[idx] += val\n        ans.push(sumEven)\n    }\n\n    return ans\n};",687        "solution_java": "class Solution {\n    public int[] sumEvenAfterQueries(int[] nums, int[][] queries) {\n        int sum = 0;\n        for (int i : nums) {\n            if ((i & 1) == 0) { // (i % 2 == 0)\n                sum += i;\n            }\n        }\n        int[] ans = new int[nums.length];\n        int k = 0;\n        for (int[] q : queries) {\n            int idx = q[1];\n            if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n                sum -= nums[idx];\n            }\n            nums[idx] += q[0];\n            if ((nums[idx] & 1) == 0) { // (nums[idx] % 2 == 0)\n                sum += nums[idx];\n            }\n            ans[k++] = sum;\n        }\n        return ans;\n    }\n}",688        "solution_c": "class Solution {\npublic:\n    vector<int> sumEvenAfterQueries(vector<int>& nums, vector<vector<int>>& queries) {\n    //Sum of all even numbers in the array intially\n        int tes=accumulate(nums.begin(),nums.end(),0,[](int curr,int a) {if(a%2==0) return curr+=a;\n                else return curr;});\n        vector<int> ans(queries.size());\n        bool a=false,b=false;\n        for(int i=0;i<queries.size();i++)\n        {\n            //If both are even or odd it stays even then\n            a=nums[queries[i][1]]%2==0 && queries[i][0]%2==0;\n            b=abs(nums[queries[i][1]]%2)==1 && abs(queries[i][0]%2)==1;\n            if(a)\n                tes+=queries[i][0];\n            else if(b)\n                tes+=queries[i][0]+nums[queries[i][1]];\n            else if(nums[queries[i][1]]%2==0)\n                tes-=nums[queries[i][1]]; //If even turns to odd because of operation remove that even value from ans\n            ans[i]=tes; //Adding the result\n            nums[queries[i][1]]+=queries[i][0]; //now completing the operation in queries to use in further operations\n        }\n        return ans;\n    }\n};"689    },690    {691        "title": "Dice Roll Simulation",692        "algo_input": "A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.\n\nGiven an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.\n\nTwo sequences are considered different if at least one element differs from each other.\n\n&nbsp;\nExample 1:\n\nInput: n = 2, rollMax = [1,1,2,2,2,3]\nOutput: 34\nExplanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n\n\nExample 2:\n\nInput: n = 2, rollMax = [1,1,1,1,1,1]\nOutput: 30\n\n\nExample 3:\n\nInput: n = 3, rollMax = [1,1,1,2,2,3]\nOutput: 181\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 5000\n\trollMax.length == 6\n\t1 &lt;= rollMax[i] &lt;= 15\n\n",693        "solution_py": "class Solution:\n    def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n        dp = {}\n        def solve(n,last,count):\n            if n == 0: return 1\n            if (n,last,count) in dp: return dp[(n,last,count)]\n            ans = 0\n            for i in range(6):\n                if last == i:\n                    if count == rollMax[i]: continue\n                    ans += solve(n-1,last,count + 1)\n                else:\n                    ans += solve(n-1,i,1)\n            dp[(n,last,count)] = ans\n            return ans\n        \n        return solve(n,None,0) % 1000000007",694        "solution_js": "/** https://leetcode.com/problems/dice-roll-simulation/\n * @param {number} n\n * @param {number[]} rollMax\n * @return {number}\n */\nvar dieSimulator = function(n, rollMax) {\n  // Memo\n  this.memo = new Map();\n  \n  // Modulo\n  this.mod = (10 ** 9) + 7;\n  \n  // Keep track of roll count for each die's face (1-6)\n  let currRoll = Array(6).fill(0);\n  return dp(n, rollMax, n, currRoll) % this.mod;\n};\n\nvar dp = function(n, rollMax, nRemain, currRoll, previous = null) {\n  let key = `${nRemain}_${currRoll.toString()}`;\n  \n  // Base case\n  if (nRemain === 0) {\n    return 1;\n  }\n  \n  // Return from memo\n  if (this.memo.has(key) === true) {\n    return this.memo.get(key);\n  }\n  \n  let count = 0;\n  \n  // Try every face of the die, the face is the number on the die\n  // The face index in array is represented by `i`\n  // The face on the die (the number) is represented by `i + 1`\n  for (let i = 0; i < 6; i++) {\n    // Clone object we use for tracking the roll count for each die, by cloning we don't the next recursive won't change the value of current object\n    let cloneRoll = [...currRoll];\n    \n    // Increment the count of current face\n    cloneRoll[i] += 1;\n    \n    // This face of the die hit limit, ignore it\n    if (cloneRoll[i] > rollMax[i]) {\n      continue;\n    }\n    \n    // This face of the die is different that previous one, since the limit is only for consecutive count, it means the previous face's count should be reset\n    if (previous != null && i + 1 != previous) {\n      cloneRoll[previous - 1] = 0;\n    }\n    \n    // Count next recursive\n    count += dp(n, rollMax, nRemain - 1, cloneRoll, i + 1) % this.mod;\n  }\n\n  // Set memo\n  this.memo.set(key, count);\n  \n  return count;\n};",695        "solution_java": "class Solution {\n    long[][][] dp;\n    int mod = 1_000_000_007;\n    public int dieSimulator(int n, int[] rollMax) {\n        dp = new long[n + 1][7][16];\n        for(long[][] row: dp)\n            for(long[] col: row)\n                Arrays.fill(col, -1);\n\n        return (int)helper(n, 0, 0, rollMax, 0);\n    }\n\n    private long helper(int n, int dice, int prev, int[] rollMax, int runs)\n    {\n        if(n == dice)\n            return 1;\n\n        if(dp[dice][prev][runs] != -1)\n            return dp[dice][prev][runs];\n\n        long ans = 0;\n        int[] temp = rollMax;\n        for(int i = 1; i <= 6; i++)\n        {\n            if(prev != 0 && i == prev && rollMax[i-1] <= runs)\n                continue;\n            if(i == prev)\n                ans = (ans + helper(n, dice + 1, i, rollMax, runs + 1)) % mod;\n            else\n                ans = (ans + helper(n, dice + 1, i, rollMax, 1)) % mod;\n        }\n\n        dp[dice][prev][runs] = ans;\n        return ans;\n    }\n}",696        "solution_c": "class Solution {\npublic:\n\n    int fun( int i , int k , int p , vector<int>& rollMax ,vector< vector< vector<int> > > &dp){\n        if(i==0) return 1;\n        if(dp[i][k][p]!=-1){\n            return dp[i][k][p] ;\n        }\n         long long int ans=0 ;\n        for(int j=1 ; j<7 ; j++){\n            if(j==k){\n            if(p<rollMax[j-1]) ans=(ans+fun(i-1,j,p+1,rollMax,dp))%1000000007 ;\n            }\n\n            else ans=(ans+fun(i-1,j,1,rollMax,dp))%1000000007 ;\n        }\n        return dp[i][k][p]=ans ;\n    }\n\n    int dieSimulator(int n, vector<int>& rollMax) {\n       vector< vector< vector<int> > > dp(n+1, vector< vector<int> >(7 , vector<int>(16,-1)));\n        int ans=fun(n,0,1,rollMax,dp) ;\n        return ans ;\n    }\n};"697    },698    {699        "title": "Nim Game",700        "algo_input": "You are playing the following Nim Game with your friend:\n\n\n\tInitially, there is a heap of stones on the table.\n\tYou and your friend will alternate taking turns, and you go first.\n\tOn each turn, the person whose turn it is will remove 1 to 3 stones from the heap.\n\tThe one who removes the last stone is the winner.\n\n\nGiven n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.\n\n&nbsp;\nExample 1:\n\nInput: n = 4\nOutput: false\nExplanation: These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.\n\n\nExample 2:\n\nInput: n = 1\nOutput: true\n\n\nExample 3:\n\nInput: n = 2\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",701        "solution_py": "class Solution:\n    def canWinNim(self, n: int) -> bool:\n        return n%4",702        "solution_js": "var canWinNim = function(n) {\n    if(n%4==0) return false;\n    else return true;\n};",703        "solution_java": "class Solution {\n    public boolean canWinNim(int n) {\n        if(n%4==0) return false;\n\n        return true;\n    }\n}",704        "solution_c": "Time: O(n)  Space: O(n)\n--> TLE\nclass Solution {\npublic:\n    bool canWinNim(int n) {\n        if(n<4)\n            return true;\n        vector<bool> dp(n+1);\n        dp[1]=true,dp[2]=true,dp[3]=true,dp[4]=false;\n        for(int i=5;i<n+1;i++){\n            if(dp[i-1]==false or dp[i-2]==false or dp[i-3]==false)\n                dp[i]=true;\n        }\n        return dp[n];\n    }\n};\n\n\nTime: O(1)  Space: O(1)\n\nclass Solution {\npublic:\n    bool canWinNim(int n) {\n        if(n%4==0)\n            return false;\n        return true;\n    }\n};"705    },706    {707        "title": "Product of the Last K Numbers",708        "algo_input": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.\n\nImplement the ProductOfNumbers class:\n\n\n\tProductOfNumbers() Initializes the object with an empty stream.\n\tvoid add(int num) Appends the integer num to the stream.\n\tint getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.\n\n\nThe test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.\n\n&nbsp;\nExample:\n\nInput\n[\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]\n\nOutput\n[null,null,null,null,null,null,20,40,0,null,32]\n\nExplanation\nProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3);        // [3]\nproductOfNumbers.add(0);        // [3,0]\nproductOfNumbers.add(2);        // [3,0,2]\nproductOfNumbers.add(5);        // [3,0,2,5]\nproductOfNumbers.add(4);        // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8);        // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 \n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 100\n\t1 &lt;= k &lt;= 4 * 104\n\tAt most 4 * 104 calls will be made to add and getProduct.\n\tThe product of the stream at any point in time will fit in a 32-bit integer.\n\n",709        "solution_py": "class ProductOfNumbers:\n    def __init__(self):\n        self.prods = [1]\n        self.max = 0\n\n    def add(self, num: int) -> None:\n        if num == 0:\n            num = 1\n            self.max = len(self.prods)\n        self.prods.append(self.prods[-1] * num)\n\n    def getProduct(self, k: int) -> int:\n        if k >= len(self.prods) - self.max:\n            return 0\n        return self.prods[-1] // self.prods[-k-1]",710        "solution_js": "var ProductOfNumbers = function() {\n    this.nums = [];\n    this.len = 0;\n};\n\n/** \n * @param {number} num\n * @return {void}\n */\nProductOfNumbers.prototype.add = function(num) {\n    this.nums.push(num);\n    this.len++;\n};\n\n/** \n * @param {number} k\n * @return {number}\n */\nProductOfNumbers.prototype.getProduct = function(k) {\n    let product = 1;\n    for (let i = 1; i <= k; i++)\n        product *= this.nums[this.len - i];\n    return product;\n};\n\n/** \n * Your ProductOfNumbers object will be instantiated and called as such:\n * var obj = new ProductOfNumbers()\n * obj.add(num)\n * var param_2 = obj.getProduct(k)\n */",711        "solution_java": "class ProductOfNumbers {\n    List<Integer> prefix;\n    public ProductOfNumbers() {\n        prefix = new ArrayList<>();\n        prefix.add(1);\n    }\n    \n    public void add(int num) {\n        if(num==0){\n            prefix.clear();\n            prefix.add(1);\n        }\n        else prefix.add(num*prefix.get(prefix.size()-1));\n    }\n    public int getProduct(int k) {\n        if(k>=prefix.size()) return 0;\n        return prefix.get(prefix.size()-1)/prefix.get(prefix.size()-k-1);\n    }\n}",712        "solution_c": "class ProductOfNumbers {\nprivate:\n    vector<int> prefixProduct;\npublic:\n    ProductOfNumbers() {\n\n    }\n\n    void add(int num) {\n        if(num == 0){\n            prefixProduct.clear();\n            return;\n        }\n        if(prefixProduct.empty()){\n            prefixProduct.push_back(num);\n        }else{\n            int prod = prefixProduct[prefixProduct.size() - 1] * num;\n            prefixProduct.push_back(prod);\n        }\n\n    }\n    int getProduct(int k) {\n        if(k > prefixProduct.size()){\n            return 0;\n        }\n        int size = prefixProduct.size();\n        if(k == size) return prefixProduct[size - 1];\n        int prod = prefixProduct[size - 1] / prefixProduct[size - k - 1];\n        return prod;\n\n    }\n};"713    },714    {715        "title": "Different Ways to Add Parentheses",716        "algo_input": "Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.\n\nThe test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.\n\n&nbsp;\nExample 1:\n\nInput: expression = \"2-1-1\"\nOutput: [0,2]\nExplanation:\n((2-1)-1) = 0 \n(2-(1-1)) = 2\n\n\nExample 2:\n\nInput: expression = \"2*3-4*5\"\nOutput: [-34,-14,-10,-10,10]\nExplanation:\n(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= expression.length &lt;= 20\n\texpression consists of digits and the operator '+', '-', and '*'.\n\tAll the integer values in the input expression are in the range [0, 99].\n\n",717        "solution_py": "class Solution(object):\n    def diffWaysToCompute(self, input):\n        m = {}\n        return self.dfs(input, m)\n        \n    def dfs(self, input, m):\n        if input in m:\n            return m[input]\n        if input.isdigit():\n            m[input] = int(input)\n            return [int(input)]\n        ret = []\n        for i, c in enumerate(input):\n            if c in \"+-*\":\n                l = self.diffWaysToCompute(input[:i])\n                r = self.diffWaysToCompute(input[i+1:])\n                ret.extend(eval(str(x)+c+str(y)) for x in l for y in r)\n        m[input] = ret\n        return ret",718        "solution_js": "var diffWaysToCompute = function(expression) {\n//     We can iterate through the expression character-by-character.\n// we can break the expression into two halves whenever we get an operator (+, -, *).\n// The two parts can be calculated by recursively calling the function.\n// Once we have the evaluation results from the left and right halves, we can combine them to produce all results.\n    \n    return diffWaysRec({},expression)\n    \n};\n\nfunction diffWaysRec(map, expression){\n    if(expression in map){\n        return map[expression]\n    }\n    let result = [];\n    \n    \n    if(!(expression.includes(\"+\")) && !(expression.includes(\"-\")) && !(expression.includes(\"*\"))){\n        result.push(parseInt(expression))\n    }else {\n        \n        for(let i =0; i<expression.length; i++){\n            let char = expression[i];\n            \n            if(isNaN(parseInt(char,10))){\n                //not a number , must it expression\n                //calculate lest and right now\n                let leftParts = diffWaysRec(map,expression.substring(0,i));\n                let rightParts = diffWaysRec(map, expression.substring(i+1));\n                for(let l = 0; l<leftParts.length; l++){\n                    for(let r = 0; r<rightParts.length; r++){\n                        let left = leftParts[l];\n                        let right = rightParts[r];\n                        \n                        if(char === \"+\"){\n                            result.push(parseInt(left) + parseInt(right))\n                        }\n                        if(char === \"-\"){\n                            result.push(parseInt(left) - parseInt(right))\n                        }\n                        if(char === \"*\"){\n                            result.push(parseInt(left) * parseInt(right))\n                        }\n                    }\n                }\n                \n            }\n        }\n    }\n    \n    map[expression] = result;\n    return result;\n    \n}",719        "solution_java": "class Solution {\n    Map<String, List<Integer>> memo = new HashMap<>();\n    public List<Integer> diffWaysToCompute(String expression) {\n        List<Integer> res = new LinkedList<>();\n        if(memo.containsKey(expression)) return memo.get(expression);\n\n        for(int i = 0; i<expression.length(); i++){\n            char c = expression.charAt(i);\n            if(c == '*' || c == '+' || c == '-'){\n                //divide\n                List<Integer> left = diffWaysToCompute(expression.substring(0, i));\n                List<Integer> right = diffWaysToCompute(expression.substring(i+1));\n\n                //conquer\n                for(int a : left){\n                    for(int b : right){\n                        if(c == '+'){\n                            res.add(a+b);\n                        }else if(c == '-'){\n                            res.add(a - b);\n                        }else if(c == '*'){\n                            res.add(a * b);\n                        }\n                    }\n                }\n                \n            }\n        }\n        //base case, when there is no operator\n        if(res.isEmpty()){\n            res.add(Integer.parseInt(expression));\n        }\n        memo.put(expression, res);\n        return res;     \n    }\n}",720        "solution_c": "class Solution {\npublic:\n    \n    int stoi1(string &s, int i, int j)\n    {\n        int num = 0;\n        for (int k = i; k <= j; k++)\n        {\n            num = num * 10 + (s[k] - '0');\n        }\n        return num;\n    }\n\n    vector<int> rec(string &s, int i, int j, vector<vector<vector<int>>> &dp)\n    {\n        if(dp[i][j].size() > 0){\n            return dp[i][j];\n        }\n        vector<int> ans;\n        for (int k = i; k <= j; k++)\n        {\n            if(s[k] == '+' || s[k] == '*' || s[k] == '-'){\n                vector<int> v1 = rec(s, i, k - 1, dp);\n                vector<int> v2 = rec(s, k + 1, j, dp);\n                for (int m = 0; m < v1.size(); m++)\n                {\n                    for (int n = 0; n < v2.size(); n++)\n                    {\n                        if (s[k] == '-')\n                        {\n                            ans.push_back(v1[m] - v2[n]);\n                        }\n                        else if (s[k] == '*')\n                        {\n                            ans.push_back(v1[m] * v2[n]);\n                        }\n                        else\n                        {\n                            ans.push_back(v1[m] + v2[n]);\n                        }\n                    }\n                }\n            }\n        }\n        if(ans.empty()){\n            ans.push_back(stoi1(s,i,j));\n        }\n        return dp[i][j] = ans;\n    }\n    \n    vector<int> diffWaysToCompute(string expression) {\n        int n = expression.length() + 1;\n        vector<vector<vector<int>>> dp(n, vector<vector<int>>(n, vector<int>()));\n        return rec(expression, 0, expression.length()-1, dp);\n    }\n};"721    },722    {723        "title": "Groups of Special-Equivalent Strings",724        "algo_input": "You are given an array of strings of the same length words.\n\nIn one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].\n\nTwo strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].\n\n\n\tFor example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -&gt; \"xzzy\" -&gt; \"xyzz\".\n\n\nA group of special-equivalent strings from words is a non-empty subset of words such that:\n\n\n\tEvery pair of strings in the group are special equivalent, and\n\tThe group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group).\n\n\nReturn the number of groups of special-equivalent strings from words.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\nOutput: 3\nExplanation: \nOne group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".\n\n\nExample 2:\n\nInput: words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 1000\n\t1 &lt;= words[i].length &lt;= 20\n\twords[i] consist of lowercase English letters.\n\tAll the strings are of the same length.\n\n",725        "solution_py": "class Solution:\n    def numSpecialEquivGroups(self, words) -> int:\n        return len(set([(''.join(sorted(i[::2])),''.join(sorted(i[1::2]))) for i in words]))",726        "solution_js": "var numSpecialEquivGroups = function(words) {\n    const set = new Set()\n    const a = 'a'.charCodeAt(0)\n    const alphaCounter = new Array(26).fill(0)\n    for (const word of words) {\n        const [even, odd] = [[...alphaCounter], [...alphaCounter]]\n        word.split('').forEach((l,i) => {\n            l = l.charCodeAt(0) - a\n            if (i%2) odd[l]++\n            else even[l]++\n        })\n        const hashkey = even.join('') + odd.join('')\n        set.add(hashkey)\n    }\n    return set.size\n};",727        "solution_java": "class Solution {\n    public int numSpecialEquivGroups(String[] words) {\n        if(words.length == 0 || words.length == 1) return words.length;\n\n        // To store group sizes\n        HashMap<String, Integer> hashmap = new HashMap<>();\n\n        // To mark the strings already part of some groups\n        boolean[] isGrouped = new boolean[words.length];\n\n        for(int index = 0; index < words.length; index++) {\n            if(isGrouped[index]) continue; // Already grouped\n            String word = words[index];\n            for(int j = index + 1; j < words.length; j++) {\n                if(isGrouped[j]) continue; // Already grouped\n                String string = words[j];\n\n                // The idea is to store count of characters on even and odd indices\n                // It is done by incrementing counts of characters in both even and odd maps respectively\n                // Then compare the two strings by reducing the same count in both even and odd maps\n                // If both the maps are empty at last, the two strings for a group\n                HashMap<Character, Integer> evens = new HashMap<>();\n                HashMap<Character, Integer> odds = new HashMap<>();\n                boolean isSpecialEquivalent = true;\n\n                for(int i = 0; i < word.length(); i++) {\n                    if(i % 2 == 0) {\n                        evens.put(word.charAt(i), evens.getOrDefault(word.charAt(i), 0) + 1);\n                    } else {\n                        odds.put(word.charAt(i), odds.getOrDefault(word.charAt(i), 0) + 1);\n                    }\n                }\n\n                for(int i = 0; i < string.length(); i++) {\n                    char character = string.charAt(i);\n                    if(i % 2 == 0) {\n                        if(!evens.containsKey(character)) {\n                            isSpecialEquivalent = false;\n                            break;\n                        }\n\n                        evens.put(character, evens.get(character) - 1);\n                        if(evens.get(character) == 0) evens.remove(character);\n                    } else {\n                        if(!odds.containsKey(character)) {\n                            isSpecialEquivalent = false;\n                            break;\n                        }\n\n                        odds.put(character, odds.get(character) - 1);\n                        if(odds.get(character) == 0) odds.remove(character);\n                    }\n                }\n\n                if(isSpecialEquivalent) {\n                    hashmap.put(word, hashmap.getOrDefault(word, 0) + 1);\n                    isGrouped[j] = true;\n                }\n            }\n\n            // If no group is formed, the word alone forms a group of size 1\n            if(!hashmap.containsKey(word)) hashmap.put(word, 1);\n        }\n\n        return hashmap.size();\n    }\n}",728        "solution_c": "class Solution {\npublic:\n    int numSpecialEquivGroups(vector<string>& words) {\n        int n = words.size();\n        vector<pair<string, string>>v;\n        for(auto it:words) {\n            string even = \"\";\n            string odd = \"\";\n            for(int i = 0;i<it.size();i+=2) even+=it[i];\n            for(int i = 1;i<it.size();i+=2) odd+=it[i];\n            sort(even.begin(), even.end());\n            sort(odd.begin(), odd.end());\n            even+=odd;\n            v.push_back({it, even});\n\n        }\n\n        map<string, int>m;\n        for(auto it:v) {\n            m[it.second]++;\n        }\n\n        return m.size();\n    }\n};"729    },730    {731        "title": "UTF-8 Validation",732        "algo_input": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).\n\nA character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:\n\n\n\tFor a 1-byte character, the first bit is a 0, followed by its Unicode code.\n\tFor an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.\n\n\nThis is how the UTF-8 encoding would work:\n\n     Number of Bytes   |        UTF-8 Octet Sequence\n                       |              (binary)\n   --------------------+-----------------------------------------\n            1          |   0xxxxxxx\n            2          |   110xxxxx 10xxxxxx\n            3          |   1110xxxx 10xxxxxx 10xxxxxx\n            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\n\nx denotes a bit in the binary form of a byte that may be either 0 or 1.\n\nNote: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.\n\n&nbsp;\nExample 1:\n\nInput: data = [197,130,1]\nOutput: true\nExplanation: data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n\n\nExample 2:\n\nInput: data = [235,140,4]\nOutput: false\nExplanation: data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= data.length &lt;= 2 * 104\n\t0 &lt;= data[i] &lt;= 255\n\n",733        "solution_py": "class Solution:\n    def validUtf8(self, data: List[int]) -> bool:\n        # Keep track of how many continuation bytes are left\n\t\t# Start at 0 since we are not expecting any continuation bytes at the beginning.\n        cont_bytes_left = 0\n        for byte in data:\n            if cont_bytes_left == 0:\n\t\t\t    # If we don't expect any continuation bytes\n\t\t\t    # then there are 4 valid case for the current byte\n                # byte >> 5 gives us the first 3 bits (8 bits - 5 = 3).\n                if byte >> 5 == 0b110:\n\t\t\t\t    # After seeing a byte that starts with 110,\n\t\t\t\t\t# we expect to see one continuation byte\n                    cont_bytes_left = 1\n                elif byte >> 4 == 0b1110:\n                    cont_bytes_left = 2\n                elif byte >> 3 == 0b11110:\n                    cont_bytes_left = 3\n                # finally if the first bit isn't 0 then it's invalid\n                elif byte >> 7 != 0:\n                    return False\n            else:\n\t\t\t    # If we are expecting a continuation byte there is only one valid case.\n                # It's invalid if the continuation byte doesn't start with 10\n                if byte >> 6 != 0b10:\n                    return False\n                cont_bytes_left -= 1\n        \n\t\t# Only valid if we aren't expecting any more continuation bytes\n        return cont_bytes_left == 0",734        "solution_js": "var validUtf8 = function(data) {\n  const len = data.length;\n  const byteBits = data.map(a => padLeft(a.toString(2))); //convert to bit strings\n  let bytes,  i = 0;\n  while (i < len) {\n    bytes = 0;\n    //count 1s in the front.\n    while (byteBits[i].charAt(bytes) === \"1\") bytes++;\n\n    //if we have only 1 byte to process expect more than 1 byte, it should fail.\n    if (len === 1 && bytes > 0) return false;\n\n    //UTF8 chars can't be more than 4 bytes.\n    if (bytes > 4) return false;\n\n    //if we're processing more than 1 byte\n    if (bytes > 1) {\n      //decrement for every byte that starts with \"10\"\n      while (i < len - 1 && byteBits[++i].startsWith(\"10\")) bytes--;\n\n      //check to see if we have too many or too little of the expected bytes left\n      if (bytes !== 1) return false;\n    }\n    else i++;\n  }\n  return true;\n};\n\nconst padLeft = (str, size = 8, pad = \"0\") => (\n  str.length >= size ? str : pad.repeat(size).substring(str.length % size) + str\n);",735        "solution_java": "class Solution {\n    public boolean validUtf8(int[] data) {\n        return help(data,0);\n    }\n\n    public boolean help(int[] data,int index) {\n        int n=data.length-index;\n        if(n==0){\n            return true;\n        }\n        int c0=count(data[index]);\n        if(c0<0||c0>n){\n            return false;\n        }\n        for(int i=index+1;i<index+c0;i++){\n            if((data[i]&0b10000000)!=0b10000000){\n                return false;\n            }\n        }\n        return help(data,index+c0);\n    }\n\n    private int count(int a){\n        if((a>>3)==0b11110){\n            return 4;\n        }else if((a>>4)==0b1110){\n            return 3;\n        }else if((a>>5)==0b110){\n            return 2;\n        }else if((a>>7)==0){\n            return 1;\n        }\n        return -1;\n    }\n}",736        "solution_c": "class Solution{\npublic:\n  bool validUtf8(vector<int> &data){\n    int n = data.size(); \n    int count = 0;       \n    for (int i = 0; i < n; i++){    \n      int ele = data[i]; \n      if (!count){ \n\t   // if the first 3 bits are 110, then the next byte is part of the current UTF-8 character\n        if ((ele >> 5) == 0b110) \n          count = 1; \n\t\t// if the first 4 bits are 1110, then the next 2 bytes are part of the current UTF-8 character  \n        else if ((ele >> 4) == 0b1110)\n          count = 2; \n\t\t // if the first 5 bits are 11110, then the next 3 bytes are part of the current UTF-8 character\n        else if ((ele >> 3) == 0b11110)\n          count = 3; \n\t\t // if the first bit is 1, then return false\n        else if ((ele >> 7))\n          return false; \n      }\n      else{\n\t   // if the first 2 bits are not 10, then return false\n        if ((ele >> 6) != 0b10)\n          return false; \n        count--;        \n      }\n    }\n    return (count == 0); \n  }\n};"737    },738    {739        "title": "Count Negative Numbers in a Sorted Matrix",740        "algo_input": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput: 8\nExplanation: There are 8 negatives number in the matrix.\n\n\nExample 2:\n\nInput: grid = [[3,2],[1,0]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 100\n\t-100 &lt;= grid[i][j] &lt;= 100\n\n\n&nbsp;\nFollow up: Could you find an O(n + m) solution?",741        "solution_py": "class Solution:\n    def countNegatives(self, grid: List[List[int]]) -> int:\n        count = 0\n\n        for i in grid:\n            low = 0\n            high = len(i) - 1\n\n            while low <= high:\n                mid = (low+high)//2\n                if i[mid] < 0:\n                    high = mid - 1\n                elif i[mid] >= 0:\n                    low = mid + 1\n            count += (len(i) - low)\n        return count",742        "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar countNegatives = function(grid) {\n  \n    const m = grid.length\n    const n = grid[0].length\n    \n    // for each row we need to find location of first negative\n    // all columns past that are negative\n    // also for next row search stops before\n    // location of current first negative because \n    // all numbers below current are also lesser (negative) \n    \n    function binSearch(start,end, arr){\n        \n        while(start<=end){\n            let mid = start + ((end-start)>>1)\n            if(arr[mid] < 0)\n                end = mid - 1\n            else \n                start = mid + 1\n        }\n        return arr[end]<0 ? end : end + 1\n    }\n    \n    \n    \n    let ans = 0\n    let searchTill = n-1\n    for(let i=0;i<m;i++){\n        \n        if(searchTill<0){ \n            // last row found 0 in first column\n            ans += n\n            continue;\n        }\n        \n        let firstNegative = binSearch(0,searchTill, grid[i])\n        searchTill = firstNegative - 1\n        ans += (n - firstNegative)\n    }\n    return ans\n};",743        "solution_java": "class Solution {\n    public int countNegatives(int[][] grid) {\n        int m = grid.length ;\n        int n = grid[0].length ;\n        int c = 0;\n        int count = 0;\n        int r = m-1;\n        while( r >= 0 && c < n ) {\n            if (grid[r][c] < 0 ) {\n                r--;\n                count += n - c;\n            } else{\n                c++;\n            }\n        }\n        return count;\n    }\n}",744        "solution_c": "class Solution {\npublic:\n    int countNegatives(vector<vector<int>>& grid) {\n        int ans = 0; for (auto hehe : grid) for (int i : hehe) if (i < 0) ans++; return ans;\n    }\n};"745    },746    {747        "title": "Shopping Offers",748        "algo_input": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.\n\nYou are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.\n\nYou are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.\n\nReturn the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.\n\n&nbsp;\nExample 1:\n\nInput: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput: 14\nExplanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\n\n\nExample 2:\n\nInput: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput: 11\nExplanation: The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == price.length == needs.length\n\t1 &lt;= n &lt;= 6\n\t0 &lt;= price[i], needs[i] &lt;= 10\n\t1 &lt;= special.length &lt;= 100\n\tspecial[i].length == n + 1\n\t0 &lt;= special[i][j] &lt;= 50\n\n",749        "solution_py": "class Solution:\n    def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n        def dfs(price, special, needs, memo = {}):\n            if tuple(needs) in memo:\n                return memo[tuple(needs)]\n            res = [sum([p * need for p, need in zip(price, needs)])] # don't use any offer\n            for offer in special:\n                # check if can apply the offer\n                new_needs = []\n                for offer_items, need in zip(offer[:-1], needs):\n                    new_needs.append(need - offer_items)\n                if min(new_needs) < 0:\n                    continue\n                # Check if without the offer is better\n                value = 0\n                for p, offer_items in zip(price, offer[:-1]):\n                    value += p * offer_items\n                if value < offer[-1]:\n                    continue\n                # Valid Case\n                res.append(dfs(price, special, new_needs, memo) + offer[-1])\n            memo[tuple(needs)] = min(res)\n            return min(res)\n        return dfs(price, special, needs)",750        "solution_js": "/** https://leetcode.com/problems/shopping-offers/\n * @param {number[]} price\n * @param {number[][]} special\n * @param {number[]} needs\n * @return {number}\n */\nvar shoppingOffers = function(price, special, needs) {\n  // Memoization\n  this.map = new Map();\n  \n  return shop(price,special,needs);\n};\n\nvar shop = function (price, special, needs) {\n  // Return memoization result\n  if (this.map.has(needs) === true) {\n    return this.map.get(needs);\n  }\n  \n  // Calculate total if purchase without special offers\n  let currTotal = calcTotal(price, needs);\n  \n  // Try every single offers\n  for(let i = 0; i < special.length; i++) {\n    // Check special offer can be used\n    if (canUseSpecial(special[i], needs) === true) {\n      // Clone the `needs` because we don't want to modify the original `needs`, update the `needs` count by calling `useSpecial()`\n      let cloneNeeds = [...needs];\n      cloneNeeds = useSpecial(special[i], cloneNeeds);\n      \n      // Count total if using special offers, basically repeat the same process with updated `needs`\n      let totalUsingSpecial = special[i][needs.length] + shop(price, special, cloneNeeds);\n      \n      // Compare the `currTotal` with total if using special offers\n      currTotal = Math.min(currTotal, totalUsingSpecial);\n    }\n  }\n  \n  // Update memoization and return result\n  this.map.set(needs, currTotal);\n  return currTotal;\n};\n\nvar calcTotal = function (price, needs) {\n  // Calculate total if purchase without special offers, basically `price[i] * needs[i]`\n  let out = 0;\n  \n  for (let i =0 ; i < price.length; i++) {\n    out += price[i] * needs[i];\n  }\n  \n  return out;\n};\n\nvar canUseSpecial = function (special, needs) {\n  // Check if special offers can be used, if any of `special[i]` is more than `needs[i]`, the special can not be used, return false because we can not buy more than needed\n  for (let i = 0; i < needs.length; i++) {\n    if (needs[i] < special[i]) {\n      return false;\n    }\n  }\n  \n  return true;\n};\n\nvar useSpecial = function (special, needs) {\n  // Update the `needs` count by subtracting it from `special`\n  for (let i = 0; i < needs.length; i++) {\n    needs[i] -= special[i];\n  }\n  \n  return needs;\n};",751        "solution_java": "class Solution {\n    public static int fun(int index,List<Integer> price,List<List<Integer>> special, List<Integer> needs){\n        // Base \n        if(index < 0){\n            int addAmount = 0;\n            for(int i=0;i<needs.size();i++){\n                addAmount += (needs.get(i) * price.get(i));\n            }\n            return addAmount;\n        }\n\n        // Not Take Offer\n        int notTakeOffer = 0 + fun(index-1,price,special,new ArrayList<>(needs));\n\n        // Take Offer \n        int takeOffer = 1000000000;\n        if(canTakeOffer(special.get(index),new ArrayList<>(needs))){\n            List<Integer> current_special = special.get(index);\n            for(int i=0;i<current_special.size()-1;i++){\n                int current_need = needs.get(i);\n                int update = current_special.get(i);\n                needs.set(i,current_need-update);\n            }\n            takeOffer = current_special.get(current_special.size()-1) + fun(index,price,special,new ArrayList<>(needs));\n        }\n        return Math.min(notTakeOffer,takeOffer);\n    }\n\n    public static boolean canTakeOffer(List<Integer> current_special, List<Integer> needs){\n        boolean canTake = true;\n        for(int i=0;i<current_special.size()-1;i++){\n            if(needs.get(i) < current_special.get(i)){\n                canTake = false;\n                break;\n            }\n        }\n        return canTake;\n    }\n\n    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {\n        int items = price.size();\n        int offers = special.size();\n        return fun(offers-1,price,special,needs);\n    }\n}",752        "solution_c": "/* Note: This code results in a Timeout. */\nclass Solution {\npublic:\n    int n, c;\n    vector<int> dp;\n    int compute(const vector<int> &price, const vector<vector<int>> &offers, int needs){\n        if(dp[needs] != -1) return dp[needs];\n        // Compute the min cost to satisfy these needs\n        int best{}, new_needs, i;\n        for(int i=0; i<n; i++){\n            c = ((needs>>(i*4))&0xf);\n            best += c * price[i];\n        }\n        if(best == 0) return 0;\n        for(const vector<int> &offer : offers){\n            new_needs = 0;\n            for(i=0; i<n; i++){\n                c = ((needs>>(i*4))&0xf);\n                if(c >= offer[i]) new_needs |= ((c-offer[i])<<(i*4));\n                else break;\n            };\n            if(i == n) best = min(best, compute(price, offers, new_needs) + offer.back());\n        }\n        return dp[needs] = best;\n    }\n    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {\n        dp.resize((1<<24)+10, -1);\n        n = needs.size();\n        int needs_hash{};\n        for(int i=0; i<n; i++) needs_hash |= ((needs[i])<<(i*4));\n        return compute(price, special, needs_hash);\n    }\n};"753    },754    {755        "title": "Sort Array By Parity",756        "algo_input": "Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.\n\nReturn any array that satisfies this condition.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,1,2,4]\nOutput: [2,4,3,1]\nExplanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n\n\nExample 2:\n\nInput: nums = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t0 &lt;= nums[i] &lt;= 5000\n\n",757        "solution_py": "class Solution:\n    def sortArrayByParity(self, A: List[int]) -> List[int]:\n        i, j = 0, len(A) - 1\n        while i < j:\n        \tif A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i]\n        \ti, j = i + 1 - A[i] % 2, j - A[j] % 2\n        return A",758        "solution_js": "var sortArrayByParity = function(nums) {\n  let even = []\n  let odd = []\n  \n  for(let i = 0; i < nums.length; i++){\n      (nums[i] % 2 === 0) ? even.push(nums[i]) : odd.push(nums[i])\n  }\n    \n    return [...even, ...odd]\n  \n    \n};",759        "solution_java": "class Solution {\n\n    public int[] sortArrayByParity(int[] nums) {\n        int i = 0;\n        int j = 0;\n\n        while(i < nums.length){\n            if(nums[i] % 2 == 1){\n                i++;\n            }else{\n                int temp = nums[i];\n                nums[i] = nums[j];\n                nums[j] = temp;\n\n                i++;\n                j++;\n            }\n        }\n\n        return nums;\n    }\n}",760        "solution_c": "class Solution {\npublic:\n    vector<int> sortArrayByParity(vector<int>& nums)\n    {\n        vector<int> v;\n        vector<int> odd;\n        if(nums.size()==1)\n        {\n            return nums;\n        }\n        for(auto it : nums)\n        {\n            if(it%2==0)\n            {\n                v.push_back(it);\n            }\n            else\n            {\n                   odd.push_back(it);\n            }\n            \n        }\n\n        for(auto i : odd)\n        {\n            v.push_back(i);\n        }\n        return v;\n    }\n};"761    },762    {763        "title": "Arranging Coins",764        "algo_input": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.\n\nGiven the integer n, return the number of complete rows of the staircase you will build.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: 2\nExplanation: Because the 3rd row is incomplete, we return 2.\n\n\nExample 2:\n\nInput: n = 8\nOutput: 3\nExplanation: Because the 4th row is incomplete, we return 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",765        "solution_py": "class Solution:\n    def arrangeCoins(self, n: int) -> int:\n        for i in range(1,2**31):\n            val=i*(i+1)//2\n            if val>n:\n                a=i\n                break\n            elif val==n:\n                return i\n        return a-1",766        "solution_js": "var arrangeCoins = function(n) {\n    if(n===1) return n\n    for(let i=1; i<=n; i++){\n        if(n<Math.floor((i*(i+1))/2)){\n            return i-1\n        }\n    }\n};",767        "solution_java": "class Solution {\n    public int arrangeCoins(int n) {\n        long s =0; long e = n;\n        while (s <= e) {\n         long mid = s +(e-s)/2;\n            long coin = mid *( mid +1)/2;\n            if(coin > n){\n                 e = mid -1;\n            } else if (coin < n){\n                s = mid +1;\n            } else return (int) mid;\n        }\n        return (int)e;\n    }\n}",768        "solution_c": "class Solution {\npublic:\n    int arrangeCoins(int n) {\n\n         int count=0;\n         while(n>0)\n         {\n             count++;\n             n=n-count;\n         }\n         if(n==0) //all the coins are used to make complete rows so n if fully uitlized till 0\n         {\n             return count;\n         }\n         else if(n<0) //if the last row has not been created fully then n will go negative\n         {\n             return count-1;\n         }\n         return -1; //this will never get encountered\n\n    }\n};"769    },770    {771        "title": "Intersection of Two Arrays II",772        "algo_input": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2,2]\n\n\nExample 2:\n\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [4,9]\nExplanation: [9,4] is also accepted.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums1.length, nums2.length &lt;= 1000\n\t0 &lt;= nums1[i], nums2[i] &lt;= 1000\n\n\n&nbsp;\nFollow up:\n\n\n\tWhat if the given array is already sorted? How would you optimize your algorithm?\n\tWhat if nums1's size is small compared to nums2's size? Which algorithm is better?\n\tWhat if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?\n\n",773        "solution_py": "class Solution:\n    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n        nums1.sort()\n        nums2.sort()\n        ans = []\n        i, j = 0, 0\n        while i < len(nums1) and j < len(nums2):\n            if nums1[i] < nums2[j]:\n                i += 1\n            elif nums1[i] > nums2[j]:\n                j += 1\n            else:\n                ans.append(nums1[i])\n                i += 1\n                j += 1\n        return ans",774        "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\nvar intersect = function(nums1, nums2) {\n    // initialize empty array\n    let result = [];\n    \n    // sort arrays\n    const nums1Sorted = nums1.sort((a,b) => a - b);\n    const nums2Sorted = nums2.sort((a,b) => a - b);\n    \n    let i = 0;\n    let j = 0;\n    \n    while(i < nums1Sorted.length && j < nums2Sorted.length ){\n        // if nums1 index value is smaller than nums2 index value continue interating through nums1\n       if(nums1Sorted[i] < nums2Sorted[j]){\n           i++;\n        // if nums1 index value is larger than nums2 index value continue interating through nums2\n       }else if(nums1Sorted[i] > nums2Sorted[j]){\n           j++;\n       }else{\n           // if match found, push to result\n           result.push(nums1Sorted[i]);\n           i++;\n           j++;\n       }\n    }\n    return result;\n    \n};",775        "solution_java": "class Solution {\n    public int[] intersect(int[] nums1, int[] nums2) {\n        int[] dp = new int[1000+1];\n        for(int i: nums1){\n            dp[i]++;\n        }\n        int ptr =0;\n        int ans[] = new int[1000+1];\n        for(int i:nums2){\n            if(dp[i]!= 0){\n                ans[ptr]= i;\n                ptr++;\n                dp[i]--;\n            }\n                        \n        }\n        return Arrays.copyOfRange(ans,0,ptr);\n    }\n}",776        "solution_c": "class Solution {\npublic:\n    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {\n     sort(nums1.begin(),nums1.end());\n    sort(nums2.begin(),nums2.end());\n\n    int a = nums1.size();\n    int b = nums2.size();\n\n    int i=0,j=0;\n    vector<int>res;\n\n    while(i<a && j<b)\n    {\n        if(nums1[i] > nums2[j])\n        {\n            j++;\n        }\n        else if(nums1[i] < nums2[j])\n        {\n            i++;\n        }\n        else\n        {\n            res.push_back(nums1[i]);\n            i++;\n            j++;\n        }\n    }\n\n    return res;\n}\n};"777    },778    {779        "title": "Maximum Number of Visible Points",780        "algo_input": "You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.\n\nInitially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].\n\n\nYour browser does not support the video tag or this video format.\n\n\nYou can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\n\nThere can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\n\nReturn the maximum number of points you can see.\n\n&nbsp;\nExample 1:\n\nInput: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput: 3\nExplanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n\n\nExample 2:\n\nInput: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput: 4\nExplanation: All points can be made visible in your field of view, including the one at your location.\n\n\nExample 3:\n\nInput: points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput: 1\nExplanation: You can only see one of the two points, as shown above.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= points.length &lt;= 105\n\tpoints[i].length == 2\n\tlocation.length == 2\n\t0 &lt;= angle &lt; 360\n\t0 &lt;= posx, posy, xi, yi &lt;= 100\n\n",781        "solution_py": "class Solution:\n    def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n\n        arr, extra = [], 0\n        xx, yy = location\n\n        for x, y in points:\n            if x == xx and y == yy:\n                extra += 1\n                continue\n            arr.append(math.atan2(y - yy, x - xx))\n\n        arr.sort()\n        arr = arr + [x + 2.0 * math.pi for x in arr]\n        angle = math.pi * angle / 180\n\n        l = ans = 0\n        for r in range(len(arr)):\n            while arr[r] - arr[l] > angle:\n                l += 1\n            ans = max(ans, r - l + 1)\n\n        return ans + extra",782        "solution_js": "// basically First i transform my points into degrees in regards to my location as the center\n// I need to perform a sliding window to see how many points can fit within my window of length\n// angle \nvar visiblePoints = function(points, angle, location) {\n    \n    //Math.atan2(y,x) returns the ANGLE in RADIANS between the point (X,Y), the CENTER (0,0) and x'x\n    // so Math.atan2(5,5) * (180/Math.pi) === 45 //transforms it from radians to degrees instead\n    let [sx,sy]=location\n    let onCenter=points.filter(([x,y])=>(x==sx&&y==sy)).length //if i m standing on a point i always count it\n\n    points=points.filter(([x,y])=>!(x==sx&&y==sy)) //other than that i dont want it messing with my result\n\n                 .map(([x,y])=>{\n                    // i need to transform my center from (0,0) to location, hence (y-sy,x-sx)\n                         return Math.atan2(y-sy,x-sx)*(180/Math.PI) //returns the degrees\n                    })\n                 .sort((a,b)=>a-b) \n\n    //I will now perform the circular array duplication trick in order to consider points from different view\n    points=[...points,...points.map(d=>d+360)] \n    // so for example if a point is 340, it can go with a point that is 15\n    // example : [0,60,230,250,359], angle=200\n    // would become     [0,60,230,250,359,360,420,590,610,719]\n    // would allow me to pick  *   *   *   *   * ,which is practically [230,250,359,0,60] \n    // (every element of my starting array), which are obviously visible with anangle fo 200 deg\n\n\n    //now i will perform a sliding window that tracks the points visible from my current degree-my angle degrees\n    let start=0,n=points.length,result=0\n    for (let end = 0; end < n; end++) {\n        while(start<end&&points[start]<points[end]-angle) //if the point of start is no bueno\n            start++ // shrink the window until all the points are within angle degrees \n        result=Math.max(result,end-start+1)\n    }\n    return result+onCenter //the points i can see + the ones i ms tanding on\n\n};",783        "solution_java": "class Solution {\n    public int visiblePoints(List<List<Integer>> points, int angle, List<Integer> location) {\n        int overlap = 0;\n        List<Double> list = new ArrayList<>(points.size());\n        for (List<Integer> p : points) {\n            if (p.get(0) == location.get(0) && p.get(1) == location.get(1)) {\n                overlap++;\n            } else {\n                list.add(angle(p.get(1) - location.get(1),\n                               p.get(0) - location.get(0)));\n            }\n        }\n        Collections.sort(list);\n        int max = 0;\n        int n = list.size();\n        int i2 = 0;\n        // list.get(i1) is first angle leg\n        // list.get(i2) is second angle leg\n        for (int i1 = 0; i1 < n; i1++) {\n            // let's grow i1-i2 angle as much as possible\n            // edge case example: angle = 30, i1 = 350 degrees, i2 = 10 degrees\n            // edge case handling: allow i2 to circle around and calculate second leg as (360 + list.get(i2 % n))\n            // then i1 = 350, i2 = 370, delta = 20 degrees < 30 degrees\n            while ((i2 < n && list.get(i2) - list.get(i1) <= angle) ||\n                   (i2 >= n && 360 + list.get(i2 % n) - list.get(i1) <= angle)) {\n                i2++;\n            }\n            // after i2 went as far as possible away from i1 under allowed limit - check if a new maximum found\n            max = Math.max(max, i2-i1);\n        }\n        return max + overlap;\n    }\n\n    private double angle(int dy, int dx) {\n        double a = Math.toDegrees(Math.atan2(dy, dx));\n        return (a < 0 ? a + 360 : a);\n    }\n}",784        "solution_c": "class Solution {\npublic:\n    int visiblePoints(vector<vector<int>>& points, int angle, vector<int>& location) {\n        vector<double> pa;\n        int at_start=0;\n        for(auto point:points)\n        {\n            if(point[0]==location[0] && point[1]==location[1])\n                at_start++;\n            else\n            {\n                double ang = atan2(point[1]-location[1], point[0]-location[0]) * 180.0 /M_PI;\n                if(ang<0)\n                    ang+=360;\n                pa.push_back(ang);\n            }\n        }\n        sort(pa.begin(), pa.end());\n        int n=pa.size();   \n        int l = 0, ret=0;\n        for(int i=0; i<n; i++)\n            pa.push_back(pa[i] + 360);\n        for(int r=0; r<pa.size(); r++)\n        {\n            while((pa[r]-pa[l])>angle)\n                l++;\n            ret = max(ret, r-l+1);\n        }\n        return ret+at_start;\n    }\n};"785    },786    {787        "title": "Robot Return to Origin",788        "algo_input": "There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.\n\nYou are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).\n\nReturn true if the robot returns to the origin after it finishes all of its moves, or false otherwise.\n\nNote: The way that the robot is \"facing\" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.\n\n&nbsp;\nExample 1:\n\nInput: moves = \"UD\"\nOutput: true\nExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\n\n\nExample 2:\n\nInput: moves = \"LL\"\nOutput: false\nExplanation: The robot moves left twice. It ends up two \"moves\" to the left of the origin. We return false because it is not at the origin at the end of its moves.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= moves.length &lt;= 2 * 104\n\tmoves only contains the characters 'U', 'D', 'L' and 'R'.\n\n",789        "solution_py": "class Solution:\n    def judgeCircle(self, moves: str) -> bool:\n        x=Counter(moves)\n        flag=False\n        if(x['U']==x['D'] and x['L']==x['R']):\n            flag=True\n        return flag",790        "solution_js": "var judgeCircle = function(moves) {\n    let x=0,y=0\n    for(i=0;i<moves.length;i++){\n        switch (moves[i]) {\n            case 'R':\n                x++;\n                break;\n            case 'L':\n                x--;\n                break;\n            case 'U':\n                y++;\n                break;\n            case 'D':\n                y--;\n                break;\n        }\n    }\n     return x === 0 && y === 0\n\n};",791        "solution_java": "class Solution {\n    public boolean judgeCircle(String moves) {\n       int up=0;\n        int rt=0;\n        for(int i=0;i<moves.length();i++){\n            if(moves.charAt(i)=='U') up++;\n            if(moves.charAt(i)=='R') rt++;\n            if(moves.charAt(i)=='L') rt--;\n            if(moves.charAt(i)=='D') up--;\n            \n        }\n        if(up==0&&rt==0) return true;\n        return false;\n    }\n}",792        "solution_c": "class Solution {\npublic:\n    bool judgeCircle(string moves) {\n        int n=moves.size();\n        int a=0;\n        int b=0;\n        int c=0;\n        int d=0;\n        for(int i=0;i<n;i++)\n        {\n            if(moves[i]=='R')\n            {\n               a=a+1;\n            }\n            if(moves[i]=='L')\n            {\n               b=b+1;\n            }\n             if(moves[i]=='U')\n             {\n               c=c+1;\n             }\n             if(moves[i]=='D')\n             {\n               d=d+1;\n             }\n         }\n        /*if(a==b && c==0 && d==0)\n        {\n            return true;\n        }\n        if(c==d && a==0 && b==0)\n        {\n            return true;\n        }*/\n        if(a==b && b==c && c==d)\n        {\n            return true;\n        }\n         if(a==b && c==d)\n        {\n            return true;\n        }\n        return false;\n    }\n};"793    },794    {795        "title": "Set Mismatch",796        "algo_input": "You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.\n\nYou are given an integer array nums representing the data status of this set after the error.\n\nFind the number that occurs twice and the number that is missing and return them in the form of an array.\n\n&nbsp;\nExample 1:\nInput: nums = [1,2,2,4]\nOutput: [2,3]\nExample 2:\nInput: nums = [1,1]\nOutput: [1,2]\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 104\n\t1 &lt;= nums[i] &lt;= 104\n\n",797        "solution_py": "class Solution {\npublic:\n    vector<int> findErrorNums(vector<int>& nums) \n    {\n        unordered_map<int,int> m;\n        int p,q;\n        for(auto &x:nums)\n        {\n            m[x]++;\n            if(m[x]==2)\n            {\n                p=x;\n                break;\n            }\n        }\n        int n=nums.size();\n        q=(n*(n+1))/2-accumulate(nums.begin(),nums.end(),0)+p;\n        return {p,q};\n        \n    }\n};\n// if you like the solution plz upvote.",798        "solution_js": "class Solution {\npublic:\n    vector<int> findErrorNums(vector<int>& nums) \n    {\n        unordered_map<int,int> m;\n        int p,q;\n        for(auto &x:nums)\n        {\n            m[x]++;\n            if(m[x]==2)\n            {\n                p=x;\n                break;\n            }\n        }\n        int n=nums.size();\n        q=(n*(n+1))/2-accumulate(nums.begin(),nums.end(),0)+p;\n        return {p,q};\n        \n    }\n};\n// if you like the solution plz upvote.",799        "solution_java": "class Solution {\n    public int[] findErrorNums(int[] nums) {\n        int n = nums.length;\n        int dup = 0, miss = 0;\n\n        for (int i = 1; i <= n; i++) {\n            int count = 0;\n            for (int j = 0; j < n; j++) {\n                if (nums[j] == i) count++;\n            }\n\n            if (count == 2) dup = i;\n            if (count == 0) miss = i;\n        }\n\n        return new int[] {dup, miss};\n    }\n}\n\n// TC: O(n ^ 2), SC: O(1)",800        "solution_c": "class Solution {\npublic:\n    vector<int> findErrorNums(vector<int>& nums)\n    {\n        unordered_map<int,int> m;\n        int p,q;\n        for(auto &x:nums)\n        {\n            m[x]++;\n            if(m[x]==2)\n            {\n                p=x;\n                break;\n            }\n        }\n        int n=nums.size();\n        q=(n*(n+1))/2-accumulate(nums.begin(),nums.end(),0)+p;\n        return {p,q};\n\n    }\n};\n// if you like the solution plz upvote."801    },802    {803        "title": "All Possible Full Binary Trees",804        "algo_input": "Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.\n\nEach element of the answer is the root node of one possible tree. You may return the final list of trees in any order.\n\nA full binary tree is a binary tree where each node has exactly 0 or 2 children.\n\n&nbsp;\nExample 1:\n\nInput: n = 7\nOutput: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]\n\n\nExample 2:\n\nInput: n = 3\nOutput: [[0,0,0]]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 20\n\n",805        "solution_py": "We can't create Full Binary tree with even number of nodes. e.g n = 2/4/6/8...\nstart with cache having n = 1\n\tcache = {1:TreeNode()}\n\t\n\tn = 3\n\t\t\t\t\t\t\t0 (root)\n\t\t\t\t\t\t 1     1\n\tn = 5       \n\t                        0 (root1)                  0 (root2) \n\t\t\t\t\t\t 1     3                     3    1\n\tn = 7  \n\t                         0                    0                   0\n\t\t\t\t\t\t 1      5              3    3              5     1\n\n\nclass Solution:\n    def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n        def helper(n):\n            if n in cache:\n                return cache[n]\n            # We use result array to store all possible binary tree of size n\n            result = [] \n            leftNodes, rightNodes = 1,n-2\n            # if n = 7 then, (leftNodes,rightNodes) should be : (1,5),(3,3),(5,1) \n            while rightNodes >0:\n                root = TreeNode()\n                if leftNodes not in cache:\n                    helper(leftNodes)\n                if rightNodes not in cache:\n                    helper(rightNodes)\n                leftTree = cache[leftNodes]\n                rightTree = cache[rightNodes]\n                # Using two for loops we generate all possible binary tree.\n                # Always remember root of each binary tree is diffrent, So create new root every time\n                for i in range(len(leftTree)):\n                    for j in range(len(rightTree)):\n                        root.left = leftTree[i]\n                        root.right = rightTree[j]\n                        result.append(root)\n                        root = TreeNode()\n                leftNodes += 2\n                rightNodes -= 2\n            cache[n] = result\n            return result\n            \n        if n % 2 == 0:\n            return \n        else:\n            cache = {1:[TreeNode()]}\n            return helper(n)\n\t\t\t\nThank You 😊",806        "solution_js": "var allPossibleFBT = function(n) {\n    if(n % 2 == 0) return [];\n    if( n == 1 ) return [new TreeNode(0)];\n    const ans = [];\n\n    const generate = (x) => {\n        if(x == 1) return [new TreeNode(0)];\n        const ans = [];\n        for(let l = 1; l <= x - 2; l += 2) {\n            const left = generate(l);\n            const right = generate(x - 1 - l);\n            left.forEach(l => {\n                right.forEach(r => {\n                    const root = new TreeNode(0);\n                    root.left = l;\n                    root.right = r;\n                    ans.push(root);\n                });\n            });\n        }\n        return ans;\n    }\n\n    for(let l = 1; l <= n - 2; l += 2) {\n        const left = generate(l);\n        const right = generate(n - 1 - l);\n        left.forEach(l => {\n            right.forEach(r => {\n                const root = new TreeNode(0);\n                root.left = l;\n                root.right = r;\n                ans.push(root);\n            });\n        });\n    }\n\n    return ans;\n};",807        "solution_java": "class Solution {\n    List<TreeNode>[] memo;\n    public List<TreeNode> allPossibleFBT(int n) {\n        memo = new ArrayList[n+1];\n        return dp(n);\n    }\n\n    public List<TreeNode> dp(int n){\n        if(n==0 || n==2){\n            return new ArrayList<TreeNode>();\n        }\n        if(n==1){\n            List<TreeNode> temp = new ArrayList<>();\n            temp.add(new TreeNode(0));\n            return temp;\n        }\n        List<TreeNode> res = new ArrayList<>();\n        for(int i=1;i<n-1;i=i+2){\n            List<TreeNode> right;\n            List<TreeNode> left;\n            if(memo[i]!=null) right = memo[i];\n            else right = dp(i);\n            if(memo[n-1-i]!=null) left = memo[n-1-i];\n            else left = dp(n-1-i);\n\n            for(TreeNode l : left){\n                for(TreeNode r : right){\n                    TreeNode temp = new TreeNode(0);\n                    temp.left=l;\n                    temp.right=r;\n                    res.add(temp);\n                }\n            }\n         }\n        memo[n] = res;\n        return res;\n\n    }\n}",808        "solution_c": "class Solution {\npublic:\n    unordered_map<int,vector<TreeNode*>> dp;\n    int hash(int i,int j){\n        return (i*21 + j);\n    }\n    vector<TreeNode*> fn(int l,int r){\n        int has = hash(l,r);\n        if(dp.find(has)!=dp.end()){\n            return dp[has];\n        }\n        vector<TreeNode*> res;\n        if(r<l){\n            return {NULL};\n        }\n        if(r==l){\n            return {new TreeNode(0)};\n        }\n        for(int i = l+1;i<r;i++){\n             vector<TreeNode*> left =  fn(l,i-1);\n            vector<TreeNode*> right =  fn(i+1,r);\n              for(auto le:left){\n                for(auto ri:right ){\n                    TreeNode* temp = new TreeNode(0);\n                    temp->left = le;\n                    temp->right = ri;\n                    res.push_back(temp);\n                }\n            }\n        }\n        return dp[has] = res;\n    }\n    vector<TreeNode*> allPossibleFBT(int n) {\n        return fn(1,n);\n    }"809    },810    {811        "title": "Count Asterisks",812        "algo_input": "You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.\n\nReturn the number of '*' in s, excluding the '*' between each pair of '|'.\n\nNote that each '|' will belong to exactly one pair.\n\n&nbsp;\nExample 1:\n\nInput: s = \"l|*e*et|c**o|*de|\"\nOutput: 2\nExplanation: The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.\n\nExample 2:\n\nInput: s = \"iamprogrammer\"\nOutput: 0\nExplanation: In this example, there are no asterisks in s. Therefore, we return 0.\n\n\nExample 3:\n\nInput: s = \"yo|uar|e**|b|e***au|tifu|l\"\nOutput: 5\nExplanation: The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of lowercase English letters, vertical bars '|', and asterisks '*'.\n\ts contains an even number of vertical bars '|'.\n\n",813        "solution_py": "# Added on 2022-08-18 15:51:55.040392\n\nvar countAsterisks = function(s) {\n    let green=true, count=0;\n    for(let i=0; i<s.length; i++){\n        if(green && s[i]==\"*\"){count++};\n        if(s[i]==\"|\"){green=!green};\n    }\n    return count;\n};",814        "solution_js": "var countAsterisks = function(s) {\n    let green=true, count=0;\n    for(let i=0; i<s.length; i++){\n        if(green && s[i]==\"*\"){count++};\n        if(s[i]==\"|\"){green=!green};\n    }\n    return count;\n};",815        "solution_java": "class Solution {\n    public int countAsterisks(String s) {\n        boolean insidePipe = false;\n        int count = 0;\n        for(int i = 0; i < s.length(); i++){\n            if(s.charAt(i) == '|'){\n                insidePipe = !insidePipe;\n            }\n            if(!insidePipe && s.charAt(i) == '*'){\n                count++;\n            }\n        }\n        return count;\n    }\n}",816        "solution_c": "/*\n1.) Maintain a counter to store the '|'\n2.) After every even no. of '|' count the asteriks.\n*/\nclass Solution {\npublic:\n    int countAsterisks(string s) {\n\n     int ans=0;\n\n    // count of no. of '|'\n        int cnt=0;\n\n        for(int i=0;i<s.size() ;i++) {\n         //if count is even then count the asteriks\n              if(cnt%2==0) {\n                  if(s[i]=='*') ans++;\n              }\n              if(s[i]=='|') cnt++;\n        }\n        return ans;\n    }\n};"817    },818    {819        "title": "Maximum Level Sum of a Binary Tree",820        "algo_input": "Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.\n\nReturn the smallest level x such that the sum of all the values of nodes at level x is maximal.\n\n&nbsp;\nExample 1:\n\nInput: root = [1,7,0,7,-8,null,null]\nOutput: 2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.\n\n\nExample 2:\n\nInput: root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput: 2\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\n",821        "solution_py": " class Solution:\n    def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n        global_max = float('-inf')\n        res = -1\n        q = deque([root])\n        lvl = 1\n        while q:\n            total = 0\n            for _ in range(len(q)):\n                node = q.popleft()\n                if node.left:\n                    q.append(node.left)\n                if node.right:\n                    q.append(node.right)\n                total+=node.val\n            if total>global_max:\n                res = lvl\n                global_max = total\n            lvl+=1\n        return res",822        "solution_js": "var maxLevelSum = function(root) {\n    let res;\n    let maxSum = -Infinity;\n    let currLevel = 1;\n\n    const queue = [root];\n\n    while (queue.length) {\n        let levelSize = queue.length;\n        let levelSum = 0;\n\n        for (let i = 0; i < levelSize; i++) {\n            let curr = queue.shift();\n            levelSum += curr.val;\n\n            if (curr.left) queue.push(curr.left);\n            if (curr.right) queue.push(curr.right);\n        }\n\n        if (maxSum < levelSum) {\n            res = currLevel;\n            maxSum = levelSum\n        }\n\n        currLevel++;\n    }\n\n    return res;\n};",823        "solution_java": "class Solution {\n    Map<Integer, Integer> map = new HashMap<>();\n\n    public void go(TreeNode root, int level) {\n        if(root == null) return;\n        if(map.containsKey(level)) {\n            map.put(level, map.get(level) + root.val);\n        }\n        else {\n            map.put(level, root.val);\n        }\n\n        go(root.left, level+1);\n        go(root.right, level+1);\n    }\n    public int maxLevelSum(TreeNode root) {\n        go(root, 0);\n        int max = Integer.MIN_VALUE, ind = -1;\n        for (var i : map.entrySet()) {\n            if(max < i.getValue()) {\n                max = i.getValue();\n                ind = i.getKey();\n            }\n        }\n        return ind+1;\n    }\n}",824        "solution_c": "class Solution {\npublic:\n    int maxLevelSum(TreeNode* root) {\n        int maxSum = INT_MIN;\n        int minLevel = 1;\n        \n        int level = 1;\n        queue<TreeNode*> qq;\n        qq.push(root);\n\t\t// level order traversal\n        while(!qq.empty()){\n            int size = qq.size();\n            int currSum  = 0;\n            while(size--){\n                auto node = qq.front();\n                qq.pop();\n                currSum += node->val;\n                if(node->left)qq.push(node->left);\n                if(node->right)qq.push(node->right);\n            }\n            if(currSum>maxSum){\n                maxSum = currSum;\n                minLevel = level;\n            }\n            level++;\n        }\n        \n        return minLevel;\n    }\n};"825    },826    {827        "title": "Find the Most Competitive Subsequence",828        "algo_input": "Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.\n\nAn array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.\n\nWe define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,5,2,6], k = 2\nOutput: [2,6]\nExplanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.\n\n\nExample 2:\n\nInput: nums = [2,4,3,3,5,4,9,6], k = 4\nOutput: [2,3,3,4]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt;= 109\n\t1 &lt;= k &lt;= nums.length\n\n",829        "solution_py": "class Solution:\n\tdef mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n\t\tend = len(nums) - k\n\t\tans = []\n\t\tfor num in nums:\n\t\t\twhile end and ans and num < ans[-1] :\n\t\t\t\tans.pop()\n\t\t\t\tend -= 1\n\t\t\tans.append(num)\n\t\t\n\t\treturn ans[:k]",830        "solution_js": "var mostCompetitive = function(nums, k) {\n  let nbToRemove = nums.length - k,stack=[];\n  for (const num of nums) {\n    while (num<stack[stack.length -1] && stack.length && nbToRemove) {\n      stack.pop();\n      nbToRemove--;\n    }\n    stack.push(num)\n  }\n  while ( nbToRemove ) {\n    stack.pop();\n    nbToRemove--;\n  }\n  return stack;\n};",831        "solution_java": "class Solution {\n    public int[] mostCompetitive(int[] nums, int k) {\n        int[] stack = new int[k];\n        for(int i=0,j=0;i<nums.length;i++) {\n          while(j>0 && stack[j-1]>nums[i] && j+nums.length-i>k) {\n              j--;\n          }\n          if(j<k) {\n              stack[j++]=nums[i];\n          }\n        }\n        return stack;\n    }\n}",832        "solution_c": "class Solution {\npublic:\n    vector<int> mostCompetitive(vector<int>& nums, int k) {\n        vector<int> stack;\n        int nums_to_delete = nums.size()-k;\n        for (int i = 0; i < nums.size(); i++) {\n            while (!stack.empty() && nums[i] < stack.back() && nums_to_delete) {\n                stack.pop_back();\n                nums_to_delete--;\n            }\n            stack.push_back(nums[i]);\n        }\n        return vector<int>(stack.begin(), stack.begin()+k);\n    }\n};"833    },834    {835        "title": "Binary Trees With Factors",836        "algo_input": "Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.\n\nWe make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.\n\nReturn the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,4]\nOutput: 3\nExplanation: We can make these trees: [2], [4], [4, 2, 2]\n\nExample 2:\n\nInput: arr = [2,4,5,10]\nOutput: 7\nExplanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 1000\n\t2 &lt;= arr[i] &lt;= 109\n\tAll the values of arr are unique.\n\n",837        "solution_py": "class Solution:\n    def numFactoredBinaryTrees(self, nums: List[int]) -> int:\n        nums = set(nums)\n        n = len(nums)\n        \n        @lru_cache(None)\n        def helper(num):\n            trees = 1\n            for factor in nums:\n                if not num % factor and num // factor in nums:\n                    trees += helper(factor) * helper(num // factor)\n\n            return trees\n        \n        return sum(helper(num) for num in nums) % (10 ** 9 + 7)",838        "solution_js": "/** https://leetcode.com/problems/binary-trees-with-factors/\n * @param {number[]} arr\n * @return {number}\n */\nvar numFactoredBinaryTrees = function(arr) {\n  // Memo\n  this.memo = new Map();\n  \n  // Sort the `arr`\n  arr.sort((a, b) => a - b);\n  \n  // Create hashmap so we can easily find the index of the value\n  let map = new Map();\n  arr.forEach((val, idx) => map.set(val, idx));\n  \n  // We are going to calculate total numbers of binary trees by assigning each `arr[i]` as the root of the tree\n  let count = 0;\n  for (let i = arr.length - 1; i >= 0; i--) {\n    count += dp(arr, map, i);\n  }\n  \n  // Perform mod on the final result\n  let mod = (10 ** 9) + 7;\n  return count % mod;\n};\n\nvar dp = function(arr, map, currIdx) {\n  // Return from memo\n  if (this.memo.has(currIdx) === true) {\n    return this.memo.get(currIdx);\n  }\n  \n  // Start the count as 1 to include the current node\n  let count = 1;\n  \n  // Loop through all number before `arr[currIdx]`\n  for (let i = currIdx - 1; i >= 0; i--) {\n    // The `left` and `right` node of the root\n    // The `right` node is basically the root divided by the `left` since the rule stated that the root is product of its children\n    let left = arr[i];\n    let right = arr[currIdx] / left;\n    \n    // Ignore if the root is not a product of its children\n    if (arr[currIdx] % left !== 0 ||\n       map.has(right) === false) {\n      continue;\n    }\n    \n    // Get the count for `left` node and `right` node\n    let leftCount = dp(arr, map, i);\n    let rightCount = dp(arr, map, map.get(right));\n    \n    // Total count is multiplication of `left` and `right` count because each combination of is unique\n    count += leftCount * rightCount;\n  }\n  \n  // Set memo\n  this.memo.set(currIdx, count);\n  \n  return count;\n};",839        "solution_java": "class Solution {\n    int mod = 1000000007;\n    HashMap<Integer, Long> dp;\n    HashSet<Integer> set;\n    \n    public int numFactoredBinaryTrees(int[] arr) {\n        long ans = 0;\n        dp = new HashMap<>();\n        set = new HashSet<>();\n        \n        for(int val : arr) set.add(val);\n        \n        for(int val : arr) {\n\t\t\t//giving each unique value a chance to be root node of the tree\n            ans += solve(val, arr);\n            ans %= mod;\n        }\n        \n        return (int)ans;\n    }\n    \n    public long solve(int val, int[] nums) {\n        \n        if(dp.containsKey(val)) {\n            return dp.get(val);\n        }\n        \n        long ans = 1;\n        \n        for(int i = 0; i < nums.length; i++) {\n            if(val % nums[i] == 0 && set.contains(val / nums[i])) {\n                long left = solve(nums[i], nums);\n                long right = solve(val / nums[i], nums);\n                \n                ans += ((left * right) % mod);\n                ans %= mod;\n            }\n        }\n        \n        dp.put(val, ans);\n        \n        return ans;\n    }\n}",840        "solution_c": "class Solution {\npublic:\n    const int mod=1e9+7;\n    int numFactoredBinaryTrees(vector<int>& arr) {\n\n        sort(arr.begin(),arr.end());\n        int n=arr.size();\n\n        vector<int> dp(n,1);\n\n        for(int i=1;i<n;i++){\n            int l=0,r=i-1;\n            while(l<=r){\n                if(arr[l]*1LL*arr[r]==arr[i]*1LL){\n                    if(l!=r) dp[i]=(dp[i]+(dp[l]*1LL*dp[r]%mod*2LL%mod))%mod;\n                    else dp[i]=(dp[i]+(dp[l]*1LL*dp[r]%mod))%mod;\n                    l++,r--;\n                } else if(arr[l]*1LL*arr[r]>arr[i]*1LL) r--;\n                else l++;\n            }\n        }\n\n        int ans=0;\n        for(auto i:dp) ans=(ans+i)%mod;\n        return ans;\n    }\n};"841    },842    {843        "title": "Count Good Meals",844        "algo_input": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.\n\nYou can pick any two different foods to make a good meal.\n\nGiven an array of integers deliciousness where deliciousness[i] is the deliciousness of the i​​​​​​th​​​​​​​​ item of food, return the number of different good meals you can make from this list modulo 109 + 7.\n\nNote that items with different indices are considered different even if they have the same deliciousness value.\n\n&nbsp;\nExample 1:\n\nInput: deliciousness = [1,3,5,7,9]\nOutput: 4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.\n\n\nExample 2:\n\nInput: deliciousness = [1,1,1,3,3,3,7]\nOutput: 15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= deliciousness.length &lt;= 105\n\t0 &lt;= deliciousness[i] &lt;= 220\n\n",845        "solution_py": "class Solution:\n    def countPairs(self, deliciousness: List[int]) -> int:\n        pows = [2 ** i for i in range(0,22)] # form our list of powers of 2\n        dp_seen = {} # dict to store what we've seen - dynamic programming solution for time requirement\n        count = 0 # to store the answer\n\n        for j in range(0, len(deliciousness)):\n            for i in range(0, len(pows)):\n                if pows[i] - deliciousness[j] in dp_seen: # \"if we find a previous deliciousness[j] as pows[i] - deliciousness[j], then we will add dp_seen[deliciousness[j]] to count\"\n                    count += dp_seen[pows[i] - deliciousness[j]]\n            if deliciousness[j] in dp_seen:\n                dp_seen[deliciousness[j]] += 1 \n            else:\n                dp_seen[deliciousness[j]] = 1\n                \n        return count % (10**9 + 7) # the arbitrary modulo, presumably to reduce the answer size\n\t\t```",846        "solution_js": "var countPairs = function(deliciousness) {\n    const n = deliciousness.length;\n    const MOD = 1e9 + 7;\n\n    const map = new Map();\n\n    for (const num of deliciousness) {\n        if (!map.has(num)) map.set(num, 0);\n        map.set(num, map.get(num) + 1);\n    }\n\n    let max = 2**21;\n    let res = 0;\n\n    for (const [num, count] of map) {\n\n        let two = 1;\n\n        while (two <= max) {\n            const diff = two - num;\n\n            if (diff >= 0 && map.has(diff)) {\n\n                const otherCount = map.get(diff);\n\n                if (num != diff) res += (count * otherCount);\n                else res += (count * (count - 1) / 2);\n            }\n\n            two <<= 1;\n        }\n\n        map.delete(num);\n    }\n\n    return res % MOD;\n};",847        "solution_java": "class Solution {\n    int mod = 1000000007;\n    public int countPairs(int[] arr) {\n        Map<Integer, Integer> map = new HashMap<>();\n        int n = arr.length;\n        long res = 0;\n        for (int num : arr) {\n            int power = 1;\n            for (int i = 0; i < 22; i++) {\n                if (map.containsKey(power - num)) {\n                    res += map.get(power - num);\n                    res %= mod;\n                }\n                power *= 2;\n            }\n            map.put(num, map.getOrDefault(num, 0) + 1);\n        }\n        return (int) res;\n    }\n}",848        "solution_c": "class Solution {\npublic:\n    int countPairs(vector<int>& deliciousness) {\n        int cnt=0;\n        unordered_map<int,int> mp;\n        mp[deliciousness[0]]++;\n        int mod=1e9+7;\n        for(int i=1;i<deliciousness.size();i++){\n            for(int p=1;p<=(1<<21);p*=2){\n                if(mp.find(p-deliciousness[i])!=mp.end()){\n                    cnt=(cnt+mp[p-deliciousness[i]])%mod;\n                    \n                }\n            }\n            mp[deliciousness[i]]++;\n            \n        }\n        return cnt%mod;\n    }\n};"849    },850    {851        "title": "Strong Password Checker",852        "algo_input": "A password is considered strong if the below conditions are all met:\n\n\n\tIt has at least 6 characters and at most 20 characters.\n\tIt contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\n\tIt does&nbsp;not contain three repeating characters in a row (i.e.,&nbsp;\"...aaa...\" is weak, but \"...aa...a...\" is strong, assuming other conditions are met).\n\n\nGiven a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0.\n\nIn one step, you can:\n\n\n\tInsert one character to password,\n\tDelete one character from password, or\n\tReplace&nbsp;one character of password with another character.\n\n\n&nbsp;\nExample 1:\nInput: password = \"a\"\nOutput: 5\nExample 2:\nInput: password = \"aA1\"\nOutput: 3\nExample 3:\nInput: password = \"1337C0d3\"\nOutput: 0\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= password.length &lt;= 50\n\tpassword consists of letters, digits, dot&nbsp;'.' or exclamation mark '!'.\n\n",853        "solution_py": "class Solution:\n    def strongPasswordChecker(self, password: str) -> int:\n        #vimla_kushwaha\n        s = password\n        missing_type = 3\n        if any('a' <= c <= 'z' for c in s): missing_type -= 1\n        if any('A' <= c <= 'Z' for c in s): missing_type -= 1\n        if any(c.isdigit() for c in s): missing_type -= 1\n\n        change = 0\n        one = two = 0\n        p = 2\n        while p < len(s):\n            if s[p] == s[p-1] == s[p-2]:\n                length = 2\n                while p < len(s) and s[p] == s[p-1]:\n                    length += 1\n                    p += 1\n                    \n                change += length // 3\n                if length % 3 == 0: one += 1\n                elif length % 3 == 1: two += 1\n            else:\n                p += 1\n        \n        if len(s) < 6:\n            return max(missing_type, 6 - len(s))\n        elif len(s) <= 20:\n            return max(missing_type, change)\n        else:\n            delete = len(s) - 20\n            \n            change -= min(delete, one)\n            change -= min(max(delete - one, 0), two * 2) // 2\n            change -= max(delete - one - 2 * two, 0) // 3\n                \n            return int(delete + max(missing_type, change))",854        "solution_js": "const strongPasswordChecker = (passwd) => {\n    let steps = 0;\n    let mustAdd = 0;\n\n    if (!passwd.match(/[A-Z]/)) {\n        mustAdd++;\n    }\n    if (!passwd.match(/[a-z]/)) {\n        mustAdd++;\n    }\n    if (!passwd.match(/\\d/)) {\n        mustAdd++;\n    }\n\n    let groups = passwd.match(/(.)\\1*/g).filter(x => x.length > 2);\n\n    if (passwd.length <= 20) {\n        groups.forEach(group => {\n            steps += Math.trunc(group.length / 3);\n            mustAdd -= Math.trunc(group.length / 3);\n        })\n    }\n\n    if (passwd.length <= 20) {\n        mustAdd = mustAdd > 0 ? mustAdd : 0;\n        if (passwd.length + steps >= 6) {\n            steps += mustAdd;\n        } else {\n            if (mustAdd > 6 - (passwd.length + steps)) {\n                steps += mustAdd;\n            } else {\n                steps += 6 - (passwd.length + steps);\n            }\n        }\n    }\n\n    if (passwd.length > 20) {\n        let mustRemove = passwd.length - 20;\n        let lengths = [];\n        let plus = [];\n        let chL = 0;\n        for (let i = 1; i <= 3; i++) {\n            for (let k = 0; k < groups.length; k++) {\n                if (plus[k] === undefined) { plus[k] = 0; }\n                chL = groups[k].length - plus[k];\n                if (lengths[k] === undefined) { lengths[k] = chL; }\n                const rec = () => {\n                    if (Math.trunc((chL - i) / 3) < Math.trunc(chL / 3) && passwd.length - steps - i >= 6 && mustRemove >= i && chL > 2 && lengths[k] - i > 0) {\n                        steps += i;\n                        plus[k] += i;\n                        mustRemove -= i;\n                        chL -= i;\n                        lengths[k] -= i;\n                        rec();\n                    }\n                }\n                rec();\n            }\n        }\n        lengths.forEach(length => {\n            if (length > 2) {\n                steps += Math.trunc(length / 3);\n                mustAdd -= Math.trunc(length / 3);\n            }\n        }\n        )\n\n        mustRemove = mustRemove > 0 ? mustRemove : 0;\n        mustAdd = mustAdd > 0 ? mustAdd : 0;\n        steps += mustAdd + mustRemove;\n    }\n\n    return steps;\n};",855        "solution_java": "class Solution {\n    private static final int MIN_LENGTH = 6;\n    private static final int MAX_LENGTH = 20;\n\n    public int strongPasswordChecker(String password) {\n        int numMissingComponents = getNumberOfMissingComponents(password);\n        int n = password.length();\n\n        if (n < MIN_LENGTH) {\n            return Math.max(numMissingComponents, MIN_LENGTH - n);\n        }\n\n        List<Integer> repeats = buildRepeatList(password);\n\n        int over = Math.max(0, n - MAX_LENGTH);\n        int numRemoval = over;\n\n        // use overage for repeat % 3 == 0 case. One removal would reduce one replacement\n        for (int i = 0; i < repeats.size() && over > 0; i++) {\n            int repeat = repeats.get(i);\n            if (repeat >= 3 && repeat % 3 == 0) {\n                repeats.set(i, repeat - 1);\n                over--;\n            }\n        }\n        // use overage for repeat % 3 == 1 case. Two removal would reduce one replacement\n        for (int i = 0; i < repeats.size() && over > 0; i++) {\n            int repeat = repeats.get(i);\n            if (repeat >= 3 && repeat % 3 == 1) {\n                repeats.set(i, repeat - Math.min(over, 2));\n                over -= Math.min(over, 2);\n            }\n        }\n\n        int numReplace = 0;\n        for (int repeat : repeats) {\n            if (over > 0 && repeat >= 3) {\n                int reduce = Math.min(over, repeat - 2);\n                over -= reduce;\n                repeat -= reduce;\n            }\n            if (repeat >= 3) {\n                numReplace += repeat / 3;\n            }\n        }\n\n        return Math.max(numReplace, numMissingComponents) + numRemoval;\n    }\n\n    private List<Integer> buildRepeatList(String password) {\n        List<Integer> repeats = new ArrayList<>();\n        for (int i = 0; i < password.length(); i++) {\n            if (i == 0 || password.charAt(i) != password.charAt(i - 1)) {\n                repeats.add(1);\n            } else {\n                int last = repeats.size() - 1;\n                repeats.set(last, repeats.get(last) + 1);\n            }\n        }\n        return repeats;\n    }\n\n    private int getNumberOfMissingComponents(String password) {\n        int digit = 1;\n        int upper = 1;\n        int lower = 1;\n        for (char c: password.toCharArray()) {\n            if (Character.isDigit(c)) {\n                digit = 0;\n            }\n            if (Character.isLowerCase(c)) {\n                lower = 0;\n            }\n            if (Character.isUpperCase(c)) {\n                upper = 0;\n            }\n        }\n        return digit + upper + lower;\n    }\n}",856        "solution_c": "class Solution {\npublic:\n    int strongPasswordChecker(string password) {\n\nif (password.size()<=2) return (6-password.size());\n    else\n    {\n        //is first condition met?\n        int sizeissue=0;\n        if (password.size()<6)\n            sizeissue=password.size()-6;\n        else if(password.size()>20) sizeissue=password.size()-20;\n\n        //is second condition met?\n        int chtype=0, u=1,l=1,d=1;\n\n        if(none_of(password.begin(), password.end(), &::isupper)) { chtype++; u=0;}\n        if(none_of(password.begin(), password.end(), &::islower)) { chtype++; l=0;}\n        if(none_of(password.begin(), password.end(), &::isdigit)) { chtype++; d=0;}\n\n        //is the third condition met? Note there are 26 letter, the string is constrained under 50, so realistically you can always find some 'other' character not included previously in the string to break the password apart so the consecutive characters are split apart. So need to find the largest sets of consecutive characters or 'blocks', and for these the min is (size of block (-1 if even)/2?\n        unsigned int output=0, i=0, start,end,issuethree=0;\n        char c;\n\n        if (sizeissue<0)\n            {\n                while (i<(password.size()-2))\n                { if (password[i]==password[i+1]&&password[i]==password[i+2])\n                    { start=i;\n                        c=password[i]; i++;\n                        while (c==password[i+2]&&i<(password.size()-2)) i++;\n                        end=i+1;\n                        i=end+1;\n\n                        //what would the amount of changes be needed?\n\n                        issuethree=(end-start+1)/3;\n\n                        // add the latest issue to total output\n                        output=output+issuethree;\n\n                        // check if the missing second condition issue could resolve any of this\n                        if(chtype>=1)\n                        {if(islower(c)&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(islower(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                        if(isupper(c)&&(l==0)) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(isupper(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                        if(isxdigit(c)&&(l==0)) {chtype--;l=1;issuethree--;}\n                        if(isxdigit(c)&&(u==0)&&issuethree>0) {chtype--;u=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                        if(c=='!'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(c=='!'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(c=='!'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                        if(c=='.'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(c=='.'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                        if(c=='.'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                        }\n\n                        //check first issue would resolve this\n                        if((-sizeissue)<=issuethree) sizeissue=0; //e.g. aaa\n                        else sizeissue=sizeissue+issuethree; //don't think this option is possible?\n\n                    }\n                    else i++;\n                }\n                if (chtype>0 && sizeissue<0)\n                    {if (chtype>abs(sizeissue)) sizeissue=0;\n                    else sizeissue=sizeissue+chtype;}\n            }\n\n        else if (sizeissue==0)\n                {while (i<(password.size()-2))\n                    { if (password[i]==password[i+1]&&password[i]==password[i+2])\n                        { start=i;\n                            c=password[i]; i++;\n                            while (c==password[i+2]&&i<(password.size()-2)) i++;\n                            end=i+1;\n                            i=end+1;\n\n                            //what would the amount of changes be needed?\n\n                            issuethree=(end-start+1)/3;\n\n                            // add the latest issue to total output\n                            output=output+issuethree;\n\n                            // check if the missing second condition issue could resolve any of this\n                            if(chtype>=1)\n                            {if(islower(c)&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(islower(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                            if(isupper(c)&&(l==0)) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(isupper(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                            if(isxdigit(c)&&(l==0)) {chtype--;l=1;issuethree--;}\n                            if(isxdigit(c)&&(u==0)&&issuethree>0) {chtype--;u=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                            if(c=='!'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(c=='!'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(c=='!'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                            if(c=='.'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(c=='.'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                            if(c=='.'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                            }\n\n                         }\n                        else i++;\n\n                    }\n                }\n\n        else if (sizeissue>0)\n                {int v[3],mod;\n                    v[0]=0; v[1]=0; v[2]=0;\n                    //have a vector where it says how many extra characters at the end of a block; e.g. aaa aa = v[2]=1; and in issue three how many blocks;\n                    while (i<(password.size()-2))\n                        { if (password[i]==password[i+1]&&password[i]==password[i+2])\n                            { start=i;\n                                c=password[i]; i++;\n                                while (c==password[i+2]&&i<(password.size()-2)) i++;\n                                end=i+1;\n                                i=end+1;\n\n                                issuethree=issuethree+(end-start+1)/3;\n                                mod=(end-start+1)%3;\n                                v[mod]=v[mod]+1;\n                                }\n\n                            else i++;\n                        }\n                    output=issuethree;\n\n                    //delete efficiently to ensure most 'blocks of 3' are removed.\n                    while (sizeissue>=1&&v[0]>0)\n                    {sizeissue=sizeissue-1; v[0]--; issuethree--;}\n                    while (sizeissue>=2&&v[1]>0)\n                    {sizeissue=sizeissue-2; v[1]--; output=output+1; issuethree--;}\n                    while (sizeissue>=3&&v[2]>0)\n                    {sizeissue=sizeissue-3; v[2]--; output=output+2; issuethree--;}\n                    while(sizeissue>=3&&issuethree>0)\n                    {sizeissue=sizeissue-3; issuethree--; output=output+2;}\n\n                    i=0;\n                        // check if the missing second condition issue could resolve any of this\n                    {while (i<(password.size()-2) && issuethree>0)\n                        { if (password[i]==password[i+1]&&password[i]==password[i+2])\n                            { start=i;\n                                c=password[i]; i++;\n                                while (c==password[i+2]&&i<(password.size()-2)) i++;\n                                end=i+1;\n                                i=end+1;\n\n                                // check if the missing second condition issue could resolve any of this\n                                if(chtype>=1)\n                                {if(islower(c)&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(islower(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                                    if(isupper(c)&&(l==0)) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(isupper(c)&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                                    if(isxdigit(c)&&(l==0)) {chtype--;l=1;issuethree--;}\n                                    if(isxdigit(c)&&(u==0)&&issuethree>0) {chtype--;u=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                                    if(c=='!'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(c=='!'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(c=='!'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                                    if(c=='.'&&(u==0)) {chtype--;u=1; issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(c=='.'&&(d==0)&&issuethree>0) {chtype--;d=1;issuethree--; if(sizeissue<0) sizeissue++; }\n                                    if(c=='.'&&(l==0)&&issuethree>0) {chtype--;l=1;issuethree--; if(sizeissue<0) sizeissue++; }\n\n                                }\n\n                            }\n                            else i++;\n\n                        }\n                    }\n\n                }\n\n        //add all other changes remaining to be done\n        output=output+chtype+abs(sizeissue);\n\n        return output;\n\n    }\n\n    }\n\n   };"857    },858    {859        "title": "Binary Tree Level Order Traversal",860        "algo_input": "Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).\n\n&nbsp;\nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[9,20],[15,7]]\n\n\nExample 2:\n\nInput: root = [1]\nOutput: [[1]]\n\n\nExample 3:\n\nInput: root = []\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 2000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\n",861        "solution_py": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, val=0, left=None, right=None):\n#         self.val = val\n#         self.left = left\n#         self.right = right\nclass Solution:\n    \n        \n    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n        \n        ret = []\n        next_levels = [[root]]\n        \n        for level in next_levels:\n            curr_lv = []\n            next_lv = []\n            for node in level:\n                if not node: \n                    continue\n                curr_lv.append(node.val)\n                next_lv.append(node.left)\n                next_lv.append(node.right)\n            \n            if curr_lv: \n                ret.append(curr_lv)\n            if next_lv: \n                next_levels.append(next_lv)\n        \n        return ret",862        "solution_js": "var levelOrder = function(root) {\n  const result = [];\n  if (root == null) return result\n\n  let lvl = 0;\n  let temp = [];\n  let q = new Queue();\n  q.enqueue(root)\n\n  while (!q.isEmpty()) {\n    let levelSize = q.size();\n    while (levelSize-- != 0) {\n      let node = q.dequeue()\n      temp.push(node.val)\n      // enqueue both children first,\n      // before looking at the next dequeued item\n      if (node.left != null) q.enqueue(node.left);\n      if (node.right != null) q.enqueue(node.right);\n    }\n    result.push(temp);\n    temp = [];\n    lvl +=1\n  }\n\n  return result\n};",863        "solution_java": "class Solution {\n    public List<List<Integer>> levelOrder(TreeNode root) {\n        List<List<Integer>> result = new ArrayList<>();\n        if(root == null)\n            return result;\n        List<Integer> rootList = new ArrayList<>();\n        rootList.add(root.val);\n        result.add(rootList);\n        levelOrder(root,1,result);\n        return result;\n\n    }\n\n    private void levelOrder(TreeNode root, int level, List<List<Integer>> result) {\n        if(root == null)\n            return;\n        List<Integer> children = exploreChildren(root);\n        if(!children.isEmpty()){\n            if(level < result.size())\n                result.get(level).addAll(children);\n            else\n                result.add(children);\n        }\n        levelOrder(root.left, level + 1, result);\n        levelOrder(root.right, level + 1,result);\n    }\n\n    private List<Integer> exploreChildren(TreeNode root) {\n        List<Integer> children = new ArrayList<>();\n        if(root.left != null)\n            children.add(root.left.val);\n        if(root.right != null)\n            children.add(root.right.val);\n        return children;\n    }\n}",864        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> levelOrder(TreeNode* root) {\n       queue<TreeNode *>q;\n        vector<vector<int>> result;\n        if(root==NULL) return result;\n        q.push(root);\n        q.push(NULL);\n        vector<int>temp;\n        while(!q.empty())\n        {\n            TreeNode *top = q.front();\n            q.pop();\n            if(top==NULL)\n            {\n                result.push_back(temp);\n                temp.clear();\n                if(!q.empty())\n                {\n                    q.push(NULL);\n                    continue;\n                }\n                return result;               \n            }\n            else temp.push_back(top->val);                            \n            \n            if(top->left) q.push(top->left);                \n               \n            if(top->right) q.push(top->right);            \n        }\n        \n        return result;\n    }\n};"865    },866    {867        "title": "Maximum Sum Obtained of Any Permutation",868        "algo_input": "We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.\n\nReturn the maximum total sum of all requests among all permutations of nums.\n\nSince the answer may be too large, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput: 19\nExplanation: One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -&gt; nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -&gt; nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -&gt; nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -&gt; nums[0] + nums[1] = 3 + 5  = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput: 11\nExplanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput: 47\nExplanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= nums[i]&nbsp;&lt;= 105\n\t1 &lt;= requests.length &lt;=&nbsp;105\n\trequests[i].length == 2\n\t0 &lt;= starti&nbsp;&lt;= endi&nbsp;&lt;&nbsp;n\n\n",869        "solution_py": "class Solution:\n    def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n        count = [0] * len(nums)\n        for i, j in requests:\n            count[i] += 1\n            if j + 1 < len(count):\n                count[j+1] -= 1\n        cur = 0\n        for i in range(len(count)):\n            count[i] += cur\n            cur = count[i]\n        return sum(n * c for n, c in zip(sorted(nums, reverse=True), sorted(count, reverse=True))) % (10 ** 9 + 7)",870        "solution_js": "/**\n * @param {number[]} nums\n * @param {number[][]} requests\n * @return {number}\n */\nvar maxSumRangeQuery = function(nums, requests) {\n    let frequency = new Array(nums.length).fill(0)\n    for(let req of requests){\n        for(let i=req[0];i<=req[1];i++){\n            frequency[i]++\n        }\n    }\n    nums = nums.sort((a,b)=>a-b)\n    let freqArr = frequency.sort((a,b)=>b-a)\n    let sum =0\n    for(let freq of freqArr){\n        sum += (freq * nums.pop())\n    }\n    const mod = (10 ** 9) + 7;\n    return sum%mod\n};",871        "solution_java": "class Solution {\n    public int maxSumRangeQuery(int[] nums, int[][] requests) {\n        int n = nums.length;\n        int[] pref = new int[n];\n        for(int i=0;i<requests.length;i++){\n            pref[requests[i][0]]++;\n            if(requests[i][1]+1<n)pref[requests[i][1]+1]--;\n        }\n        for(int i=1;i<n;i++){\n            pref[i]+= pref[i-1];\n        }\n        Arrays.sort(nums);\n        Arrays.sort(pref);\n        long res = 0;\n        for(int i=0;i<n;i++){\n            res+=((long)pref[i]*nums[i]);\n            res%=1000000007;\n        }\n        return (int)res%1000000007;\n    }\n}",872        "solution_c": "class Solution {\npublic:\n    int MOD = 1e9 + 7 ;\n    vector<int> createPermutation(vector<int>&nums , vector<vector<int>> &requests){\n        sort(begin(nums),end(nums)) ;\n        \n        vector<int>sweep(nums.size() + 1) ;\n        for(auto &x : requests) ++sweep[x[0]] , --sweep[x[1] + 1] ;\n        for(int i = 1 ; i < sweep.size() ; ++i ) sweep[i] += sweep[i-1] ;\n        \n        vector<int> aux(nums.size()) ;\n        set<pair<int,int>> st ;\n        for(int i = 0 ; i < nums.size() ; ++i ) st.insert({sweep[i],i}) ;\n        \n        int i = 0 ;\n        while(st.size()){\n            auto[freq,idx] = *begin(st) ;\n            st.erase(begin(st)) ;\n            aux[idx] = nums[i++] ;\n        }\n        return aux ;\n    }\n    \n    int maxSumRangeQuery(vector<int>& nums, vector<vector<int>>& requests) {\n        vector<int> aux = createPermutation(nums,requests);\n        vector<int>pref ;\n        for(auto &x : aux) pref.push_back(pref.empty() ? x : x + pref.back()) ;\n        int ans = 0 ;\n        for(auto &x : requests) ans = (ans + (pref[x[1]] - (x[0]-1 >= 0 ? pref[x[0] - 1] : 0) + MOD) % MOD) % MOD;\n        return ans ;\n    }\n};"873    },874    {875        "title": "Stock Price Fluctuation",876        "algo_input": "You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.\n\nUnfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.\n\nDesign an algorithm that:\n\n\n\tUpdates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.\n\tFinds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.\n\tFinds the maximum price the stock has been based on the current records.\n\tFinds the minimum price the stock has been based on the current records.\n\n\nImplement the StockPrice class:\n\n\n\tStockPrice() Initializes the object with no price records.\n\tvoid update(int timestamp, int price) Updates the price of the stock at the given timestamp.\n\tint current() Returns the latest price of the stock.\n\tint maximum() Returns the maximum price of the stock.\n\tint minimum() Returns the minimum price of the stock.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]\nOutput\n[null, null, null, 5, 10, null, 5, null, 2]\n\nExplanation\nStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5);  // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current();     // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum();     // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3);  // The previous timestamp 1 had the wrong price, so it is updated to 3.\n                          // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum();     // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2);  // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum();     // return 2, the minimum price is 2 at timestamp 4.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= timestamp, price &lt;= 109\n\tAt most 105 calls will be made in total to update, current, maximum, and minimum.\n\tcurrent, maximum, and minimum will be called only after update has been called at least once.\n\n",877        "solution_py": "class StockPrice:\n\n    def __init__(self):\n        self.timestamps = {}\n        self.highestTimestamp = 0\n        self.minHeap = []\n        self.maxHeap = []\n\n    def update(self, timestamp: int, price: int) -> None:\n\t    #Keep track of current prices\n        self.timestamps[timestamp] = price\n        self.highestTimestamp = max(self.highestTimestamp, timestamp)\n        \n\t\t#For maximum/minimum\n        heappush(self.minHeap, (price, timestamp))\n        heappush(self.maxHeap, (-price, timestamp))\n\n    def current(self) -> int:\n\t    #Just return the highest timestamp in O(1)\n        return self.timestamps[self.highestTimestamp]\n\n    def maximum(self) -> int:\n        currPrice, timestamp = heappop(self.maxHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n        while -currPrice != self.timestamps[timestamp]:\n            currPrice, timestamp = heappop(self.maxHeap)\n            \n        heappush(self.maxHeap, (currPrice, timestamp))\n        return -currPrice\n\n    def minimum(self) -> int:\n        currPrice, timestamp = heappop(self.minHeap)\n\t\t\n\t\t#If the price from the heap doesn't match the price the timestamp indicates, keep popping from the heap\n        while currPrice != self.timestamps[timestamp]:\n            currPrice, timestamp = heappop(self.minHeap)\n            \n        heappush(self.minHeap, (currPrice, timestamp))\n        return currPrice",878        "solution_js": "var StockPrice = function() {\n    this.stocksPrice=[]\n    this.timesStamp=[]\n    this.lastPrice=[0,0];\n    this.maxPrice=Number.NEGATIVE_INFINITY\n    this.minPrice=Number.POSITIVE_INFINITY\n};\n\n/** \n * @param {number} timestamp \n * @param {number} price\n * @return {void}\n */\nStockPrice.prototype.update = function(timestamp, price) {  \n    let index=this.timesStamp.indexOf(timestamp)\n    if(index === -1) {\n        this.timesStamp.push(timestamp)\n        this.stocksPrice.push(price)\n        this.maxPrice=Math.max(this.maxPrice, price)\n        this.minPrice=Math.min(this.minPrice, price)\n    } else {\n        if(this.maxPrice === this.stocksPrice[index] || \n           this.minPrice === this.stocksPrice[index]) {\n            this.stocksPrice[index]=price\n            this.maxPrice=Math.max(...this.stocksPrice)\n            this.minPrice=Math.min(...this.stocksPrice)\n        } else {\n            this.stocksPrice[index]=price\n            this.maxPrice=Math.max(this.maxPrice, price)\n            this.minPrice=Math.min(this.minPrice, price)\n        }\n    }\n    \n    if(timestamp >= this.lastPrice[0])  this.lastPrice=[timestamp, price] \n};\n\n/**\n * @return {number}\n */\nStockPrice.prototype.current = function() {\n    return this.lastPrice[1];\n};\n\n/**\n * @return {number}\n */\nStockPrice.prototype.maximum = function() {\n    return this.maxPrice\n};\n\n/**\n * @return {number}\n */\nStockPrice.prototype.minimum = function() {\n    return this.minPrice\n};\n\n/** \n * Your StockPrice object will be instantiated and called as such:\n * var obj = new StockPrice()\n * obj.update(timestamp,price)\n * var param_2 = obj.current()\n * var param_3 = obj.maximum()\n * var param_4 = obj.minimum()\n */",879        "solution_java": "class StockRecord {\n    int timestamp;\n    int price;\n    \n    public StockRecord(){}\n    \n    public StockRecord(int t, int p) {\n        timestamp = t;\n        price = p;\n    }\n}\n\nclass StockPrice {\n    \n    PriorityQueue<StockRecord> max = new PriorityQueue<>((sr1, sr2) -> (sr2.price - sr1.price));\n    PriorityQueue<StockRecord> min = new PriorityQueue<>((sr1, sr2) -> (sr1.price - sr2.price));\n    StockRecord current_record;\n    Map<Integer, Integer> map = new HashMap<>();\n\n    \n    public StockPrice() {\n        current_record = new StockRecord();\n    }\n    \n    public void update(int timestamp, int price) {\n        if(timestamp >= current_record.timestamp) {\n            current_record.timestamp = timestamp;\n            current_record.price = price;\n        }\n        \n        StockRecord sr = new StockRecord(timestamp, price);\n        max.add(sr);\n        min.add(sr);\n        map.put(timestamp, price);\n    }\n    \n    public int current() {\n        return current_record.price;\n    }\n    \n    public int maximum() {\n        StockRecord sp = max.peek();\n        while(true) {\n            sp = max.peek();\n            if(sp.price != map.get(sp.timestamp))\n                max.poll();\n            else break;\n        }\n        return sp.price;\n    }\n    \n    public int minimum() {\n        StockRecord sp = min.peek();\n         while(true) {\n            sp = min.peek();\n            if(sp.price != map.get(sp.timestamp))\n                min.poll();\n            else break;\n        }\n        return sp.price;\n    }\n}",880        "solution_c": "class StockPrice {\n    map<int, int> stock; \n    map<int, int> prices;\n    pair<int, int> currentStock = {-1, -1};\npublic:\n    \n    StockPrice() {\n        \n    }\n    \n    void update(int timestamp, int price) {\n\t\n\t\t// Update current stock price if we get a new greater timestamp\n        if(timestamp >= currentStock.first) {\n            currentStock = {timestamp, price};\n        }\n        \n        if(stock.find(timestamp) != stock.end()) {\n\t\t\t// Case 2\n            int old_price = stock[timestamp];  // Get old price for timestamp\n            \n            prices[old_price]--;  // Reduce count \n            if(prices[old_price] == 0) prices.erase(old_price); // Remove if no timestamp has old price\n        }\n        \n\t\t// Case 1\n        prices[price]++;  \n        stocks[timestamp] = price;   \n        \n    }\n    \n    int current() {\n        return currentStock.second;\n    }\n    \n    int maximum() {\n\t\t\treturn prices.rbegin()->first;  // GET last element\n    }\n    \n    int minimum() {\n        return prices.begin()->first; // Get first element\n    }\n};"881    },882    {883        "title": "Flip Equivalent Binary Trees",884        "algo_input": "For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.\n\nA binary tree X&nbsp;is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.\n\nGiven the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput: true\nExplanation: We flipped at nodes with values 1, 3, and 5.\n\n\nExample 2:\n\nInput: root1 = [], root2 = []\nOutput: true\n\n\nExample 3:\n\nInput: root1 = [], root2 = [1]\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in each tree is in the range [0, 100].\n\tEach tree will have unique node values in the range [0, 99].\n\n",885        "solution_py": "class Solution:\n    def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n        def swap(root):\n            if root.right is None or (root.left is not None and root.left.val > root.right.val):\n                root.left, root.right = root.right, root.left\n        \n        def equal(root1, root2):\n            if root1 is None or root2 is None:\n                return root1 is None and root2 is None\n            \n            swap(root1)\n            swap(root2)\n            \n            return (root1.val == root2.val and\n                    equal(root1.left, root2.left) and\n                    equal(root1.right, root2.right))\n        \n        return equal(root1, root2)",886        "solution_js": "var flipEquiv = function(root1, root2) {\n    const flipEquivHelper = (r1 = root1, r2 = root2) => {\n        if(!r1 && !r2) return true;\n        \n        if(!r1 || !r2) return false;\n        \n        if(r1.val != r2.val) return false;\n        \n        let ans = false;\n        // normal\n        ans = ans || (\n            flipEquivHelper(r1.left, r2.left) && \n            flipEquivHelper(r1.right, r2.right)\n        );\n        // flip\n        ans = ans || (\n            flipEquivHelper(r1.right, r2.left) && \n            flipEquivHelper(r1.left, r2.right)\n        );\n        return ans;\n    }\n    return flipEquivHelper();\n};",887        "solution_java": "class Solution {\n    public boolean flipEquiv(TreeNode root1, TreeNode root2) {\n        return helper(root1, root2);\n    }\n    \n    private boolean helper(TreeNode x, TreeNode y)\n    {\n        if(x == null && y == null) return true;\n        if(x == null || y == null || x.val != y.val) return false;\n        boolean similarity = helper(x.left, y.left) && helper(x.right, y.right); // check if 2 subtrees are similar\n        boolean swap = helper(x.left, y.right) && helper(x.right, y.left); // check if the 2 subtrees can be similar after swapping the left & right subtrees with each other\n        \n        return similarity || swap; // if either true, means we can flip to match both trees\n    }\n}",888        "solution_c": "class Solution {\npublic:\n    bool flipEquiv(TreeNode* root1, TreeNode* root2) {\n        if (root1 == NULL && root2 == NULL)\n            return true;\n        else if (root1 == NULL || root2 == NULL)\n            return false;\n        else if (root1 -> val != root2 -> val)\n            return false;\n\n        return (flipEquiv(root1 -> left, root2 -> right) && flipEquiv(root1 -> right, root2 -> left)) || (flipEquiv(root1 -> left, root2 -> left) && flipEquiv(root1 -> right, root2 -> right));\n    }\n};"889    },890    {891        "title": "Array of Doubled Pairs",892        "algo_input": "Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 &lt;= i &lt; len(arr) / 2, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: arr = [3,1,3,6]\nOutput: false\n\n\nExample 2:\n\nInput: arr = [2,1,2,6]\nOutput: false\n\n\nExample 3:\n\nInput: arr = [4,-2,2,-4]\nOutput: true\nExplanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= arr.length &lt;= 3 * 104\n\tarr.length is even.\n\t-105 &lt;= arr[i] &lt;= 105\n\n",893        "solution_py": "class Solution:\n    def canReorderDoubled(self, arr: List[int]) -> bool:\n        n = len(arr)\n        arr.sort()\n        times = n//2\n        count = {}\n        for i in arr :\n            if i in count:count[i] += 1\n            else: count[i] = 1\n        for i in count:\n            if i == 0:\n                tmp = count[0]//2\n                times -= tmp\n                if times <=0 : return True\n            else:\n                if i*2 in count:\n                    ct1 = count[i]\n                    ct2 = count[i*2]\n                    while ct1 > 0 and ct2 > 0 and times > 0:\n                        ct1 -= 1\n                        ct2 -= 1\n                        times -= 1\n                    count[i] = ct1\n                    count[i*2] = ct2\n                    if times == 0:return True\n        return False",894        "solution_js": "var canReorderDoubled = function(arr) {\n    const obj = {}\n    let total = 0\n    arr.sort((a,b) => a-b)\n    for (let i = 0; i < arr.length; i++) {\n        const num = arr[i]\n        if (obj[num / 2]) {\n            obj[num / 2]--\n            total++\n        } else if (obj[num * 2]) {\n            obj[num * 2]--\n            total++\n        } else if (obj[num]) {\n            obj[num]++\n        } else {\n            obj[num] = 1\n        }\n    }\n\n    return total >= arr.length / 2\n};",895        "solution_java": "class Solution {\n    public boolean canReorderDoubled(int[] arr) {\n        Map<Integer,Integer> map=new HashMap<>();\n        int zeroCount=0,out=0,len=arr.length;\n        Arrays.sort(arr);\n        for(int ar:arr){\n           if(ar%2==1)\n               map.put(ar,map.getOrDefault(ar,0)+1);\n           else\n           {\n               if(ar>0)\n               {\n                   int val=map.getOrDefault(ar/2,0);\n                   if(val>0){\n                       out++;\n                       map.put(ar/2,val-1);\n                   }\n                   else map.put(ar,map.getOrDefault(ar,0)+1);\n               }\n               else if(ar<0)\n               {\n                  int val=map.getOrDefault(ar2,0);\n                   if(val>0){\n                       out++;\n                       map.put(ar2,val-1);\n                   } \n                   else map.put(ar,map.getOrDefault(ar,0)+1);\n               }\n               else zeroCount++;   \n           }\n        }\n        zeroCount=zeroCount/2;\n        return out+zeroCount==len/2;\n    }\n}",896        "solution_c": "class Solution {\npublic:\n    bool func(vector<int> pos){\n        map<int,int> mp;\n        for(int i=0;i<pos.size();i++){\n            mp[pos[i]]++;\n        }\n\n        for(auto it:mp){\n            if(mp.find(2*it.first)==mp.end()){\n                return false;\n            }\n            if(mp[it.first]>mp[2*it.first]){\n                return false;\n            }\n            mp[2*it.first]-=mp[it.first];\n            if(mp[2*it.first]==0)\n                mp.erase(2*it.first);\n        }\n\n        return true;\n    }\n\n    bool canReorderDoubled(vector<int>& arr) {\n        int n=arr.size();\n        vector<int> pos,neg;\n        int zeroes=0;\n        for(int i:arr){\n            if(i>0){\n                pos.push_back(i);\n            }else if(i<0){\n                neg.push_back(i);\n            }else{\n                zeroes++;\n            }\n        }\n\n        if(zeroes%2!=0){\n            return false;\n        }\n\n        if(neg.size()%2!=0 or pos.size()%2!=0){\n            return false;\n        }\n\n        for(int i=0;i<neg.size();i++){\n            neg[i]=-1*neg[i];\n        }\n\n        sort(pos.begin(),pos.end());\n        sort(neg.begin(),neg.end());\n        return func(pos) and func(neg);\n    }\n};"897    },898    {899        "title": "Count Submatrices With All Ones",900        "algo_input": "Given an m x n binary matrix mat, return the number of submatrices that have all ones.\n\n&nbsp;\nExample 1:\n\nInput: mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput: 13\nExplanation: \nThere are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.\n\n\nExample 2:\n\nInput: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput: 24\nExplanation: \nThere are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 150\n\tmat[i][j] is either 0 or 1.\n\n",901        "solution_py": "class Solution:\n    def numSubmat(self, mat: List[List[int]]) -> int:\n        from dataclasses import dataclass\n        @dataclass\n        class Cell:\n            left: int = 0\n            top: int = 0\n            \n        n = len(mat)\n        m = len(mat[0])  \n        dp = [[Cell() for _ in range(m + 1)] for _ in range(n + 1)]\n        \n        ans = 0\n        for i in range(1, n + 1):\n            for j in range(1, m + 1):\n                if mat[i - 1][j - 1]: \n                    dp[i][j].top = 1 + dp[i - 1][j].top\n                    dp[i][j].left = 1 + dp[i][j - 1].left\n                    \n                    min_height = dp[i][j].top\n                    for k in range(dp[i][j].left):\n                        min_height = min(min_height, dp[i][j-k].top)\n                        ans += min_height \n        return ans",902        "solution_js": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nvar numSubmat = function(mat) {\n    var m = mat.length;\n    var n = mat[0].length;\n\n    for(let i=0; i<m; i++){\n        for(let j = n-2; j>=0; j-- ){\n            if(mat[i][j] === 0)continue;\n            mat[i][j] += mat[i][j+1];\n\n        }\n    }\n    var sum = 0\n    for(let i=0; i<m; i++){\n        for(let j = 0; j<n; j++ ){\n            if(mat[i][j] === 0)continue;\n            var min = mat[i][j]\n\n            for(let k=i; k<m; k++){\n                if(mat[k][j] === 0)break;\n                min = Math.min(min , mat[k][j])\n                sum += min\n            }\n        }\n\n    }\n    return sum\n};",903        "solution_java": "class Solution {\n\tpublic int numSubmat(int[][] mat) {\n\t\tint n = mat.length;\n\t\tint m = mat[0].length;\n\t\t//left[i][j] indicates how many consecutive 1s are on the left of i, j\n\t\t//left[i][j] indicates how many consecutive 1s are above i, j\n\t\t//dp[i][j] represents the number of submatrices with i, j as the lower right corner\n\t\tint[][] left = new int[n][m];\n\t\tint[][] up = new int[n][m];\n\t\tint[][] dp = new int[n][m];\n\t\tup[0][0] = mat[0][0];\n\t\tleft[0][0] = mat[0][0];\n\t\tdp[0][0] = mat[0][0];\n\t\tfor(int i = 1; i < n; i++){\n\t\t\tif(mat[i][0] == 0){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tup[i][0] = mat[i][0];\n\t\t\tleft[i][0] = left[i - 1][0] + 1;\n\t\t\tdp[i][0] = left[i][0];\n\t\t}\n\n\t\tfor(int j = 1; j < m; j++){\n\t\t\tif(mat[0][j] == 0){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tup[0][j] = up[0][j - 1] + 1;\n\t\t\tleft[0][j] = mat[0][j];\n\t\t\tdp[0][j] = up[0][j];\n\t\t}\n\n\t\tfor(int i = 1; i < n; i++){\n\t\t\tfor(int j = 1; j < m; j++){\n\t\t\t\tif(mat[i][j] == 0){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tup[i][j] = up[i][j - 1] + 1;\n\t\t\t\tleft[i][j] = left[i - 1][j] + 1;\n\t\t\t\tint minHeight = up[i][j];\n\t\t\t\tfor(int k = 0; k < left[i][j]; k++){\n\t\t\t\t\tminHeight = Math.min(minHeight, up[i - k][j]);\n\t\t\t\t\tdp[i][j] += minHeight;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint res = 0;\n\t\tfor(int i = 0; i < n; i++){\n\t\t\tfor(int j = 0; j < m; j++){\n\t\t\t\tres += dp[i][j];\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n}",904        "solution_c": "class Solution {\npublic:\n    int numSubmat(vector<vector<int>>& mat) {\n        int n = mat.size(), m = mat[0].size();\n        vector<vector<int>> v(n,vector<int>(m+1,0));\n        for(int i=0; i<n; i++){\n            for(int j=0; j<m; j++){\n                v[i][j+1] = v[i][j] + mat[i][j];\n            }\n        }\n        int res = 0;\n        for(int i=0; i<m; i++){\n            for(int j=i+1; j<=m; j++){\n                int cnt = 0;\n                for(int k=0; k<n; k++){\n                    int x = v[k][j] - v[k][i];\n                    if(x == (j-i)){\n                        cnt++;\n                    }else{\n                        res += cnt*(cnt+1)/2;\n                        cnt = 0;\n                    }\n                }\n                res += cnt*(cnt+1)/2;\n            }\n        }\n        return res;\n    }\n};"905    },906    {907        "title": "Partition Array for Maximum Sum",908        "algo_input": "Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.\n\nReturn the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.\n\n&nbsp;\nExample 1:\n\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\n\n\nExample 2:\n\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\n\n\nExample 3:\n\nInput: arr = [1], k = 1\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 500\n\t0 &lt;= arr[i] &lt;= 109\n\t1 &lt;= k &lt;= arr.length\n\n",909        "solution_py": "class Solution:\n    def maxSumAfterPartitioning(self, nums: List[int], k: int) -> int:\n        def get_max(start, end):\n            return max(nums[start:end + 1]) * (end - start + 1)\n\n        def dfs(start):\n            if start == N: # base case, so in tabulation we go [N - 1]...[0], as [N] = 0\n                return 0\n            \n            maxi = float(-inf)\n\t\t\t# you partition at every position up to start + k and repeat the same process for the next partition\n\t\t\t# e.g. 1 9 3, k = 2\n\t\t\t# 1|9|3 => with max in each partition: 1|9|3 = 13\n\t\t\t# 1|9 3 => with max in each partition: 1|9 9 = 19\n\t\t\t# 1 9|3 => with max in each partition: 9 9|3 = 21\n\t\t\t# get max_in_partition(start,end) + give_me_max_for_array(previous_partition_end + 1, N)\n\t\t\t# rec.relation = max(max_sum_in_partition[start, end] + dfs(end + 1)))\n            for end in range(start, min(N, start + k)):\n                maxi = max(maxi, get_max(start, end) + dfs(end + 1))\n            return maxi\n        \n        N = len(nums)\n        return dfs(0)",910        "solution_js": "/** https://leetcode.com/problems/partition-array-for-maximum-sum/\n * @param {number[]} arr\n * @param {number} k\n * @return {number}\n */\nvar maxSumAfterPartitioning = function(arr, k) {\n  // Array to hold max value for each integer in `arr`\n  let dp = Array(arr.length).fill(0);\n  dp[0] = arr[0];\n  \n  // Calculate max value for each integer\n  for (let i = 1; i < arr.length; i++) {\n    // The `maxK` is largest number from `i` to `i - k - 1`\n    let maxK = 0;\n    \n    // The `maxVal` is for holding max value to be added to `dp[i]`\n    let maxVal = 0;\n    \n    // Loop through `i` to `i - k - 1`\n    for (let j = 1; j <= k; j++) {\n      // Get max number\n      maxK = Math.max(maxK, arr[i - (j - 1)]);\n      \n      // Calculate `maxVal`, if current `i` is smaller than `k`, we don't need to continue\n      if (i < j) {\n        maxVal = Math.max(maxVal, maxK * j);\n        break;\n      }\n      \n      maxVal = Math.max(maxVal, dp[i - j] + (maxK * j));\n    }\n    \n    // Store `maxVal`\n    dp[i] = maxVal;\n  }\n  \n  return dp[dp.length - 1];\n};",911        "solution_java": "class Solution {\n    public int maxSumAfterPartitioning(int[] arr, int k) {\n         return maxSum(arr,k, 0 );\n\n    }\n    public int maxSum(int[] arr, int k, int start) {\n        int curr1 = 0, curr2= 0;\n        int prev = 0;\n        int max = 0;\n\n        Map<String, Integer> memo = new HashMap();\n        //memo.put(\"0,0\", arr[0]);\n\n        for(int i=0; i< arr.length; ++i){\n            //without current element\n            curr1 = prev + arr[i];\n\n            //with current element, find max if p=0...k (since subarray can be longeth of at most k)\n            int tempk = 0, half1 = 0, half2 = 0, temp= 0;\n            for(int p=0; p<=k; ++p){\n                half1 = findMaxSumWithKEle(arr, p , i);\n                tempk = i-p;\n                half2 = memo.get((\"0,\"+tempk)) == null ? 0: memo.get((\"0,\"+tempk));\n                if(temp < half1 + half2){\n                    temp = half1 + half2;\n                }\n            }\n\n            curr2 = temp;\n\n            //find max between curr1 or curr2 - with current elemtn in the subarray or outside the subarray\n            max = (curr1 < curr2) ? curr2:curr1;\n\n            //add in memo\n            String key= \"0,\" + i;\n            memo.put(key, max);\n            System.out.println(\"Max: \" + max + \" from [\" + key + \"]\");\n            prev = max;\n        }\n\n        return max;\n    }\n\n    public static Integer findMaxSumWithKEle(int[] arr, int k, int end) {\n        int max= 0;\n        if(end > arr.length || end<0){\n            return 0;\n        }\n        int c = 0;\n        for(int i=end; i> (end -k ) && i>=0; --i){\n            ++c;\n            if(max < arr[i]){\n                max = arr[i];\n            }\n        }\n        return max *c;\n    }\n}",912        "solution_c": "class Solution {\npublic:\n\n    int get_max(vector<int>&arr , int s , int e ){\n        int mx_val = *max_element(arr.begin() + s , arr.begin() + e + 1);\n        return (e-s + 1 )* mx_val ;\n    }\n\n    int solve( vector<int>&arr , int idx , int k , vector<vector<int>>&dp){\n\n        if(idx >= arr.size() ) return 0;\n\n        if(dp[idx][k] != -1 )\n            return dp[idx][k];\n\n        int ans = 0;\n\n        for(int i = 0 ; i<k ; ++i ){\n            if((idx + i ) > arr.size() - 1)\n                break;\n\n            int val = get_max(arr , idx , idx + i ) + solve( arr , idx + i + 1 , k , dp );\n            ans = max( ans , val );\n        }\n        return dp[idx][k] = ans ;\n\n    }\n\n    int maxSumAfterPartitioning(vector<int>& arr, int k) {\n        vector<vector<int>>dp(arr.size()+1 , vector<int>( k + 1 , -1 ));\n\n        return solve( arr , 0 , k , dp );\n    }\n};"913    },914    {915        "title": "Count Items Matching a Rule",916        "algo_input": "You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.\n\nThe ith item is said to match the rule if one of the following is true:\n\n\n\truleKey == \"type\" and ruleValue == typei.\n\truleKey == \"color\" and ruleValue == colori.\n\truleKey == \"name\" and ruleValue == namei.\n\n\nReturn the number of items that match the given rule.\n\n&nbsp;\nExample 1:\n\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"\nOutput: 1\nExplanation: There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].\n\n\nExample 2:\n\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"\nOutput: 2\nExplanation: There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= items.length &lt;= 104\n\t1 &lt;= typei.length, colori.length, namei.length, ruleValue.length &lt;= 10\n\truleKey is equal to either \"type\", \"color\", or \"name\".\n\tAll strings consist only of lowercase letters.\n\n",917        "solution_py": "class Solution:\n    def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n        d = {'type': 0, 'color': 1, 'name': 2}\n        return sum(1 for item in items if item[d[ruleKey]] == ruleValue)",918        "solution_js": "const RULE_IDX = {\n    'type': 0,\n    'color': 1,\n    'name': 2\n};\n\nvar countMatches = function(items, ruleKey, ruleValue) {\n    return items.reduce((ans, item) => item[RULE_IDX[ruleKey]] === ruleValue ? ans + 1 : ans, 0);\n};",919        "solution_java": "class Solution {\n    public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {\n        int res = 0;\n\n        for(int i = 0 ;i<items.size();i++){\n            if(ruleKey.equals(\"type\") && items.get(i).get(0).equals(ruleValue)) res++;\n            if(ruleKey.equals(\"color\") && items.get(i).get(1).equals(ruleValue)) res++;\n            if(ruleKey.equals(\"name\") && items.get(i).get(2).equals(ruleValue)) res++;\n        }\n\n        return res;\n\n    }\n}",920        "solution_c": "class Solution {\npublic:\n    int countMatches(vector<vector<string>>& items, string ruleKey, string ruleValue) {\n        int i;\n        if(ruleKey==\"type\")i=0;\n        if(ruleKey==\"color\")i=1;\n        if(ruleKey==\"name\")i=2;\n\n        int ans=0;\n        for(int j=0;j<items.size();j++){\n            if(items[j][i]==ruleValue)ans++;\n        }\n\n        return ans;\n    }\n};"921    },922    {923        "title": "Online Stock Span",924        "algo_input": "Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.\n\nThe span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.\n\n\n\tFor example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6].\n\n\nImplement the StockSpanner class:\n\n\n\tStockSpanner() Initializes the object of the class.\n\tint next(int price) Returns the span of the stock's price given that today's price is price.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n[[], [100], [80], [60], [70], [60], [75], [85]]\nOutput\n[null, 1, 1, 1, 2, 1, 4, 6]\n\nExplanation\nStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80);  // return 1\nstockSpanner.next(60);  // return 1\nstockSpanner.next(70);  // return 2\nstockSpanner.next(60);  // return 1\nstockSpanner.next(75);  // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85);  // return 6\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= price &lt;= 105\n\tAt most 104 calls will be made to next.\n\n",925        "solution_py": "class StockSpanner:\n\n    def __init__(self):\n        self.stack = []\n        \n    def next(self, price: int) -> int:\n        \n        ans = 1\n        while self.stack and self.stack[-1][0] <= price:\n            ans += self.stack.pop()[1]\n        \n        self.stack.append((price, ans))\n        \n        return ans\n        \n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)",926        "solution_js": "var StockSpanner = function() {\n    this.stack = [];\n    this.idx = 0;\n};\n\nStockSpanner.prototype.next = function(price) {\n    \n\t// keep Pop-ing if top element of stack is bigger than current price\n    while(this.stack.length > 0 && this.stack[this.stack.length-1][0] <= price){\n        this.stack.pop();\n    }\n    \n\t// if stack is empty after above operation\n    if(this.stack.length === 0){\n\t\n\t\t// Push current price with index\n        this.stack.push([price,this.idx]);\n\t\t\n\t\t// increment index - this is a tricky part\n        this.idx++;\n\t\t\n        return this.idx;\n    }\n    \n\t// caclulate distance from top element of stack and return\n\t\n    const res = this.idx - this.stack[this.stack.length-1][1];\n    this.stack.push([price,this.idx]);\n    this.idx++;\n    return res;\n};",927        "solution_java": "class Pair{\n    int stock;\n    int span;\n    \n    public Pair(int stock, int span){\n        this.stock = stock;\n        this.span = span;\n    }\n    \n}\nclass StockSpanner {\n    Stack<Pair> stack;\n    public StockSpanner() {\n        stack = new Stack<>();\n    }\n    \n    public int next(int price) {\n        int span = 1;\n        while(!stack.isEmpty() && stack.peek().stock <= price){\n           Pair pStock = stack.pop();\n           span += pStock.span ;\n        }\n        stack.push(new Pair(price, span));\n        return span;\n    }\n}\n\n/**\n * Your StockSpanner object will be instantiated and called as such:\n * StockSpanner obj = new StockSpanner();\n * int param_1 = obj.next(price);\n */",928        "solution_c": "class StockSpanner {\npublic:\n    stack<pair<int , int>>s; //val , index\n    vector<int>prices;\n    vector<int>res;\n    StockSpanner() {\n\n    }\n\n    int next(int price) {\n        prices.push_back(price);\n        int n = prices.size();\n        for(int i = n-1 ; i<n ; i++)\n        {\n            while(!s.empty() and s.top().first <= prices[i])\n            {\n                s.pop();\n            }\n            if(s.empty())\n            {\n                res.push_back(i - 0 + 1);\n                s.push({prices[i] , i});\n            }\n            else\n            {\n                auto it = s.top();\n                res.push_back({i - it.second });\n                s.push({prices[i] , i});\n            }\n        }\n        return res[n-1];\n    }\n};"929    },930    {931        "title": "Second Largest Digit in a String",932        "algo_input": "Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.\n\nAn alphanumeric string is a string consisting of lowercase English letters and digits.\n\n&nbsp;\nExample 1:\n\nInput: s = \"dfa12321afd\"\nOutput: 2\nExplanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\n\n\nExample 2:\n\nInput: s = \"abc1111\"\nOutput: -1\nExplanation: The digits that appear in s are [1]. There is no second largest digit. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of only lowercase English letters and/or digits.\n\n",933        "solution_py": "class Solution:\n    def secondHighest(self, s: str) -> int:\n        nums = []\n        for char in s:\n            if char.isdigit():\n                nums.append(int(char))\n        nums = [num for num in nums if num != max(nums)]\n        if len(nums) >= 1: return max(nums)\n        else: return -1",934        "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar secondHighest = function(s) {\n    //let's start by getting rid of all the non-digits\n    let myRegex = /\\D/g\n    s = s.replace(myRegex,'')\n    var digits = s.split('')\n    //at this point, digits is an array of all the digit characters that were originally in s\n    digits.sort(function(a, b){return b - a}) //sort the array into descending order\n    var res = new Set(digits) //turn the array into a set, to remove duplicates\n    if(res.size <=1){\n        //if the set is sized 1, then there is no second largest digit\n        return -1\n    }\n    else{\n        //otherwise, the second largest digit would be at index 1 (because we sorted the array into descending order)\n        return [...res][1]\n    }\n};",935        "solution_java": "class Solution {\n    public int secondHighest(String s) {\n        int[] arr = new int[10];\n        for(int i = 0;i<s.length();i++){\n            if(s.charAt(i) - '0' <=9 & s.charAt(i)-'0' >=0){\n                arr[s.charAt(i)-'0']++;\n            }\n        }\n        boolean first = false;\n        for(int i = 9;i>=0;i--){\n            if(arr[i] !=0){\n                if(first)\n                    return i;\n                else first = true;\n            }\n        }\n\n        return -1;\n    }\n}",936        "solution_c": "class Solution {\npublic:\n    int secondHighest(string s) {\n        // support variables\n        int res[2] = {-1, -1};\n        // parsing s\n        for (char c: s) {\n            // considering only numerical characters\n            if (c >= '0' && c <= '9') {\n                // normalising c\n                c -= '0';\n                // updating res\n                if (c > res[0]) {\n                    res[1] = res[0];\n                    res[0] = c;\n                } else if (c != res[0] && c > res[1]) res[1] = c;\n            }\n        }\n        return res[1];\n    }\n};"937    },938    {939        "title": "Design Underground System",940        "algo_input": "An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.\n\nImplement the UndergroundSystem class:\n\n\n\tvoid checkIn(int id, string stationName, int t)\n\n\t\n\t\tA customer with a card ID equal to id, checks in at the station stationName at time t.\n\t\tA customer can only be checked into one place at a time.\n\t\n\t\n\tvoid checkOut(int id, string stationName, int t)\n\t\n\t\tA customer with a card ID equal to id, checks out from the station stationName at time t.\n\t\n\t\n\tdouble getAverageTime(string startStation, string endStation)\n\t\n\t\tReturns the average time it takes to travel from startStation to endStation.\n\t\tThe average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.\n\t\tThe time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.\n\t\tThere will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.\n\t\n\t\n\n\nYou may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 &lt; t2. All events happen in chronological order.\n\n&nbsp;\nExample 1:\n\nInput\n[\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n[[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]\n\nOutput\n[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, \"Leyton\", 3);\nundergroundSystem.checkIn(32, \"Paradise\", 8);\nundergroundSystem.checkIn(27, \"Leyton\", 10);\nundergroundSystem.checkOut(45, \"Waterloo\", 15);  // Customer 45 \"Leyton\" -&gt; \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20);  // Customer 27 \"Leyton\" -&gt; \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -&gt; \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -&gt; \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 11.00000. Two trips \"Leyton\" -&gt; \"Waterloo\", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, \"Leyton\", 24);\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 11.00000\nundergroundSystem.checkOut(10, \"Waterloo\", 38);  // Customer 10 \"Leyton\" -&gt; \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\");    // return 12.00000. Three trips \"Leyton\" -&gt; \"Waterloo\", (10 + 12 + 14) / 3 = 12\n\n\nExample 2:\n\nInput\n[\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n[[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]\n\nOutput\n[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, \"Leyton\", 3);\nundergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -&gt; \"Paradise\" in 8-3 = 5\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, \"Leyton\", 10);\nundergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -&gt; \"Paradise\" in 16-10 = 6\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, \"Leyton\", 21);\nundergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -&gt; \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= id, t &lt;= 106\n\t1 &lt;= stationName.length, startStation.length, endStation.length &lt;= 10\n\tAll strings consist of uppercase and lowercase English letters and digits.\n\tThere will be at most 2 * 104 calls in total to checkIn, checkOut, and getAverageTime.\n\tAnswers within 10-5 of the actual value will be accepted.\n\n",941        "solution_py": "from collections import defaultdict\nclass UndergroundSystem:\n    def __init__(self):\n        self.checkin = {}\n        self.traveltime = defaultdict(dict)\n\n    def checkIn(self, id: int, stationName: str, t: int) -> None:\n        self.checkin[id] = (stationName, t)\n\n    def checkOut(self, id: int, stationName: str, t: int) -> None:\n        startStation, startTime = self.checkin[id]\n        del self.checkin[id]\n        if stationName not in self.traveltime[startStation]:\n            self.traveltime[startStation][stationName] = []\n        self.traveltime[startStation][stationName].append(t-startTime)\n\n    def getAverageTime(self, startStation: str, endStation: str) -> float:\n        return sum(self.traveltime[startStation][endStation])/len(self.traveltime[startStation][endStation])",942        "solution_js": "var UndergroundSystem = function() {\n    this.checkInMap = {}\n    this.tripMap = {}\n};\n\n/** \n * @param {number} id \n * @param {string} stationName \n * @param {number} t\n * @return {void}\n */\nUndergroundSystem.prototype.checkIn = function(id, stationName, t) {\n    this.checkInMap[id] = [stationName, t]\n};\n\n/** \n * @param {number} id \n * @param {string} stationName \n * @param {number} t\n * @return {void}\n */\nUndergroundSystem.prototype.checkOut = function(id, stationName, t) {\n    const [checkInStationName, checkInTime] = this.checkInMap[id]\n    const tripKey = `${checkInStationName}-${stationName}`\n    \n    if (!this.tripMap[tripKey]) this.tripMap[tripKey] = [0,0]\n    \n    this.tripMap[tripKey][0] += t - checkInTime\n    this.tripMap[tripKey][1]++\n};\n\n/** \n * @param {string} startStation \n * @param {string} endStation\n * @return {number}\n */\nUndergroundSystem.prototype.getAverageTime = function(startStation, endStation) {\n    const tripkey = `${startStation}-${endStation}`\n    const [totalTripTime, totalTrips] = this.tripMap[tripkey]\n    return totalTripTime / totalTrips\n};",943        "solution_java": "class UndergroundSystem {\n    HashMap<Integer, Travel> travelMap;\n    HashMap<String, Averages> avgMap;\n    \n    public UndergroundSystem() {\n        travelMap = new HashMap();\n        avgMap = new HashMap();\n    }\n    \n    public void checkIn(int id, String stationName, int t) {\n        Travel journey = new Travel(id, t, stationName);\n        travelMap.put(id, journey);\n    }\n    \n    public void checkOut(int id, String stationName, int t) {\n        Travel journey = travelMap.get(id);\n        \n        int journeyTime = t - journey.checkIn;\n        String key = journey.startStation + \",\" + stationName;\n        \n        Averages average = avgMap.containsKey(key) ? avgMap.get(key) : new Averages();\n        average.updateAverage(journeyTime);\n        \n        avgMap.put(key, average);\n    }\n    \n    public double getAverageTime(String startStation, String endStation) {\n        String key = startStation + \",\" + endStation;\n        Averages average = avgMap.get(key);\n        \n        int totalTrips = average.totalTrips;\n        double totalJourneytime = average.totalTraveltime;\n        double averageTime = totalJourneytime/totalTrips;\n        \n        return averageTime;\n    }\n    \n    class Travel{\n        int id;\n        String startStation;\n        int checkIn;\n        \n        public Travel(int id, int checkIn, String startStation)\n        {\n            this.id = id;\n            this.checkIn = checkIn;\n            this.startStation = startStation;\n        }\n    }\n    \n    class Averages{\n        double totalTraveltime;\n        int totalTrips;\n        \n        public Averages()\n        {\n            totalTraveltime = 0;\n            totalTrips = 0;\n        }\n        \n        private void updateAverage(int journeyTime)\n        {\n            totalTraveltime += journeyTime;\n            totalTrips++;\n        }\n    }\n}",944        "solution_c": "typedef pair<string, int> PSI;\ntypedef pair<string, string> PSS;\ntypedef vector<int> VI;\ntypedef vector<PSI> VPSI;\ntypedef map<PSS, VI> HPSSVI;\ntypedef map<int, VPSI> HIVPSI;\n\nclass UndergroundSystem {\n    HPSSVI schedule;\n    HIVPSI customer;\npublic:\n    UndergroundSystem() {\n        \n    }\n    \n    void checkIn(int id, string stationName, int t) {\n        customer[id].push_back(make_pair(stationName, t));\n    }\n    \n    void checkOut(int id, string stationName, int t) {\n        auto it=customer.find(id);\n        int idx = it->second.size()-1;\n        schedule[{it->second[idx].first, stationName}].push_back(t - it->second[idx].second);\n    }\n    \n    double getAverageTime(string startStation, string endStation) {\n        double sum=0.0;\n        int s=schedule[{startStation,endStation}].size();\n        auto it=schedule.find({startStation,endStation});\n        for(int i=0;i<s;i++)\n            sum += schedule[{startStation,endStation}][i];\n        return sum/s;\n    }\n};\n\n/**\n * Your UndergroundSystem object will be instantiated and called as such:\n * UndergroundSystem* obj = new UndergroundSystem();\n * obj->checkIn(id,stationName,t);\n * obj->checkOut(id,stationName,t);\n * double param_3 = obj->getAverageTime(startStation,endStation);\n */"945    },946    {947        "title": "Prime Arrangements",948        "algo_input": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)\n\n(Recall that an integer&nbsp;is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers&nbsp;both smaller than it.)\n\nSince the answer may be large, return the answer modulo 10^9 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n\n\nExample 2:\n\nInput: n = 100\nOutput: 682289015\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 100\n\n",949        "solution_py": "class Solution:\n    def numPrimeArrangements(self, n: int) -> int:\n        primes = set()\n        for i in range(2,n+1):\n            if all(i%p != 0 for p in primes):\n                primes.add(i)\n        M = 10**9 + 7\n        def fact(k):\n            res = 1\n            for i in range(2,k+1):\n                res = (res*i)%M\n            return res\n        return fact(len(primes))*fact(n-len(primes))%M",950        "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\n\nvar findNoOfPrimes = function(n){\n    let isPrime = new Array(n+1).fill(true);\n\n    let count =0;\n\n    for(let i=2; i<n;i++){\n        for(let j=i;j<=n;j++){\n            isPrime[j*i]= false;\n        }\n    }\n\n    isPrime.forEach(prime=> {\n        if(prime){\n            count++\n        }\n    })\n\n    return count-2;\n}\n\nvar factorial = function(num){\n    let modulo = Math.pow(10,9) +7;\n\n    if(num<=0)\n        return 1;\n\n    return (BigInt(num) * BigInt(factorial(num-1)))%BigInt(modulo) ;\n}\n\nvar numPrimeArrangements = function(n) {\n\n    let modulo = BigInt(Math.pow(10,9) +7);\n\n    let count = findNoOfPrimes(n);\n\n    let factorialPrime = factorial(count);\n\n    let factorialComposite = factorial(n-count);\n\n    return (BigInt(factorialPrime)*BigInt(factorialComposite))% (modulo);\n};",951        "solution_java": "class Solution {\n     long mod = (long)(1e9+7);\n    public int numPrimeArrangements(int n) {\n        if(n==1){\n            return 1;\n        }\n     \n        boolean[] arr = new boolean[n+1];\n        Arrays.fill(arr,true);\n        arr[0]=false;\n        arr[1]=false;\n        \n        for(int i=2;i<=Math.sqrt(n);i++){\n            \n            for(int j=i*i;j<=n;j+=i){\n                if(arr[i]==false){\n                    continue;\n                }\n                arr[j]=false;\n            }\n            \n        }\n       long prime = 0;\n        long notPrime=0;\n        for(int k=1;k<arr.length;k++){\n            if(arr[k]==true){\n                prime++;\n            }\n            else{\n                notPrime++;\n            }\n        }\n\n       long x = factorial(prime)%mod;\n       long y = factorial(notPrime)%mod;\n       long t = (x*y)%mod;\n        return (int)t ;\n        \n    }\n \n    public long factorial(long i){\n        if(i<=1){\n            return i;\n        }\n        return (i*(factorial(i-1)%mod))%mod;\n    }\n}",952        "solution_c": "class Solution {\npublic:\n    bool isPrime(int x) {\n        if(x <= 3) return x > 1;\n        if(x % 2 == 0) return false;\n        \n        for(int i = 3; i <= sqrt(x); i += 2) {\n            if(x % i == 0) return false;\n        }\n        return true;\n    }\n    \n    int fact(int x) {\n        if(x <= 1) return 1;\n        return ((long long)(x) * fact(x - 1)) % 1000000007;\n    }\n    \n    int numPrimeArrangements(int n) {\n        int c = 0;\n        for(int i = 1; i <= n; ++i) {\n            c += isPrime(i);\n        }\n        return ((long long)(fact(n - c)) * fact(c)) % 1000000007;\n    }\n};"953    },954    {955        "title": "Vowels of All Substrings",956        "algo_input": "Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.\n\nA substring is a contiguous (non-empty) sequence of characters within a string.\n\nNote: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.\n\n&nbsp;\nExample 1:\n\nInput: word = \"aba\"\nOutput: 6\nExplanation: \nAll possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. \n\n\nExample 2:\n\nInput: word = \"abc\"\nOutput: 3\nExplanation: \nAll possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.\n\n\nExample 3:\n\nInput: word = \"ltcd\"\nOutput: 0\nExplanation: There are no vowels in any substring of \"ltcd\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 105\n\tword consists of lowercase English letters.\n\n",957        "solution_py": "class Solution:\n    def countVowels(self, word: str) -> int:\n        count = vowelIndexSum = 0\n        vowels = {'a', 'e', 'i', 'o', 'u'}\n\n        for i, c in enumerate(word, start=1):\n            if c in vowels:\n                vowelIndexSum += i\n            count += vowelIndexSum\n        \n        return count",958        "solution_js": "var countVowels = function(word) {\n    const vowels = new Set(['a', 'e', 'i', 'o', 'u']);\n    let total = 0;\n    let count = 0;\n    for (let i = 0; i < word.length; i++) {\n        if (vowels.has(word[i])) {\n            count += i + 1;\n        }\n        total += count;\n    }\n    return total;\n};",959        "solution_java": "class Solution {\n\n    boolean isVowel(char ch) {\n        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';\n    }\n\n    public long countVowels(String word) {\n        long count = 0;\n        int len = word.length();\n\n        for(int pos = 0; pos < len; pos++) {\n            if(isVowel(word.charAt(pos))) {\n                count += (long)(len - pos) * (long)(pos + 1);\n            }\n        }\n\n        return count;\n    }\n}",960        "solution_c": "class Solution {\npublic:\n    bool isVowel(char ch) {\n        return ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u';\n    }\n\n    long long countVowels(string word) {\n        long long count = 0;\n        int len = word.size();\n\n        for(int pos = 0; pos < len; pos++) {\n            if(isVowel(word[pos])) {\n                count += (long)(len - pos) * (long)(pos + 1);\n            }\n        }\n\n        return count;\n    }\n};"961    },962    {963        "title": "Jump Game V",964        "algo_input": "Given an array of&nbsp;integers arr and an integer d. In one step you can jump from index i to index:\n\n\n\ti + x where:&nbsp;i + x &lt; arr.length and  0 &lt;&nbsp;x &lt;= d.\n\ti - x where:&nbsp;i - x &gt;= 0 and  0 &lt;&nbsp;x &lt;= d.\n\n\nIn addition, you can only jump from index i to index j&nbsp;if arr[i] &gt; arr[j] and arr[i] &gt; arr[k] for all indices k between i and j (More formally min(i,&nbsp;j) &lt; k &lt; max(i, j)).\n\nYou can choose any index of the array and start jumping. Return the maximum number of indices&nbsp;you can visit.\n\nNotice that you can not jump outside of the array at any time.\n\n&nbsp;\nExample 1:\n\nInput: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput: 4\nExplanation: You can start at index 10. You can jump 10 --&gt; 8 --&gt; 6 --&gt; 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 &gt; 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 &gt; 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.\n\n\nExample 2:\n\nInput: arr = [3,3,3,3,3], d = 3\nOutput: 1\nExplanation: You can start at any index. You always cannot jump to any index.\n\n\nExample 3:\n\nInput: arr = [7,6,5,4,3,2,1], d = 1\nOutput: 7\nExplanation: Start at index 0. You can visit all the indicies. \n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 1000\n\t1 &lt;= arr[i] &lt;= 105\n\t1 &lt;= d &lt;= arr.length\n\n",965        "solution_py": "class Solution:\n    def maxJumps(self, arr: List[int], d: int) -> int:\n        n = len(arr)\n        sorted_arr = []\n        for i in range(n):\n            sorted_arr.append((arr[i], i))\n        sorted_arr.sort(reverse = True)\n        depth = [1 for i in range(n)]\n        while(sorted_arr):\n            val, i = sorted_arr.pop()\n            for j in range(i-1, max(-1, i-d-1), -1):\n                if(arr[j] >= arr[i]):\n                    break\n                depth[i] = max(depth[j] + 1, depth[i])\n            for j in range(i+1, min(n, i+d+1)):\n                if(arr[j] >= arr[i]):\n                    break\n                depth[i] = max(depth[j] + 1, depth[i])\n        return max(depth)",966        "solution_js": "var maxJumps = function(arr, d) {\n\n    let n = arr.length;\n    let dp = new Array(n).fill(0);\n    let result = 0;\n\n    // Time complexity:\n    // O(nlogn) + O(n*d) => O(ologn)\n\n    // First we sort the arr (small -> large) , then calculating DP by sortedArr.\n    // O(nlogn)\n    let sortedArr = arr.map((v,i)=>([v,i])).sort((a,b)=>a[0]-b[0]);\n\n    // Shifting with single way\n    // mid -> left ; mid -> right\n    // O(n*d)\n    for(let index=1 ; index< n; index++){\n        let [v,i] = sortedArr[index];\n\n        for(let shift =1 ; shift <=d ; shift++){\n            if(i+shift >= n || arr[i+shift] >= arr[i]) break;\n            dp[i] = Math.max(dp[i],dp[i+shift]+1);\n            if(dp[i] > result) result = dp[i];\n        };\n\n        for(let shift=-1 ; shift >= -d; shift--){\n            if(i+shift < 0 || arr[i+shift] >= arr[i]) break;\n            dp[i] = Math.max(dp[i],dp[i+shift]+1);\n            if(dp[i] > result) result = dp[i];\n        };\n    };\n\n    return result+1;\n\n};",967        "solution_java": "class Solution {\n    public int maxJumps(int[] arr, int d) {\n        List jumpsFrom[] =  new List[arr.length];  //find all possible jumps from each spot\n        findJumps (arr,d,true,jumpsFrom); // add left jumps (itareting left to right)\n        findJumps (arr,d,false,jumpsFrom); // add right jumps\n        int jumpChain[] = new int[arr.length] , max = 1; // 0 - unvisited\n        for (int i = 0 ; i < arr.length; i++) {\n            if (jumpChain[i] == 0) {\n                jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n                max = Math.max(max, jumpChain[i]);\n            }\n        }\n        return max;\n    }\n\n    private void findJumps(int[] arr, int d, boolean left , List jumpsFrom[]){\n        Stack<Integer> s = new Stack();\n        int i = (left) ? 0 : arr.length - 1;\n        while (i >=0  && i < arr.length){\n            if (left) jumpsFrom[i] = new ArrayList();\n            while (!s.isEmpty() && arr[i] > arr[s.peek()]){ // pop stack until higher step found from left/right, adding all left/right lower jumps from i\n                int lowerIndex = s.pop(); \n                if (Math.abs(i - lowerIndex) <= d) jumpsFrom[i].add(lowerIndex); \n                else s = new Stack(); // past d steps\n            }\n            s.push(i);\n            i += (left) ? 1 : -1;\n        }\n    }\n\n    private int dfs(int[] arr , int jumpChain[], List<Integer> jumpsFrom[], int start){\n        int max = 1;\n        for (int i: jumpsFrom[start]) {\n            if (jumpChain[i] == 0) jumpChain[i] = dfs(arr, jumpChain, jumpsFrom, i);\n            max = Math.max (max , 1 + jumpChain[i]);\n        }\n        return max;\n    }\n\n}",968        "solution_c": "class Solution {\n    vector<int> dp;\n    int countJumps(vector<int>& arr, int i, int d){\n        if(dp[i]!=-1) return dp[i];\n        int jumps = 0;\n        int k = 1;\n        while(k <= d && k + i < arr.size()){\n            if(arr[k+i] < arr[i]){\n                jumps = max(countJumps(arr, k+i, d)+1, jumps);\n                k++;\n            }\n            else{\n                break;\n            }\n        }\n        k = 1;\n        while(k <= d && i - k >= 0){\n            if(arr[i] > arr[i - k]){\n                jumps = max(countJumps(arr, i-k, d)+1, jumps);\n                k++;\n            }\n            else{\n                break;\n            }\n        }\n        return dp[i] = jumps;\n    }\npublic:\n    int maxJumps(vector<int>& arr, int d) {\n        dp.resize(arr.size(), -1);\n        int maxJumps = 0;\n        int n = arr.size();\n        for(int i = 0; i < n; i++){\n            maxJumps = max(countJumps(arr, i, d), maxJumps);\n        }\n        return maxJumps + 1;\n    }\n};"969    },970    {971        "title": "Count and Say",972        "algo_input": "The count-and-say sequence is a sequence of digit strings defined by the recursive formula:\n\n\n\tcountAndSay(1) = \"1\"\n\tcountAndSay(n) is the way you would \"say\" the digit string from countAndSay(n-1), which is then converted into a different digit string.\n\n\nTo determine how you \"say\" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.\n\nFor example, the saying and conversion for digit string \"3322251\":\n\nGiven a positive integer n, return the nth term of the count-and-say sequence.\n\n&nbsp;\nExample 1:\n\nInput: n = 1\nOutput: \"1\"\nExplanation: This is the base case.\n\n\nExample 2:\n\nInput: n = 4\nOutput: \"1211\"\nExplanation:\ncountAndSay(1) = \"1\"\ncountAndSay(2) = say \"1\" = one 1 = \"11\"\ncountAndSay(3) = say \"11\" = two 1's = \"21\"\ncountAndSay(4) = say \"21\" = one 2 + one 1 = \"12\" + \"11\" = \"1211\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 30\n\n",973        "solution_py": "class Solution:\n    def countAndSay(self, n: int) -> str:\n        if n==1:\n            return \"1\"\n        \n        x=self.countAndSay(n-1)\n        count=1\n        cur=x[0]\n        res=\"\"\n        for i in range(1,len(x)):\n            if cur==x[i]:\n                count+=1\n            else:\n                res+=str(count)+str(cur)\n                count=1\n                cur=x[i]\n                \n        res+=str(count)+str(cur)\n        return res",974        "solution_js": "var countAndSay = function(n) {\n    if(n==1) return '1';\n    let index = 1, num = '1';\n    while(index < n){\n        num = say(num);\n        index++;\n    }\n    return num;\n};\n\nfunction say(num) {\n    let prev = num[num.length-1], count = 0, newNum = '';\n    for(let index = num.length-1; index >= 0 ; index--) {\n        if(prev == num[index]) {\n            count++;\n        }\n        else{\n            newNum = ''+count + prev + newNum;\n            count = 1;\n            prev = num[index];\n        }\n    }\n    if(count) {\n        newNum = ''+count + prev + newNum;\n    }\n    return newNum;\n}",975        "solution_java": "class Solution {\n    public String countSay(int n, String[] mapper) {\n        if (n == 1) return mapper[1];\n        else {\n            String say = \"\";\n            if (mapper[n-1] != null) say += mapper[n-1];\n            else say += countSay(n-1, mapper);\n            String count = \"\";\n            int cache = Integer.parseInt(say.substring(0, 1));\n            int cntr = 1;\n            if (say.length() < 2) {\n                count += \"1\" + Integer.toString(cache);\n            } else {\n                for(int i=1;i<say.length();i++) {\n                    if (cache == Integer.parseInt(say.substring(i, i+1))) {\n                        cntr++;\n                        if (i == say.length() - 1) {\n                            count += Integer.toString(cntr) + Integer.toString(cache);\n                            cntr = 1;\n                        }\n                    } else {\n                        count += Integer.toString(cntr) + Integer.toString(cache);\n                        if (i < say.length() - 1) {\n                            cache = Integer.parseInt(say.substring(i, i+1));\n                            cntr = 1;\n                        } else if (i == say.length() - 1) {\n                            count += \"1\" + say.substring(i, i+1);\n                        }\n                    }\n                }\n            }\n            mapper[n] = count;\n            return mapper[n];\n        }\n    }\n    public String countAndSay(int n) {\n        String mapper[] = new String[n+1];\n        mapper[1] = \"1\";\n        return countSay(n, mapper);\n    }\n}",976        "solution_c": "class Solution {\npublic:\n    string countAndSay(int n) {\n        if(n == 1)\n            return \"1\";\n        else\n        {\n            string ans = \"\";\n            string temp = countAndSay(n-1);\n            int count = 1, curr = temp[0], i = 1;\n            while(i < temp.length())\n            {\n                if(temp[i] == curr)\n                    count++;\n                else\n                {\n                    ans += to_string(count);\n                    ans += curr;\n                    count = 1;\n                    curr = temp[i];\n                }\n                i++;\n            }\n            ans += to_string(count);\n            ans += curr;\n\n            return ans;\n        }\n\n    }\n};"977    },978    {979        "title": "Cyclically Rotating a Grid",980        "algo_input": "You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k.\n\nThe matrix is composed of several layers, which is shown in the below image, where each color is its own layer:\n\n\n\nA cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:\n\nReturn the matrix after applying k cyclic rotations to it.\n\n&nbsp;\nExample 1:\n\nInput: grid = [[40,10],[30,20]], k = 1\nOutput: [[10,20],[40,30]]\nExplanation: The figures above represent the grid at every state.\n\n\nExample 2:\n  \n\nInput: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\nOutput: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\nExplanation: The figures above represent the grid at every state.\n\n\n&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t2 &lt;= m, n &lt;= 50\n\tBoth m and n are even integers.\n\t1 &lt;= grid[i][j] &lt;= 5000\n\t1 &lt;= k &lt;= 109\n",981        "solution_py": "class Solution:\n    def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n        n = len(grid)\n        m = len(grid[0])\n        \n        i, j = 0, 0\n        bottom, right = n-1, m-1 \n        while i < n//2 and j < m//2:\n            temp = []\n            for x in range(j, right):\n                temp.append(grid[i][x])\n            for x in range(i, bottom):\n                temp.append(grid[x][right])\n            for x in range(right, j, -1):\n                temp.append(grid[bottom][x])\n            for x in range(bottom, i, -1):\n                temp.append(grid[x][j])\n                \n            \n            indx = 0\n            for x in range(j, right):\n                grid[i][x] = temp[(k + indx)%len(temp)]\n                indx += 1\n            for x in range(i, bottom):\n                grid[x][right] = temp[(k + indx)%len(temp)]\n                indx += 1\n            for x in range(right, j, -1):\n                grid[bottom][x] = temp[(k + indx)%len(temp)]\n                indx += 1\n            for x in range(bottom, i, -1):\n                grid[x][j] = temp[(k + indx)%len(temp)]\n                indx += 1\n                \n            i += 1\n            j += 1\n            bottom -= 1\n            right -= 1\n        return grid",982        "solution_js": "var rotateGrid = function(grid, k) {\n    const m = grid.length;\n    const n = grid[0].length;\n    \n    let startRow = 0;\n    let endRow = m - 1;\n    \n    let startCol = 0;\n    let endCol = n - 1;\n    \n    while (startRow <= endRow && startCol <= endCol) {\n        let currRowStart = startRow;\n        let currRowEnd = endRow;\n\n        let currColStart = startCol;\n        let currColEnd = endCol;\n\n        const vals = [];\n\n        // Top\n        for (let col = currColStart; col <= currColEnd; ++col) {\n            const val = grid[currRowStart][col];\n            vals.push(val);\n        }\n        ++currRowStart;\n\n        // Right\n        for (let row = currRowStart; row <= currRowEnd; ++row) {\n            const val = grid[row][currColEnd];\n            vals.push(val);\n        }\n        --currColEnd;\n\n        // Bottom\n        for (let col = currColEnd; col >= currColStart; --col) {\n            const val = grid[currRowEnd][col];\n            vals.push(val);\n        }\n        --currRowEnd;\n\n        // Left\n        for (let row = currRowEnd; row >= currRowStart; --row) {\n            const val = grid[row][currColStart];\n            vals.push(val);\n        }\n        ++currColStart;\n\n        const size = vals.length;\n        const remK = k % size;\n\n        const movedVals = [];\n\n        for (let i = 0; i < size; ++i) {\n            const movedIdx = (i + remK) % size;\n            movedVals[i] = vals[movedIdx];\n        }\n\n        let i = 0;\n\n        currRowStart = startRow;\n        currRowEnd = endRow;\n\n        currColStart = startCol;\n        currColEnd = endCol;\n\n        // Top\n        for (let col = currColStart; col <= currColEnd; ++col) {\n            grid[currRowStart][col] = movedVals[i++];\n        }\n        ++currRowStart;\n\n        // Right\n        for (let row = currRowStart; row <= currRowEnd; ++row) {\n            grid[row][currColEnd] = movedVals[i++];\n        }\n        --currColEnd;\n\n        // Bottom\n        for (let col = currColEnd; col >= currColStart; --col) {\n            grid[currRowEnd][col] = movedVals[i++];\n        }\n        --currRowEnd;\n\n        // Left\n        for (let row = currRowEnd; row >= currRowStart; --row) {\n            grid[row][currColStart] = movedVals[i++];\n        }\n        ++currColStart;\n\n        // update the boundaries for the next layer\n        startRow = currRowStart;\n        endRow = currRowEnd;\n\n        startCol = currColStart;\n        endCol = currColEnd;\n    }\n    \n   return grid;\n};",983        "solution_java": "class Solution {\n    public int[][] rotateGrid(int[][] grid, int k) {\n        int m = grid.length, n = grid[0].length, noOfLayers = Math.min(m/2, n/2); \n        // Peeling each layer one by one\n        for(int layerNo = 0; layerNo < noOfLayers; layerNo++){\n            // Please suggest if you have better way to find perimeter of matrix on a given layer!\n            int perimeter = (m-(2*layerNo)) + (n-(2*layerNo)-1) + (m-(2*layerNo)-1) + (n-(2*layerNo)-2); \n            int[] layer = new int[perimeter]; // this out be use to store that particular layer\n            readLayer(grid, layer, layerNo, m, n); // this will read the layer\n            writeLayer(grid, layer, layerNo, m, n, k); // this will rotate it by k and write back the layer  \n        }\n        return grid;\n    }\n    \n    public void readLayer(int[][] grid, int[] layer, int layerNo, int m, int n){\n        int count = 0, r = layerNo, c = layerNo;\n        m--; n--;\n        // read left a -> c\n        for(int i = layerNo; i < n - layerNo; i++) layer[count++] = grid[layerNo][i];\n        // read down c -> i\n        for(int i = layerNo; i < m - layerNo; i++) layer[count++] = grid[i][n-layerNo];\n        // read right i -> g\n        for(int i = n-layerNo; i > layerNo; i--) layer[count++] = grid[m-layerNo][i];\n        // read up g -> a\n        for(int i = m-layerNo; i > layerNo; i--) layer[count++] = grid[i][layerNo];\n    }\n    \n    public void writeLayer(int[][] grid, int[] layer, int layerNo, int m, int n, int k){\n         m--; n--;\n        int len = layer.length, count = k; \n        // write left a -> c\n        for(int i = layerNo; i < n - layerNo; i++){\n            count %= len; // reason if goes out of length start back from 0\n            grid[layerNo][i] = layer[count++];\n        }\n        // write down c -> i\n        for(int i = layerNo; i < m - layerNo; i++){\n            count %= len;\n            grid[i][n-layerNo] = layer[count++];\n        } \n        // write right i -> g\n        for(int i = n-layerNo; i > layerNo; i--){\n            count %= len;\n            grid[m-layerNo][i] = layer[count++];\n        }\n        // write up g -> a\n        for(int i = m-layerNo; i > layerNo; i--){\n            count %= len;\n            grid[i][layerNo] = layer[count++];\n        } \n    }\n    \n   \n}",984        "solution_c": "const vector<pair<int, int>> directions{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};\n\nclass Solution\n{\nprotected:\n    int n, m;\n\n    int whichLayer(int x, int y) {\n        if (x < 0 || y < 0 || x >= n || y >= m) return -1;\n        int i = min(x, n - x - 1);\n        int j = min(y, m - y - 1);\n        return min(i, j);\n    }\n\n    void nextPos(int x, int y, int dir, int& nx, int& ny) {\n        nx = x + directions[dir].first;\n        ny = y + directions[dir].second;\n    }\n\n    // Go to next position in the current layer (in clockwise order)\n    void advancePosition(int& x, int& y, int& d) {\n        int nx, ny;\n        nextPos(x, y, d, nx, ny);\n        if (whichLayer(nx, ny) != whichLayer(x, y)) {\n            // Change direction\n            d = (d + 1) % 4;\n            nextPos(x, y, d, nx, ny);\n        }\n        x = nx; y = ny;\n    }\n\npublic:\n    vector<vector<int>> rotateGrid(vector<vector<int>>& grid, int k)\n    {\n        // Check validity of the arguments\n        if (grid.empty()) throw invalid_argument(\"empty grid\");\n        m = grid.size();\n        n = grid[0].size();\n        if (n == 0) throw invalid_argument(\"empty grid\");\n        if (k < 0) throw invalid_argument(\"negative k not accepted\");\n\n        // Trivial case\n        if (k == 0) return grid;\n\n        const int L = min(n, m) / 2;\n        for (int l = 0; l < L; l++) {\n            vector<int> v;\n\n            // Flatten a layer from grid into a vector\n            int j = l, i = l; // start position\n            int d = 0; // direction\n            do {\n                v.push_back(grid[j][i]);\n                advancePosition(i, j, d);\n            } while (!(i == l && j == l)); // until the start position is reached\n\n            // Unflatten rotated vector back into the grid\n            j = l; i = l; // start position\n            d = 0; // direction\n            int off = k % v.size();\n            do {\n                grid[j][i] = v[off];\n                off = (off + 1) % v.size();\n                advancePosition(i, j, d);\n            } while (!(i == l && j == l)); // until the start position is reached\n        }\n\n        return grid;\n    }\n};"985    },986    {987        "title": "Replace Non-Coprime Numbers in Array",988        "algo_input": "You are given an array of integers nums. Perform the following steps:\n\n\n\tFind any two adjacent numbers in nums that are non-coprime.\n\tIf no such numbers are found, stop the process.\n\tOtherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).\n\tRepeat this process as long as you keep finding two adjacent non-coprime numbers.\n\n\nReturn the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.\n\nThe test cases are generated such that the values in the final array are less than or equal to 108.\n\nTwo values x and y are non-coprime if GCD(x, y) &gt; 1 where GCD(x, y) is the Greatest Common Divisor of x and y.\n\n&nbsp;\nExample 1:\n\nInput: nums = [6,4,3,2,7,6,2]\nOutput: [12,7,6]\nExplanation: \n- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.\n\n\nExample 2:\n\nInput: nums = [2,2,1,1,3,3,3]\nOutput: [2,1,1,3]\nExplanation: \n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\tThe test cases are generated such that the values in the final array are less than or equal to 108.\n\n",989        "solution_py": "class Solution:\n    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n        res = []\n        for num in nums:\n            while res and gcd(res[-1], num) > 1:\n                num = lcm(res[-1], num)\n                res.pop()\n            res.append(num)\n        return res",990        "solution_js": "function gcd(a, b) {\n    while (b > 0) {\n        a %= b;\n        [a, b] = [b, a];\n    }\n    return a;\n}\nfunction lcm(a, b) {\n    return a / gcd(a, b) * b;\n}\n\nvar replaceNonCoprimes = function(nums) {\n    let res = new Array();\n    for (let num of nums) {\n        while (res.length > 0 && gcd(res.at(-1), num) > 1) {\n            num = lcm(res.at(-1), num);\n            res.pop();\n        }\n        res.push(num);\n    }\n    return res;\n};",991        "solution_java": "class Solution {\n\tpublic List<Integer> replaceNonCoprimes(int[] nums) \n\t{\n\t\tList<Integer> al=new ArrayList<>();\n\t\tlong n1=nums[0];\n\t\tint idx=1;\n\n\t\twhile(idx<nums.length)\n\t\t{\n\t\t\tif((int)gcd(n1,nums[idx])==1)\n\t\t\t{\n\t\t\t\twhile(al.size()!=0)\n\t\t\t\t{\n\t\t\t\t\tint t=al.get(al.size()-1);\n\t\t\t\t\tif(gcd(n1,t)==1)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tal.remove(al.size()-1);\n\t\t\t\t\t\tn1=lcm(t,n1);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tal.add((int)n1);\n\t\t\t\tn1=nums[idx];\n\t\t\t\tidx++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn1=lcm(n1,nums[idx]);\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\n\t\twhile(al.size()!=0)\n\t\t{\n\t\t\tint t=al.get(al.size()-1);\n\t\t\tif(gcd(n1,t)==1)\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t{\n\t\t\t\tal.remove(al.size()-1);\n\t\t\t\tn1=lcm(t,n1);\n\t\t\t}\n\t\t} \n\t\tal.add((int)n1);\n\n\t\treturn al;\n\t}\n\n\tpublic long gcd(long a,long b)\n\t{\n\t\tif (b == 0)   \n\t\t\treturn a;  \n\n\t\treturn gcd(b, a % b);  \n\t}\n\n\tpublic long lcm(long a,long b)\n\t{\n\t\tlong hcf=gcd(a,b);\n\t\treturn (a*b)/hcf;\n\t}\n}",992        "solution_c": "class Solution {\npublic:\n    vector<int> replaceNonCoprimes(vector<int>& nums) {\n        vector<int> res;\n        for (auto num : nums) {\n            while (!res.empty() && gcd(res.back(), num) > 1) {\n                num = lcm(res.back(), num);\n                res.pop_back();\n            }\n            res.push_back(num);\n        }\n        return res;\n    }\n};"993    },994    {995        "title": "Consecutive Characters",996        "algo_input": "The power of the string is the maximum length of a non-empty substring that contains only one unique character.\n\nGiven a string s, return the power of s.\n\n&nbsp;\nExample 1:\n\nInput: s = \"leetcode\"\nOutput: 2\nExplanation: The substring \"ee\" is of length 2 with the character 'e' only.\n\n\nExample 2:\n\nInput: s = \"abbcccddddeeeeedcba\"\nOutput: 5\nExplanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of only lowercase English letters.\n\n",997        "solution_py": "class Solution(object):\n    def maxPower(self, s):\n        \"\"\"\n        :type s: str\n        :rtype: int\n        \"\"\"\n        stack=[]\n        mxpow=0\n        for i in s:\n            if stack and stack[-1]!=i:\n                mxpow=max(mxpow,len(stack))\n                stack=[]\n                stack.append(i)\n            else:\n                stack.append(i)\n        mxpow=max(mxpow,len(stack))\n        return mxpow",998        "solution_js": "var maxPower = function(s) {\n    let count = 1;\n    let maxNum =1;\n\n    for(let i=0;i<s.length;i++){\n       (s[i]===s[Number(i)+1]) ? count++ : count=1;\n        maxNum = Math.max(count,maxNum);\n    }\n\n    return maxNum;\n};",999        "solution_java": "class Solution {\n    public int maxPower(String s) {\n        // O(n), assuming the access to every char is O(1)\n        // iterate through characters\n        // if char(n) == char(n+1) counter++\n            // if counter > max, max = counter\n        // else counter = 1 // 1 is init value because otherwise the compared char itself is not counted\n\n        int maxConsecutive = 1; // 1 is init value because otherwise the compared char itself is not counted\n        int counterConsecutive = 1;\n        for(int i = 0; i< s.length()-1; i++){\n            if(s.charAt(i) == s.charAt(i+1)){\n                counterConsecutive++;\n                maxConsecutive = Math.max(counterConsecutive, maxConsecutive);\n            } else {\n                counterConsecutive = 1;\n            }\n        }\n\n        return maxConsecutive;\n    }\n}",1000        "solution_c": "class Solution {\npublic:\n    int ans = 1 ;\n    int maxPower(string s) {\n        for(int i = 0 ; i < size(s) ; ++i ){\n            int j = i ;\n            while(j < size(s) and s[j] == s[i]) ++j ;\n            ans = max(ans,j-i);\n            i = j - 1 ;\n        }\n        return ans ;\n    }\n};"1001    },1002    {1003        "title": "Sequentially Ordinal Rank Tracker",1004        "algo_input": "A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better.\n\nYou are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:\n\n\n\tAdding scenic locations, one at a time.\n\tQuerying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query).\n\t\n\t\tFor example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added.\n\t\n\t\n\n\nNote that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system.\n\nImplement the SORTracker class:\n\n\n\tSORTracker() Initializes the tracker system.\n\tvoid add(string name, int score) Adds a scenic location with name and score to the system.\n\tstring get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n[[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]\nOutput\n[null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]\n\nExplanation\nSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\ntracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\ntracker.get();              // The sorted locations, from best to worst, are: branford, bradford.\n                            // Note that branford precedes bradford due to its higher score (3 &gt; 2).\n                            // This is the 1st time get() is called, so return the best location: \"branford\".\ntracker.add(\"alps\", 2);     // Add location with name=\"alps\" and score=2 to the system.\ntracker.get();              // Sorted locations: branford, alps, bradford.\n                            // Note that alps precedes bradford even though they have the same score (2).\n                            // This is because \"alps\" is lexicographically smaller than \"bradford\".\n                            // Return the 2nd best location \"alps\", as it is the 2nd time get() is called.\ntracker.add(\"orland\", 2);   // Add location with name=\"orland\" and score=2 to the system.\ntracker.get();              // Sorted locations: branford, alps, bradford, orland.\n                            // Return \"bradford\", as it is the 3rd time get() is called.\ntracker.add(\"orlando\", 3);  // Add location with name=\"orlando\" and score=3 to the system.\ntracker.get();              // Sorted locations: branford, orlando, alps, bradford, orland.\n                            // Return \"bradford\".\ntracker.add(\"alpine\", 2);   // Add location with name=\"alpine\" and score=2 to the system.\ntracker.get();              // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n                            // Return \"bradford\".\ntracker.get();              // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n                            // Return \"orland\".\n\n\n&nbsp;\nConstraints:\n\n\n\tname consists of lowercase English letters, and is unique among all locations.\n\t1 &lt;= name.length &lt;= 10\n\t1 &lt;= score &lt;= 105\n\tAt any time, the number of calls to get does not exceed the number of calls to add.\n\tAt most 4 * 104 calls in total will be made to add and get.\n\n",1005        "solution_py": "from heapq import *\n\nclass MinHeapItem:\n    def __init__(self, name, score):\n        self.name = name\n        self.score = score\n    def __lt__(self, other):\n        return self.score < other.score or \\\n               (self.score == other.score and self.name > other.name)\n\nclass MaxHeapItem:\n    def __init__(self, name, score):\n        self.name = name\n        self.score = score\n    def __lt__(self, other):\n        return self.score > other.score or \\\n               (self.score == other.score and self.name < other.name)\n\nclass SORTracker:\n    def __init__(self):\n        self.min_heap = []\n        self.max_heap = []\n        self.i = 1\n\n    def add(self, name: str, score: int) -> None:\n        current = MinHeapItem(name, score)\n        if len(self.min_heap) < self.i:\n            heappush(self.min_heap, current)\n        elif current > self.min_heap[0]:\n            temp = heapreplace(self.min_heap, current)\n            heappush(self.max_heap, MaxHeapItem(temp.name, temp.score))\n        else:\n            heappush(self.max_heap, MaxHeapItem(name, score))\n\n    def get(self) -> str:\n        ans = self.min_heap[0].name\n        self.i += 1\n        if self.max_heap:\n            temp = heappop(self.max_heap)\n            heappush(self.min_heap, MinHeapItem(temp.name, temp.score))\n        return ans",1006        "solution_js": "var SORTracker = function() {\n    this.S=new AVL(),this.i=1\n};\nSORTracker.prototype.add = function(name, score) {\n    this.S.insert([name,score])\n};\nSORTracker.prototype.get = function() {\n    return this.S.findKthNODE(this.i++)[0]\n};\n\n// B O I  L E R P L A T E \nclass AVL{\n    constructor(){\n        this.nodeCount=0\n        this.root=null\n\n        // MODIFY THIS EVERY TIME.\n        this.NODE=class{\n            constructor(val,left=null,right=null,parent=null,bf=0,height=0){\n                this.val=val\n                this.left=left,this.right=right,this.parent=parent\n                this.bf=bf,this.height=height\n                this.SubTreeNodes=1\n            }\n        }\n    }\n    \n//===M O D I F Y   FOR     COMPLEX     NODES==\\\\\n    NODIFY(val){  //should return a new node based on the stats given\n        return new this.NODE(val)\n    }\n    comparator=(node1,node2)=>{// basic comparator that returns <0,0,>0 if node1>node2,node1==node2,node1<node2\n        if(node1.val[1]===node2.val[1]){\n             if(node2.val[0]>node1.val[0])\n                 return -1\n            return 1\n        }\n        return Number(node2.val[1])-Number(node1.val[1])\n    }\n//-------------U S A B L E------------------\\\\\n    //returns true if the value was inserted successfully\n    //returns false if the value already exists\n    insert(NODE){ //O(logn) \n        if(NODE===null)\n            return false\n        NODE=this.NODIFY(NODE)\n        if(!this.contains(this.root,NODE)){\n            this.root=this.ins(this.root,NODE)\n            this.nodeCount++\n            return true\n        }\n        return false\n    }\n    remove(NODE){ \n        if(NODE===null)\n            return false\n        NODE=this.NODIFY(NODE)\n       // console.log(this.contains(this.root,new Node(7)))\n        if(this.contains(this.root,NODE)){\n            this.root=this.rem(this.root,NODE)\n            this.nodeCount--\n            return true\n        }\n        return false\n        //rebalance the tree\n    }\n    has(NODE){\n        NODE=this.NODIFY(NODE)\n        return this.contains(this.root,NODE)\n    }\n    traversalASC(){ //O(n)\n        let result=[]\n        let dfs=(node)=>{\n            if(!node)\n                return\n            dfs(node.left)\n            result.push(node)\n            dfs(node.right)\n        }\n        dfs(this.root)\n        return result\n    }\n    findNextSmaller(NODE){\n        NODE=this.NODIFY(NODE)\n        let cur=this.root,result=null\n        while(cur!==null){\n            if(this.comparator(cur,NODE)<0)\n                result=cur,\n                cur=cur.right\n            else\n                cur=cur.left\n        }\n        if(result===null)\n            return false // no such element\n        return result\n    }\n    findNextBigger(NODE){\n        NODE=this.NODIFY(NODE)\n        let cur=this.root,result=null\n        while(cur!==null){\n            if(this.comparator(cur,NODE)<=0)\n                cur=cur.right\n            else\n                result=cur,\n                cur=cur.left\n        }\n        if(result===null)\n            return false // no such element\n        return result\n    }\n    findKthNODE(k){ //RETURNS THE NODE, NOT THE VALUE\n        if(this.nodeCount<k)\n            return null\n        return this.findKth(this.root,k)\n    }\n    min=()=>this.findMin(this.root).val\n    max=()=>this.findMax(this.root).val\n//--------- I N T E R N A L S -----------------\\\\\n    contains(node,val){\n        if(node===null)\n            return false\n        let compare=this.comparator(node,val)\n        if(compare<0) //node<val\n            return this.contains(node.right,val)\n        if(compare>0)\n            return this.contains(node.left,val)\n        return true\n    }\n    //inserts newNode to target node\n    ins(tree,value){\n        if(tree===null)\n            return value\n        //(target is bigger? insert it to the left): else to the right\n        if(this.comparator(tree,value)>0)\n            tree.left=this.ins(tree.left,value)\n        else\n            tree.right=this.ins(tree.right,value)\n        //update balance factor of the target\n        this.update(tree) \n        return this.rebalance(tree) //balance the target if it needs rebalancing\n    }\n    rem(node,elem){\n        if(node===null)\n            return null\n        //search an existing node with the given value\n        let compare=this.comparator(elem,node)//-----\n        if(compare<0)\n            node.left=this.rem(node.left,elem)\n        else if(compare>0)\n            node.right=this.rem(node.right,elem)\n        else{ //node found\n             //remove the node and replace it with its sucessor\n            if(node.left===null)\n                return node.right\n            else if(node.right===null)\n                return node.left\n            else{ //still has both subtrees? \n                if(node.left.height>node.right.height){\n                    let successor=this.findMax(node.left)/////\n                    node.val=successor.val\n                    node.left=this.rem(node.left,successor)\n                }   \n                else{\n                    let successor=this.findMin(node.right)\n                    node.val=successor.val\n                    node.right=this.rem(node.right,successor)\n                }\n            }\n        }\n        this.update(node)\n        return this.rebalance(node)\n    }\n    //find the min and max node of the subtree rooted at (node)\n    findMin=(node)=>node.left?this.findMin(node.left):node\n    findMax=(node)=>node.right?this.findMax(node.right):node\n    //balances the subtree rooted at node if it is imbalanced (has balancefactor=+-2)\n    //and returns the now balanced node\n    rebalance(node){  //4 cases, 4 rotations\n        if(node.bf==-2){\n            if(node.left.bf<=0)\n                return this.LL(node)\n            else\n                return this.LR(node)\n        }\n        else if(node.bf==2){\n            if(node.right.bf>=0)\n                return this.RR(node)\n            else\n                return this.RL(node)\n        }\n        return node\n    }\n    //update the balance factor and the height of the current node\n    update(node){ \n        let leftHeight=node.left!==null?node.left.height:-1,rightHeight=node.right!==null?node.right.height:-1\n        node.height=Math.max(leftHeight,rightHeight)+1\n        node.bf=rightHeight-leftHeight\n        node.SubTreeNodes=1+(node.left===null?0:node.left.SubTreeNodes )+(node.right===null?0:node.right.SubTreeNodes)\n    }\n\n    //4 cases of unbalanced trees\n    LL=(node)=>this.rightRotation(node)\n    RR=(node)=>this.leftRotation(node)\n    LR(node){\n        node.left=this.leftRotation(node.left)\n        return this.LL(node)\n    }\n    RL(node){\n        node.right=this.rightRotation(node.right)\n        return this.RR(node)\n    }\n    //2 total rotations that work on RR and LL cases\n    leftRotation(node){\n        let newParent=node.right\n        node.right=newParent.left\n        newParent.left=node\n        this.update(node)\n        this.update(newParent)\n        return newParent\n    }\n    rightRotation(node){\n        let newParent=node.left\n        node.left=newParent.right\n        newParent.right=node\n        this.update(node)\n        this.update(newParent)\n        return newParent\n    }\n    findKth(node,k){\n        let leftCount=node.left?node.left.SubTreeNodes:0\n        if(leftCount+1===k)\n            return node.val\n        if(leftCount+1<k)\n            return this.findKth(node.right,k-leftCount-1)\n        \n        return this.findKth(node.left,k)\n    }\n}",1007        "solution_java": "class SORTracker {\n\n    private TreeMap<Integer, List<String>> map;\n    private int queryNum;\n\n    // Find suitable position for name in the list\n    private int getIndex(String name, List<String> list) {\n        int l = 0, r = list.size() - 1, m = 0;\n        while (l < r) {\n            m = l + (r - l) / 2;\n            if(name.compareTo(list.get(m)) > 0) {\n                l = m + 1;\n            } else {\n                r = m;\n            }\n        }\n        return name.compareTo(list.get(l)) > 0 ? l+1 : l;\n    }\n\n    public SORTracker() {\n        map = new TreeMap<>((a,b) -> (b-a));\n        queryNum = 0;\n    }\n\n    public void add(String name, int score) {\n        List<String> list = map.getOrDefault(score, new ArrayList<>());\n        int index = (list.size() == 0) ? 0 : getIndex(name, list);\n        list.add(index, name);\n        map.put(score, list);\n    }\n\n    public String get() {\n        int index = queryNum;\n        for (int score: map.keySet()) {\n            if (index < map.get(score).size()) {\n                queryNum++;\n                return map.get(score).get(index);\n            }\n            index -= map.get(score).size();\n        }\n        return \"\";\n    }\n}",1008        "solution_c": "struct compareMin\n{\n    bool operator() (pair<int,string> p1, pair<int,string> p2) {\n        if(p1.first == p2.first) return p1.second < p2.second;\n        return p1.first > p2.first;\n    }\n};\n\nstruct compareMax\n{\n    bool operator() (pair<int,string> p1, pair<int,string> p2) {\n        if(p1.first == p2.first) return p1.second > p2.second;\n        return p1.first < p2.first;\n    }\n};\n\nclass SORTracker {\npublic:\n    priority_queue <pair<int,string>, vector<pair<int,string>>, compareMin> min_heap;\n    priority_queue <pair<int,string>, vector<pair<int,string>>, compareMax> max_heap;\n\n    SORTracker() {}\n\n    void add(string name, int score) {\n        if(!min_heap.empty() && (min_heap.top().first < score || (min_heap.top().first == score && min_heap.top().second > name))) {\n                pair<int,string> t = min_heap.top();\n                min_heap.pop();\n                min_heap.push({score,name});\n                max_heap.push(t);\n        } else {\n            max_heap.push({score,name});\n        }\n    }\n\n    string get() {\n        pair<int,string> s = max_heap.top();\n        max_heap.pop();\n        min_heap.push(s);\n        return s.second;\n    }\n};"1009    },1010    {1011        "title": "Count Good Triplets in an Array",1012        "algo_input": "You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].\n\nA good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 &lt;= x, y, z &lt;= n - 1, such that pos1x &lt; pos1y &lt; pos1z and pos2x &lt; pos2y &lt; pos2z.\n\nReturn the total number of good triplets.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [2,0,1,3], nums2 = [0,1,2,3]\nOutput: 1\nExplanation: \nThere are 4 triplets (x,y,z) such that pos1x &lt; pos1y &lt; pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x &lt; pos2y &lt; pos2z. Hence, there is only 1 good triplet.\n\n\nExample 2:\n\nInput: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\nOutput: 4\nExplanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums1.length == nums2.length\n\t3 &lt;= n &lt;= 105\n\t0 &lt;= nums1[i], nums2[i] &lt;= n - 1\n\tnums1 and nums2 are permutations of [0, 1, ..., n - 1].\n\n",1013        "solution_py": "from sortedcontainers import SortedList\nclass Solution:\n    def goodTriplets(self, A: List[int], B: List[int]) -> int:\n        # Index of a (from A) in B.\n        pos = [0] * len(A)               \n        for idx, b in enumerate(B):\n            pos[b] = idx\n        \n        # Build pre_a[i]: number of elements on a[i]'s left in both A and B.\n        # pos_in_b: sorted indexes (in B) of all the visited elements in A.\n        pos_in_b, pre_a = SortedList([pos[A[0]]]), [0]      \n        for a in A[1:]:       \n            pos_in_b.add(pos[a])\n            pre_a.append(pos_in_b.bisect_left(pos[a]))\n    \n        # Build suf_a[i]: number of elements on a[i]'s right in both A and B.\n        pos_in_b, suf_a = SortedList([pos[A[-1]]]), [0]\n        for a in reversed(A[:len(A)-1]):\n            idx = pos_in_b.bisect(pos[a])\n            suf_a.append(len(pos_in_b) - idx)\n            pos_in_b.add(pos[a])\n        suf_a.reverse()\n        \n        # Sum up all unique triplets centered on A[i].\n        ans = 0\n        for x, y in zip(pre_a, suf_a):\n            ans += x * y\n        return ans",1014        "solution_js": "var goodTriplets = function(nums1, nums2) {\n  let n = nums1.length, nums2_idx = Array(n);\n  for (let i = 0; i < n; i++) nums2_idx[nums2[i]] = i;\n  let idxs = Array(n);\n  for (let i = 0; i < n; i++) idxs[i] = nums2_idx[nums1[i]];\n\n  let smallerLeft = getSmallerLeft(idxs); // smallerLeft[i] = number of indices to the left of i smaller than idxs[i] in both nums1 and nums2\n  let biggerRight = getBiggerRight(idxs); // biggerRight[i] = number of indices to the right of i bigger than idxs[i] in both nums1 and nums2\n  let ans = 0;\n  for (let i = 1; i < n - 1; i++) {\n    ans += smallerLeft[i] * biggerRight[i];\n  }\n  return ans;\n};\n\nfunction getSmallerLeft(idxs) {\n  let n = idxs.length, res = Array(n).fill(0);\n  let segTree = new SegmentTree(n);\n  for (let i = 0; i < n; i++) {\n    res[i] = segTree.getSum(0, idxs[i] - 1);\n    segTree.update(idxs[i], 1);\n  }\n  return res;\n}\n\nfunction getBiggerRight(idxs) {\n  let n = idxs.length, res = Array(n).fill(0);\n  let segTree = new SegmentTree(n);\n  for (let i = n - 1; i >= 0; i--) {\n    res[i] = segTree.getSum(idxs[i] + 1, n - 1);\n    segTree.update(idxs[i], 1);\n  }\n  return res;\n}\n\nclass SegmentTree {\n  constructor(n) {\n    this.size = n;\n    this.segTree = Array(n * 2).fill(0);\n  }\n  update(index, val) {\n    let n = this.size, idx = index + n;\n    this.segTree[idx] += val;\n    idx = Math.floor(idx / 2);\n\n    while (idx > 0) {\n      this.segTree[idx] = this.segTree[idx * 2] + this.segTree[idx * 2 + 1];\n      idx = Math.floor(idx / 2);\n    }\n  }\n  getSum(left, right) {\n    let n = this.size, sum = 0;\n    let left_idx = left + n, right_idx = right + n;\n    // left must be even, right must be odd\n    while (left_idx <= right_idx) {\n      if (left_idx % 2 === 1) sum += this.segTree[left_idx++];\n      if (right_idx % 2 === 0) sum += this.segTree[right_idx--];\n      left_idx = Math.floor(left_idx / 2);\n      right_idx = Math.floor(right_idx / 2);\n    }\n    return sum;\n  }\n}",1015        "solution_java": "class Solution {\n    public long goodTriplets(int[] nums1, int[] nums2) {\n        int n= nums1.length;\n        int indices[]= new int[n];\n        for(int i=0;i<n;i++)\n        {\n            indices[nums2[i]]=i;\n        }\n        int B[]= new int[n];\n        for(int i=0;i<n;i++)\n        {\n            B[i]=indices[nums1[i]];\n            B[i]++;\n        }\n        Fenw L=new Fenw(n+1);\n        long []left= new long[n+1];\n        long []right= new long[n+1];\n        for(int i=1;i<=n;i++)\n        {\n            left[i]=L.sum(B[i-1]-1);\n            L.update(B[i-1],1);\n        }\n         Fenw R=new Fenw(n+1);\n        for(int i=n;i>0;i--)\n        {\n            right[i]=R.sum(n)-R.sum(B[i-1]);\n            R.update(B[i-1],1);\n        }\n        long ans=0l;\n        for(int i=0;i<=n;i++)\n        {\n            ans+=left[i]*right[i];\n        }\n        return ans;\n    }\n}\nclass Fenw\n{\n    long[]farr;\n    int n;\n    Fenw(int n)\n    {\n        this.n=n;\n        farr=new long[n+1];\n    }\n    void update(int index, int val)\n    {\n        int c=0;\n        for(int i=index;i<=n;i+=(i&-i))\n        {\n            c++;\n            farr[i]+=val;\n        }\n    }\n   \n    long sum(int index)\n    {\n        long ans=0l;\n        for(int i=index;i>0;i-=(i&-i))\n        {\n            ans+=farr[i];\n        }\n        return ans;\n    }\n}",1016        "solution_c": "typedef long long ll;\ntypedef long double ld;\n#define mod 1000000007\n#define all(x) begin(x),end(x)\n#include <ext/pb_ds/assoc_container.hpp> \n#include <ext/pb_ds/tree_policy.hpp>\nusing namespace __gnu_pbds;\n#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>\n\n\nclass Solution {\npublic:\n    long long goodTriplets(vector<int>& nums1, vector<int>& nums2) {\n        unordered_map<int, int> mapping;\n        int no = 1;\n        for (int x : nums1){\n            mapping[x] = no;\n            no++;\n        }\n        for (int i = 0; i < nums2.size(); ++i)\n            nums2[i] = mapping[nums2[i]];\n        int n = nums2.size();\n        ordered_set st1;\n        ordered_set st2;\n        for (int x : nums2)\n            st2.insert(x);\n        ll ans = 0;\n        st1.insert(nums2[0]);\n        st2.erase(st2.find(nums2[0]));\n        for (int i = 1; i < n - 1; ++i)\n        {\n            st2.erase(st2.find(nums2[i]));\n            ll less = (ll)st1.order_of_key(nums2[i]);\n            ll great = (ll) (((int)st2.size()) - st2.order_of_key(nums2[i]));\n            ans += (less * great);\n            st1.insert(nums2[i]);\n        }\n        return ans;\n    }\n};"1017    },1018    {1019        "title": "Numbers With Same Consecutive Differences",1020        "algo_input": "Return all non-negative integers of length n such that the absolute difference between every two consecutive digits is k.\n\nNote that every number in the answer must not have leading zeros. For example, 01 has one leading zero and is invalid.\n\nYou may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 3, k = 7\nOutput: [181,292,707,818,929]\nExplanation: Note that 070 is not a valid number, because it has leading zeroes.\n\n\nExample 2:\n\nInput: n = 2, k = 1\nOutput: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 9\n\t0 &lt;= k &lt;= 9\n\n",1021        "solution_py": "class Solution:\n    def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n        # initialize the cache with all the valid numbers of length 1\n        # cache is a list of tuple (number, digit at units place)\n        cache = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]\n        cacheTemp = []\n        \n        # each iteration will store all the valid numbers of length 2 to n in cache\n        for i in range(2, n + 1):\n            # loop through the cache from the previous iteration\n            for j in cache:\n                if k == 0:\n                    if j[0] != 0:\n                        cacheTemp.append((j[0] * 10 + j[1], j[1]))\n                elif j[1] == 0 and i == 2:\n                    continue\n                elif j[1] <= k - 1:\n                    if j[1] < 10 - k:\n                        cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n                elif j[1] >= 10 - k:\n                    if j[1] > k - 1:\n                        cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n                else:\n                    cacheTemp.append((j[0] * 10 + j[1] - k, j[1] - k))\n                    cacheTemp.append((j[0] * 10 + j[1] + k, j[1] + k))\n            cache = cacheTemp   # store the list of valid integers of length i in cache\n            cacheTemp = []  # empty the temporary list\n        \n        res = []\n        for i in cache:\n            res.append(i[0])\n        \n        return res\n        ",1022        "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number[]}\n */\nvar numsSameConsecDiff = function(n, k) {\n\n  let res = [];\n\n  const bfs=(num,i)=>{\n    let queue = [];\n    queue.push(i);\n    while(queue.length){\n        // console.log(\"queue is \",queue)\n        i = queue.shift();\n        if (i <= num)\n        {\n            if(i.toString().length===n){\n               res.push(i);\n            }\n            let last_digit = i % 10;\n\n            if (last_digit+k<10)\n            {\n                queue.push((i * 10) + (last_digit + k));\n            }\n            if(k>0 && last_digit-k >= 0)\n             {\n                queue.push((i * 10) + (last_digit-k));\n             }\n\n        }\n    }\n  }\n\n  let num = Math.pow(10,n)-1;\n  for(let i=1;i<=9 && i<num ;i++){\n    bfs(num,i);\n  }\n  return res;\n\n};",1023        "solution_java": "class Solution {\n    \n    List<Integer> res = new ArrayList<>();\n    public int[] numsSameConsecDiff(int n, int k) {\n        \n        for(int ans = 1; ans < 10; ans++){ // first digit can't be 0\n            find(ans, n-1, k); // find remaining n-1 digits using backtrack\n        }\n        \n        return res.stream().mapToInt(Integer::intValue).toArray();  // convert list to int arr\n    }\n    \n    private void find(int ans, int n, int k){\n        \n        if(n == 0){\n            res.add(ans); // if got length n number then put that into res\n            return;\n        }\n        \n        for(int i = 0; i < 10; i++){\n            if(Math.abs(ans%10-i) == k) // find digit that have k difference with last digit\n                find(ans*10+i, n-1, k);\n        }\n        ans /= 10; // remove last digit while backtrack\n    }\n}",1024        "solution_c": "class Solution {\npublic:\n    vector<int> res;\n    void solve(int num,int n,int k)\n    {\n        if(n==1)\n        {\n            res.push_back(num);\n            return;\n        }\n        int dig=num%10;\n        if(dig+k<=9 && k!=0)\n        {\n            solve(num*10+dig+k,n-1,k);\n        }\n        if(dig-k>=0)\n        {\n            solve(num*10+dig-k,n-1,k);\n        }\n    }\n    vector<int> numsSameConsecDiff(int n, int k) {\n        res.clear();\n        for(int i=1;i<=9;++i)\n        {\n            solve(i,n,k);\n        }\n        return res;\n    }\n};"1025    },1026    {1027        "title": "Intervals Between Identical Elements",1028        "algo_input": "You are given a 0-indexed array of n integers arr.\n\nThe interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.\n\nReturn an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i].\n\nNote: |x| is the absolute value of x.\n\n&nbsp;\nExample 1:\n\nInput: arr = [2,1,3,1,2,3,3]\nOutput: [4,2,7,2,4,4,5]\nExplanation:\n- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5\n\n\nExample 2:\n\nInput: arr = [10,5,10,10]\nOutput: [5,0,3,4]\nExplanation:\n- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4\n\n\n&nbsp;\nConstraints:\n\n\n\tn == arr.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= arr[i] &lt;= 105\n\n",1029        "solution_py": "# helper data structure Scout\nclass Scout:\n    \n    def __init__(self, prev_idx=-1, count_of_equal=0):\n        \n        # record of index of last identical element\n        self.prev_idx = prev_idx\n        \n        # count of identical elements so far\n        self.count_of_equal = count_of_equal\n    \n    def __iter__(self):\n\t\t# ouput previous index, and count of equal in order\n        return iter( (self.prev_idx, self.count_of_equal) )\n    \n    \n        \nclass Solution:\n    def getDistances(self, arr: List[int]) -> List[int]:\n        \n        size = len(arr)\n        \n        pre_scout = defaultdict( Scout )\n        pre_dist_sum = [0 for _ in range(size)]\n        \n        post_scout = defaultdict( Scout )\n        post_dist_sum = [0 for _ in range(size)]\n        \n        \n        ## Step_1:\n        # update for pre_dist_sum table, direction is from left to right\n        for i, element in enumerate(arr):\n            \n            prev_equal_idx, prev_count_of_equal = pre_scout[element]\n            \n            # update pre_dist_sum table if we have identical elements before index i\n            if prev_count_of_equal:\n                pre_dist_sum[i] += pre_dist_sum[ prev_equal_idx ] + (i - prev_equal_idx) * prev_count_of_equal\n            \n            # update Scout information for current element\n            pre_scout[element] = i, prev_count_of_equal+1\n            \n        # --------------------------------------------------------------\n        \n        ## Step_2:\n        # update for pos_dist_sum table, direction is from right to left\n        for i, element in reversed( [*enumerate(arr)] ):\n            \n            post_equal_idx, post_count_of_equal = post_scout[element]\n\n            # update post_dist_sum table if we have identical elements after index i\n            if post_count_of_equal:\n                post_dist_sum[i] += post_dist_sum[ post_equal_idx ] + (post_equal_idx - i) * post_count_of_equal\n            \n            # update Scout information for current element\n            post_scout[element] = i, post_count_of_equal+1\n            \n            \n        ## Step_3:\n        # Generate final output by definition\n        return [ pre_dist_sum[i] + post_dist_sum[i] for i in range(size) ]\n        \n        ",1030        "solution_js": "var getDistances = function(arr) {\n    const map = new Map();\n    const result = new Array(arr.length).fill(0);\n\n    for (let i = 0; i < arr.length; i++) {\n        const num = arr[i];\n        const val = map.get(num) || {\n            count: 0,\n            sum: 0\n        };\n        result[i] += (val.count * i) - val.sum;\n        val.sum += i;\n        val.count++;\n        map.set(num, val);\n    }\n    map.clear();\n\n    for (let i = arr.length - 1; i >= 0; i--) {\n        const num = arr[i];\n        const val = map.get(num) || {\n            count: 0,\n            sum: 0\n        };\n        result[i] += val.sum - (val.count * i);\n        val.sum += i;\n        val.count++;\n        map.set(num, val);\n    }\n\n    return result;\n};",1031        "solution_java": "class Solution {\n    public long[] getDistances(int[] arr) {\n        long[] output = new long[arr.length];\n        Map<Integer, Long> sumMap = new HashMap<>();\n        Map<Integer, Integer> countMap = new HashMap<>();\n        for (int i = 0; i < arr.length; ++ i) {\n            if (!sumMap.containsKey(arr[i])) {\n                sumMap.put(arr[i], 0l);\n                countMap.put(arr[i], 0);\n            }\n\n            output[i] += i * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n            sumMap.put(arr[i], sumMap.get(arr[i]) + i);\n            countMap.put(arr[i], countMap.get(arr[i]) + 1);\n        }\n\n        sumMap = new HashMap<>();\n        countMap = new HashMap<>();\n        int len = arr.length;\n        for (int i = len - 1; i >= 0; -- i) {\n            if (!sumMap.containsKey(arr[i])) {\n                sumMap.put(arr[i], 0l);\n                countMap.put(arr[i], 0);\n            }\n\n            output[i] += (len - i - 1) * (long)countMap.get(arr[i]) - sumMap.get(arr[i]);\n            sumMap.put(arr[i], sumMap.get(arr[i]) + (len - i - 1));\n            countMap.put(arr[i], countMap.get(arr[i]) + 1);\n        }\n\n        return output;\n    }\n}",1032        "solution_c": "class Solution {\npublic:\n    vector<long long> getDistances(vector<int>& arr) {\n        int size=arr.size();\n        vector<long long>pre(size,0),suf(size,0),ans(size,0);\n        unordered_map<int,vector<int>>mp;\n        \n        // store index of the same elements.\n        for(int i=0;i<size;i++)\n            mp[arr[i]].push_back(i);\n       //  prefix will store the sum of absolute diff. from the starting index of current element to the current index.\n        // pre[cur index]=pre[prev index]+ number of same elements before cur element * abs diff of cur element pos and pre element pos\n        for(auto &p:mp){\n            auto vec=p.second;\n            for(int i=1;i<vec.size();i++)\n                pre[vec[i]]=  pre[vec[i-1]]+  i*(long)(vec[i]-vec[i-1]);\n        }\n       // suffix will store the sum of absolute diff. from the ending index of current element to the current index.\n        // same formula as above but in reverse order\n        for(auto &p:mp){\n            auto vec=p.second;\n            for(int i=vec.size()-2;i>=0;i--)\n                suf[vec[i]]=  suf[vec[i+1]] + long(vec.size()-1-i) * (long)(vec[i+1]-vec[i]);\n        }\n        for(int i=0;i<size;i++)\n            ans[i]+=(pre[i]+suf[i]);\n        return ans;\n    }\n};"1033    },1034    {1035        "title": "Majority Element",1036        "algo_input": "Given an array nums of size n, return the majority element.\n\nThe majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.\n\n&nbsp;\nExample 1:\nInput: nums = [3,2,3]\nOutput: 3\nExample 2:\nInput: nums = [2,2,1,1,1,2,2]\nOutput: 2\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 5 * 104\n\t-109 &lt;= nums[i] &lt;= 109\n\n\n&nbsp;\nFollow-up: Could you solve the problem in linear time and in O(1) space?",1037        "solution_py": "class Solution(object):\n    def majorityElement(self, nums):\n        sol = None\n        cnt = 0\n        for i in nums:\n            if cnt == 0:\n                sol = i\n            cnt += (1 if i == sol else -1)\n        return sol",1038        "solution_js": "var majorityElement = function(nums) {\n    // Initialize sol and cnt to store the solution and its frequency for respective iterations...\n    let sol = 0, cnt = 0;\n    // For every element i in the array...\n    for(let i = 0; i < nums.length; i++ ) {\n        // If cnt is equal to zero, update sol as sol = i\n        if(cnt == 0){\n            sol = nums[i];\n            cnt = 1;\n        }\n        // If i is equal to candidate, increment cnt...\n        else if(sol == nums[i]){\n            cnt++;\n        }\n        // Otherwise, decrement cnt...\n        else{\n            cnt--;\n        }\n    }\n    // Return & print the solution...\n    return sol;\n};",1039        "solution_java": "class Solution {\n    public int majorityElement(int[] nums) {\n        // Base case...\n        if (nums.length == 1) {\n            return nums[0];\n        }\n        // Sort nums array...\n        Arrays.sort(nums);\n        // Since the majority element appears more than n / 2 times...\n        // The n/2 -th element in the sorted nums must be the majority element...\n        return nums[nums.length / 2];\n    }\n}",1040        "solution_c": "class Solution {\npublic:\n    int majorityElement(vector<int>& nums) {\n        // Initialize sol and cnt to store the solution and its frequency for respective iterations...\n        int sol = 0, cnt = 0;\n        // For every element i in the array...\n        for(int i = 0; i < nums.size(); i++ ) {\n            // If cnt is equal to zero, update sol as sol = i\n            if(cnt == 0){\n                sol = nums[i];\n                cnt = 1;\n            }\n            // If i is equal to candidate, increment cnt...\n            else if(sol == nums[i]){\n                cnt++;\n            }\n            // Otherwise, decrement cnt...\n            else{\n                cnt--;\n            }\n        }\n        // Return & print the solution...\n        return sol;\n    }\n};"1041    },1042    {1043        "title": "Minimum Absolute Difference Queries",1044        "algo_input": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 &lt;= i &lt; j &lt; a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.\n\n\n\tFor example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.\n\n\nYou are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).\n\nReturn an array ans where ans[i] is the answer to the ith query.\n\nA subarray is a contiguous sequence of elements in an array.\n\nThe value of |x| is defined as:\n\n\n\tx if x &gt;= 0.\n\t-x if x &lt; 0.\n\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput: [2,1,4,1]\nExplanation: The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.\n\n\nExample 2:\n\nInput: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput: [-1,1,1,3]\nExplanation: The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n  elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 100\n\t1 &lt;= queries.length &lt;= 2&nbsp;* 104\n\t0 &lt;= li &lt; ri &lt; nums.length\n\n",1045        "solution_py": "class Solution:\n    def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n        # location of number\n        loc = defaultdict(list)\n        for i, num in enumerate(nums):\n            loc[num].append(i)\n        \n        # start from sorted key thus keep tracking minimum difference\n        k = sorted(loc)\n        \n        res = []\n        for a, b in queries:\n            cands = []\n            ans = float('inf')\n            for c in k:\n                # left and right range overlap means no available locations in range\n                if bisect.bisect_left(loc[c], a) == bisect.bisect(loc[c], b): continue\n                if cands: \n\t\t\t\t\tans = min(ans, c - cands[-1])\n                cands.append(c)\n            if ans == float('inf'): ans = -1\n            res.append(ans)\n        return res",1046        "solution_js": "var minDifference = function(nums, queries) {\n    const qlen   = queries.length, len = nums.length;\n    const res    = new Array(qlen).fill(-1);\n    const prefix = [];\n    \n    for(let i = 0; i <= len; i++) {\n        if(i == 0) prefix[i] = new Array(101).fill(0);\n        else {\n            prefix[i] = Array.from(prefix[i-1]);\n            prefix[i][nums[i-1]]++;   \n        }\n    }\n    \n    for(let k = 0; k < qlen; k++) {\n        const [l, r] = queries[k];\n        const left = prefix[l], right = prefix[r + 1];\n        let prev = -1, ans = Infinity;\n        for(let i = 1; i <= 100; i++) {\n            const diff = right[i] - left[i];\n            if(diff == 0) continue;\n            \n            if(prev != -1) {\n                ans = Math.min(ans, i - prev);\n            }\n            prev = i;\n        }\n        if(ans != Infinity) {\n            res[k] = ans;\n        }\n    }\n    \n    return res;\n};",1047        "solution_java": "class Solution {\n    public int[] minDifference(int[] nums, int[][] queries) {\n        int n = nums.length;\n        int[][] count = new int[n + 1][100];\n        int q = queries.length;\n        int ans[] = new int[q];\n        \n        for(int i = 0; i < n; ++i) {\n            for(int j = 0; j < 100; ++j)\n                count[i + 1][j] = count[i][j];\n            \n            ++count[i + 1][nums[i] - 1];\n        }\n        \n        for(int i = 0; i < q; ++i) {\n            int low = queries[i][0];\n            int high = queries[i][1] + 1;\n            List<Integer> present = new ArrayList<>();\n            int min = 100;\n            \n            for(int j = 0; j < 100; ++j)\n                if(count[high][j] - count[low][j] != 0)\n                    present.add(j);\n            \n            for(int j = 1; j < present.size(); ++j)\n                min = Math.min(min, present.get(j) - present.get(j - 1));\n            \n            if(present.size() == 1)\n                min = -1;\n            \n            ans[i] = min;\n        }\n        \n        return ans;\n    }\n}",1048        "solution_c": "class Solution {\npublic:\n    vector<bitset<101>> tree;\n    vector<int> minDifference(vector<int>& nums, vector<vector<int>>& queries) {\n        int n = nums.size();\n\n        tree = vector<bitset<101>>(4*(n+1) + 1);\n        buildtree(1, 0, n-1, nums);\n\n        vector<int> ans;\n        for(auto &e: queries){\n            auto finalOnesRepresentations = query(1, 0, n-1, e[0], e[1]);\n\n            // find the first 1\n            int i = 0;\n            while(i < 101 and finalOnesRepresentations[i] != 1){\n                i++;\n            }\n\n            int gap = INT_MAX;\n            int prev = i;\n            i++;\n            // find the minimum gap\n            for(; i < 101; i++){\n                if(finalOnesRepresentations[i] == 1){\n                    gap = min(gap, i - prev);\n                    prev = i;\n                }\n            }\n            ans.push_back(gap == INT_MAX ? -1 : gap);\n        }\n        return ans;\n    }\n\n    bitset<101> query(int index, int s, int e, int qs, int qe){\n\n        if(s > e) return bitset<101>();\n        if(e < qs || s > qe) return bitset<101>();\n        if(qs <= s and e <= qe) return tree[index];\n\n        int mid = (s+e)/2;\n        auto left = query(index*2, s, mid, qs, qe);\n        auto right = query(index*2+1, mid+1, e, qs , qe);\n        return left | right;\n    }\n\n    void buildtree(int index, int s, int e, vector<int>& a){\n\n        if(s > e)return;\n\n        if(s==e){\n            bitset<101> b;\n            b[a[s]] = 1;\n            tree[index] = b;\n            return;\n        }\n\n        int mid = (s+e)/2;\n        buildtree(index*2, s, mid, a);\n        buildtree(index*2+1, mid+1, e, a);\n        tree[index] = tree[index*2] | tree[index*2+1];\n    }\n};"1049    },1050    {1051        "title": "Minimum Swaps to Arrange a Binary Grid",1052        "algo_input": "Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.\n\nA grid is said to be valid if all the cells above the main diagonal are zeros.\n\nReturn the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.\n\nThe main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).\n\n&nbsp;\nExample 1:\n\nInput: grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput: 3\n\n\nExample 2:\n\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput: -1\nExplanation: All rows are similar, swaps have no effect on the grid.\n\n\nExample 3:\n\nInput: grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 &lt;= n &lt;= 200\n\tgrid[i][j] is either 0 or 1\n\n",1053        "solution_py": "class Solution:\n    def minSwaps(self, grid) -> int:\n        n = len(grid)\n        max_right = [-1] * n\n        for r, row in enumerate(grid):\n            for c in range(n - 1, -1, -1):\n                if row[c] == 1:\n                    max_right[r] = c\n                    break\n        if all(v <= i for i, v in enumerate(sorted(max_right))):\n            swaps = 0\n            i = 0\n            while i < n:\n                while i < n and max_right[i] <= i:\n                    i += 1\n                if i == n:\n                    break\n                j = i\n                while j < n and max_right[j] > i:\n                    j += 1\n                swaps += j - i\n                max_right[i], max_right[i + 1: j + 1] = (max_right[j],\n                                                         max_right[i: j])\n                i += 1\n            return swaps\n        return -1",1054        "solution_js": "var minSwaps = function(grid) {\n    const arr = [];\n    let count = 0;\n\n    for(let row of grid) {\n        arr.push(row.lastIndexOf(1));\n    }\n\n    function swap(i, j) {\n        [arr[i], arr[j]] = [arr[j], arr[i]];\n        count++;\n    }\n\n    for(let i = 0; i < arr.length; i++) {\n        // if num <= i pass b/c it's its correct spot\n        if(arr[i] <= i) continue;\n        let j = i;\n\n        // scan forward looking for a num <= i\n        while(arr[j] > i) {\n            j++;\n            if(j >= arr.length) return -1;\n        }\n\n        // swap as you move back to the right spot\n        for(let k = j; k > i; k--) {\n            swap(k, k-1);\n        }\n    }\n    return count;\n};",1055        "solution_java": "class Solution {\n    public int minSwaps(int[][] grid) {\n        int n = grid.length, ans = 0, cur = 0;\n        for (int k = 0; k < n - 1; k++){ // looking for the fitting row for row k\n            for (int i = k; i < n; i++){ // start from row k looking downward\n                for (int j = k + 1; j < n; j++){ // all cell after and at k + 1 must be 0\n                    if (grid[i][j] == 1)\n                        break;\n                    if (j < n - 1)\n                        continue;\n                    for (int m = i; m > k; m--){ // j == n - 1 here, so we found a valid row\n                        int[] tmp = grid[m - 1];  // swap it into the correct row - row k\n                        grid[m - 1] = grid[m];\n                        grid[m] = tmp;\n                        ans++;\n                    }\n                    i = n;\n                }\n                if (i == n - 1) // i reaches the end and did not find a fitting row, return -1\n                    return -1;\n            }\n        }\n        return ans;\n    }\n}",1056        "solution_c": "class Solution {\npublic:\n    int minSwaps(vector<vector<int>>& grid) {\n\n        int n = grid.size();\n        vector<int> mr(n,0);\n        vector<int> br(n,0);\n        for(int i=0;i<n;i++)\n        {\n            for(int j=0;j<n;j++)\n            {\n                if(grid[i][j]==1)\n                    mr[i] = j;\n            }\n        }\n        br = mr;\n        sort(mr.begin(),mr.end());\n        for(int i=0;i<n;i++)\n            if(mr[i]>i)\n                return -1;\n        int count = 0;\n        for(int i=0;i<n;i++)\n        {\n            for(int j=i+1;j<n;j++)\n            {\n                if(br[i]>i){\n                    swap(br[i],br[j]);\n                    count++;\n                }\n            }\n        }\n        return count;\n    }\n};"1057    },1058    {1059        "title": "Removing Minimum and Maximum From Array",1060        "algo_input": "You are given a 0-indexed array of distinct integers nums.\n\nThere is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.\n\nA deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.\n\nReturn the minimum number of deletions it would take to remove both the minimum and maximum element from the array.\n\n&nbsp;\nExample 1:\n\nInput: nums = [2,10,7,5,4,1,8,6]\nOutput: 5\nExplanation: \nThe minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.\n\n\nExample 2:\n\nInput: nums = [0,-4,19,1,8,-2,-3,5]\nOutput: 3\nExplanation: \nThe minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.\n\n\nExample 3:\n\nInput: nums = [101]\nOutput: 1\nExplanation:  \nThere is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-105 &lt;= nums[i] &lt;= 105\n\tThe integers in nums are distinct.\n\n",1061        "solution_py": "class Solution:\n    def minimumDeletions(self, nums: List[int]) -> int:\n        minFromFront = nums.index(min(nums))\n        maxFromFront = nums.index(max(nums))\n        \n        minFromBack = len(nums) - minFromFront - 1\n        maxFromBack = len(nums) - maxFromFront - 1 \n        \n        return min(max(minFromFront, maxFromFront) + 1,  # Case 1\n                   max(minFromBack, maxFromBack) + 1,    # Case 2\n                   minFromBack + maxFromFront + 2,       # Case 3 \n                   minFromFront + maxFromBack + 2)       # Case 4",1062        "solution_js": "var minimumDeletions = function(nums) {\n    if(nums.length===1)return 1\n    let min=Math.min()\n    let max=Math.max()\n    \n\t// finding min and max\n    for(let n of nums){\n        min=Math.min(n,min)\n        max=Math.max(n,max)\n    };\n    \n\t// obj to store no. of elements to remove if we start from left and if we start from right\n    const obj={\n        left:[],\n        right:[]\n    }\n\t// left[0]-> no. of elements upto min element if we start from left\n\t// left[1]-> no. of elements upto max element if we start from left\n\t// right[0]-> no. of elements upto min element if we start from right\n\t// right[1]-> no. of elements upto max element if we start from right\n    for(let i=0;i<nums.length;i++){\n        if(nums[i]===max){\n            obj['left'][1]=i+1\n            obj['right'][1]=nums.length-i\n        }\n        if(nums[i]===min){\n            obj['left'][0]=i+1\n            obj['right'][0]=nums.length-i\n        }\n    }\n    let total=0\n    const set = new Set();\n\t// if no. of elements to remove min element from left is less than right \n    if(obj['left'][0]<obj['right'][0]){\n        set.add('left');\n        total+=obj['left'][0]\n    }else{\n\t\t// vice versa\n        set.add('right');\n        total+=obj['right'][0]\n    }\n\t// if no. of elements to remove max element from right is less than left \n     if(obj['left'][1]<obj['right'][1]){\n        set.add('left');\n         total+=obj['left'][1]\n    }else{\n\t\t// vice versa\n        set.add('right');\n        total+=obj['right'][1]\n    }\n\t\n\t// if both elements are to be removed from diff direction inorder to remove lesser element\n\t// we have 3 cases: \n\t// one from left and one from right(total), min/max element lies after max/min ele from left,min/max element lies after max/min ele from right\n    if(set.size===2)return Math.min(total,Math.max(...obj['left']),Math.max(...obj['right']));\n    else{\n\t   // if both elements can be removed from same direction(ie. either left or right)\n        return Math.max(...obj[set.values().next().value])\n    }\n    \n};",1063        "solution_java": "class Solution {\n    public int minimumDeletions(int[] nums) {\n        int max = Integer.MIN_VALUE;\n        int min = Integer.MAX_VALUE;\n        int minInd = 0;\n        int maxInd = 0;\n        int n = nums.length;\n        \n        //First Find out the max and min element index\n        for(int i=0;i<n;i++){\n            if(nums[i]>max){\n                max = nums[i];\n                maxInd = i;\n            }\n            \n            if(nums[i]<min){\n                min = nums[i];\n                minInd = i;\n            }\n        }\n        \n        //if both index are same then return the part in which less number of elements are there\n        if(maxInd==minInd){\n            return Math.min(maxInd+1,n-maxInd);\n        }\n        \n        //max element is right side of min element\n        if(maxInd>minInd){\n            int count = Math.min(maxInd+1,n-minInd); // min of all the elements till max element and all the elements to the right of min element\n            int count1 = minInd+1+(n-maxInd); // all elements to the left of min and right of max\n            return Math.min(count,count1); // min of both\n        }\n        // min element is right side of the max element\n        else{\n            int count = Math.min(minInd+1,n-maxInd);\n            int count1 = maxInd+1+(n-minInd);\n            return Math.min(count,count1);\n        }\n        \n    }\n}",1064        "solution_c": "class Solution {\npublic:\n    int minimumDeletions(vector<int>& nums) {\n\n        int indmin, indmax, mini(INT_MAX), maxi(INT_MIN), n(nums.size());\n\n        for (int i=0; i<n; i++)\n        {\n            if (maxi < nums[i]) maxi = nums[i], indmax = i;\n            if (mini > nums[i]) mini = nums[i], indmin = i;\n        }\n\n        int before(min(indmin, indmax)), after(max(indmin, indmax));\n        return min(before+1 + min(n-after, after-before), n-after + min(before+1, after-before));\n    }\n};"1065    },1066    {1067        "title": "RLE Iterator",1068        "algo_input": "We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence.\n\n\n\tFor example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5]. encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr.\n\n\nGiven a run-length encoded array, design an iterator that iterates through it.\n\nImplement the RLEIterator class:\n\n\n\tRLEIterator(int[] encoded) Initializes the object with the encoded array encoded.\n\tint next(int n) Exhausts the next n elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1 instead.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]\nOutput\n[null, 8, 8, 5, -1]\n\nExplanation\nRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= encoding.length &lt;= 1000\n\tencoding.length is even.\n\t0 &lt;= encoding[i] &lt;= 109\n\t1 &lt;= n &lt;= 109\n\tAt most 1000 calls will be made to next.\n\n",1069        "solution_py": "class RLEIterator:\n\n    def __init__(self, encoding: List[int]):\n        self.encoding = encoding\n\n    def next(self, n: int) -> int:\n\n        if self.encoding:\n\n            count = self.encoding[0]\n\n            if count >= n:\n                # Partially exhaust and return the current value.\n                self.encoding[0] -= n\n                return self.encoding[1]\n\n            # Exhaust all of current value and continue.\n            self.encoding = self.encoding[2:]\n            return self.next(n - count)\n\n        return -1",1070        "solution_js": "var RLEIterator = function(encoding) {\n    this.encoding = encoding\n    // Pointer to count index\n    this.index = 0\n}\n\nRLEIterator.prototype.next = function(n) {\n    while (n > 0) {\n        // Move to next count index when the current index is 0\n        if (this.encoding[this.index] === 0) this.index += 2\n        \n        // Too many calls to next, return -1\n        if (this.index >= this.encoding.length) return -1\n        \n        // n goes completely into count\n        if (n <= this.encoding[this.index]) {\n            this.encoding[this.index] -= n\n            n = 0\n        // count goes completely into n\n        } else if (n > this.encoding[this.index]) {\n            n -= this.encoding[this.index]\n            this.encoding[this.index] = 0\n        }\n    }\n\n    return this.encoding[this.index + 1]\n}",1071        "solution_java": "class RLEIterator {\n    \n    long[] prefixEncoded;\n    long processed = 0;\n    int l = 0;\n\n    public RLEIterator(int[] encoding) {\n        int encodeLen = encoding.length;\n        this.prefixEncoded = new long[encodeLen];\n        for(int i=0;i<encodeLen;i+=2) {\n            long prevPrefixSum = 0;\n            if(i > 0) {\n                prevPrefixSum = this.prefixEncoded[i-2];\n            }\n            this.prefixEncoded[i] = encoding[i] + prevPrefixSum;\n            this.prefixEncoded[i+1] = encoding[i+1];\n        }\n    }\n\n    public int next(int n) {\n        int r = this.prefixEncoded.length-2;\n    \n        processed += n;\n        \n        if(l >= this.prefixEncoded.length || processed > this.prefixEncoded[this.prefixEncoded.length - 2]) {\n            return -1;\n        }\n        \n        while(l < r) {\n            int m = (l + ((r-l)/2));\n            if(m % 2 != 0) {\n                m = m - 1;\n            }\n            if(this.prefixEncoded[m] >= processed) {\n                r = m;\n            } else {\n                l = m + 2;\n            }\n        }\n        return l >= this.prefixEncoded.length ? -1: (int) this.prefixEncoded[l + 1];\n    }   \n}",1072        "solution_c": "/*\n    https://leetcode.com/problems/rle-iterator/\n    \n    next(): TC: O(n) in total over n calls\n    Idea is to use two pointers are this.\n    We maintain a ptr that points to the current element bucket. For a given n\n    first iterate through the buckets which have freq < n, this means they won't have the \n    last element.\n    Once the iteration ends, either we will have no elements left or we will be on the bucket\n    with freq >= n. Update the iteration ptr accordingly.\n*/\nclass RLEIterator {\n    vector<int> encoding;\n    // Tracks the even indices\n    int curr = -1;\n    // Tracks the total length of array\n    int len = 0;\npublic:\n    RLEIterator(vector<int>& encoding) {\n        this->encoding = encoding;\n        curr = 0;\n        len = encoding.size();\n    }\n    \n    int next(int n) {\n        // Skip all the number buckets which will be completely exhausted\n        // and we will still have some n left i.e n > 0\n        for(; curr < len && n > 0 && encoding[curr] < n; curr += 2) {\n            // Skip the buckets with 0 frequency\n            if(encoding[curr] == 0)\n                continue;\n            n -= encoding[curr];\n        }\n        \n        int element = -1;\n        //  If we still have elements left with non zero frequency then\n        // the current bucket's frequency will be >= leftover n\n        if(curr < len && encoding[curr] >= n) {\n            // Exhaust the leftover n\n            encoding[curr] -= n;\n            element = encoding[curr+1];\n            // If the bucket is completely exhausted, then move the iterator ptr to next element\n            // for the next function call\n            if(encoding[curr] == 0)\n                curr += 2;\n        }\n        return element;\n    }\n};\n\n/**\n * Your RLEIterator object will be instantiated and called as such:\n * RLEIterator* obj = new RLEIterator(encoding);\n * int param_1 = obj->next(n);\n */"1073    },1074    {1075        "title": "Course Schedule III",1076        "algo_input": "There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.\n\nYou will start on the 1st day and you cannot take two or more courses simultaneously.\n\nReturn the maximum number of courses that you can take.\n\n&nbsp;\nExample 1:\n\nInput: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput: 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n\n\nExample 2:\n\nInput: courses = [[1,2]]\nOutput: 1\n\n\nExample 3:\n\nInput: courses = [[3,2],[4,3]]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= courses.length &lt;= 104\n\t1 &lt;= durationi, lastDayi &lt;= 104\n\n",1077        "solution_py": "class Solution {\npublic:\n    bool static cmp(vector<int> &a,vector<int>&b) {\n        return a[1] < b[1];\n    }\n    int scheduleCourse(vector<vector<int>>& courses) {\n         sort(courses.begin(),courses.end(),cmp);\n         int sm = 0;\n         priority_queue<int> pq;\n         for(int i=0; i<courses.size(); i++) {\n               pq.push(courses[i][0]);  \n               sm+=courses[i][0]; // sum of duration of courses\n               // when there exists a course duration that is invalid and can't be completed on that day!\n               if(sm>courses[i][1]) { \n                    sm-=pq.top();  // remove the biggest invalid course duration!\n                    pq.pop();\n               }\n         }\n        return pq.size();\n    }\n};",1078        "solution_js": "var scheduleCourse = function(courses) {\n  courses.sort((a,b)=>a[1]-b[1]);\n  let pq = new PQ(), currentDay = 0;\n\n  for(let [duration,lastDay] of courses){\n    if(duration > lastDay) continue;    \n \n    if(currentDay + duration <= lastDay){\n      pq.offer(duration);\n      currentDay += duration;\n    }\n    \n    else if(duration < pq.peek() && pq.size())\n      {\n        currentDay += duration-pq.poll();\n        pq.offer(duration);\n      }  \n  }\n  return pq.size();   \n};",1079        "solution_java": "class Solution {\n    public int scheduleCourse(int[][] courses) {\n        Arrays.sort(courses, (a,b)->(a[1]-b[1]));\n        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->(b - a));\n        int time = 0;\n        for(int[] course: courses){\n            time += course[0];\n            pq.add(course[0]);\n            if(time > course[1])\n                time -= pq.poll();\n        }\n        return pq.size();\n    }\n}",1080        "solution_c": "class Solution {\npublic:\n    bool static cmp(vector<int> &a,vector<int>&b) {\n        return a[1] < b[1];\n    }\n    int scheduleCourse(vector<vector<int>>& courses) {\n         sort(courses.begin(),courses.end(),cmp);\n         int sm = 0;\n         priority_queue<int> pq;\n         for(int i=0; i<courses.size(); i++) {\n               pq.push(courses[i][0]);\n               sm+=courses[i][0]; // sum of duration of courses\n               // when there exists a course duration that is invalid and can't be completed on that day!\n               if(sm>courses[i][1]) {\n                    sm-=pq.top(); // remove the biggest invalid course duration!\n                    pq.pop();\n               }\n         }\n        return pq.size();\n    }\n};"1081    },1082    {1083        "title": "Decode XORed Permutation",1084        "algo_input": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.\n\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].\n\nGiven the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.\n\n&nbsp;\nExample 1:\n\nInput: encoded = [3,1]\nOutput: [1,2,3]\nExplanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\n\n\nExample 2:\n\nInput: encoded = [6,5,4,6]\nOutput: [2,4,1,5,3]\n\n\n&nbsp;\nConstraints:\n\n\n\t3 &lt;= n &lt;&nbsp;105\n\tn&nbsp;is odd.\n\tencoded.length == n - 1\n\n",1085        "solution_py": "from functools import reduce\nfrom operator import xor\n\nclass Solution:\n\n    def decode(self, encoded: List[int]) -> List[int]:\n        n = len(encoded) + 1\n        a = reduce(xor, range(1, n+1))\n        b = reduce(xor, encoded[1::2])\n        result = [a ^ b]\n        for y in encoded:\n            result.append(result[-1] ^ y)\n        return result",1086        "solution_js": "var decode = function(encoded) {\n  const n = encoded.length + 1;\n  const perm = Array(n);\n  for (let i = 1; i <= n; i++) { perm[0] ^= i }\n  for (let i = 1; i < n - 1; i += 2) { perm[0] ^= encoded[i] }\n  for (let i = 1; i < n; i++) { perm[i] = perm[i - 1] ^ encoded[i - 1] }\n  return perm;\n};",1087        "solution_java": "class Solution {\n    public int[] decode(int[] encoded) {\n        int n = encoded.length+1, all = 0;\n        for(int i = 1; i <= n; ++i){//a^b^c^d^e^f^g^h^i\n            all ^= i;\n        }\n        int x = 0;\n        for(int v : encoded){//a^b  b^c  c^d  d^e e^f f^g g^h h^i = a^i\n            x ^= v;\n        }\n        int mid = all^x; //a^b^c^d^e^f^g^h^i ^ a^i = b^c^d^e^f^g^h\n        for(int i = 1, j = encoded.length-2; i < j;i += 2, j -= 2){\n        //(b^c^d^e^f^g^h) ^ (b^c ^ g^h ^ d^e ^ e^f) = e\n            mid ^= encoded[i]^encoded[j];\n        }\n        int[] ans = new int[n];\n        ans[n/2] = mid;\n        //a    b    c    d   e   f   g   h   i\n        //a^b  b^c  c^d  d^e e^f f^g g^h h^i\n        for(int i = n/2+1; i < n; ++i){\n            ans[i] = encoded[i-1]^ans[i-1];\n        }\n        for(int i = n/2-1; i >= 0; --i){\n            ans[i] = encoded[i]^ans[i+1];\n        }\n        return ans;\n    }\n}",1088        "solution_c": "class Solution {\npublic:\n    vector<int> decode(vector<int>& encoded) {\n        int n = encoded.size(), x = 0;\n        // XOR of the permutation\n        for(int i = 1; i<=n+1; i++) x ^= i;\n\n        // Xoring X with all the odd positioned elements to find first number\n        for(int i = 1; i<n; i+=2) x ^= encoded[i];\n\n        vector <int> res;\n        res.push_back(x);\n        for(int i = 0; i<n; i++){\n            x ^= encoded[i];\n            res.push_back(x);\n        }\n        return res;\n    }\n};"1089    },1090    {1091        "title": "Sum of Beauty of All Substrings",1092        "algo_input": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.\n\n\n\tFor example, the beauty of \"abaacc\" is 3 - 1 = 2.\n\n\nGiven a string s, return the sum of beauty of all of its substrings.\n\n&nbsp;\nExample 1:\n\nInput: s = \"aabcb\"\nOutput: 5\nExplanation: The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.\n\nExample 2:\n\nInput: s = \"aabcbaa\"\nOutput: 17\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of only lowercase English letters.\n\n",1093        "solution_py": "class Solution:\n    def beautySum(self, s: str) -> int:\n        c, n, ans = Counter(s), len(s), 0\n        for i in range(n-2):\n            x=c.copy()\n            for j in range(n-1,i+1,-1):\n                ans+=max(x.values())-min(x.values())\n                if x[s[j]]==1:\n                    del x[s[j]]\n                else:\n                    x[s[j]]-=1\n            if c[s[i]]==1:\n                del c[s[i]]\n            else:\n                c[s[i]]-=1\n        return ans",1094        "solution_js": "var beautySum = function(s) {\n    const len = s.length;\n\n    let ans = 0;\n    const freq = new Array(26).fill(0);\n\n    for(let i = 0; i < len; i++) {\n        freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;\n        for(let j = i + 1; j < len; j++) {\n            freq[s[j].charCodeAt(0) - 'a'.charCodeAt(0)]++;\n            ans += minMaxDiff(freq);\n        }\n        freq.fill(0);\n    }\n\n    function minMaxDiff(freq) {\n        freq = freq.filter(f => f != 0);\n        return Math.max(...freq) - Math.min(...freq);\n    }\n\n    return ans;\n};",1095        "solution_java": "class Solution {\n    private int getMinCount(int[] charCount) {\n        int min = Integer.MAX_VALUE;\n\t\t\n        for (int i = 0; i < charCount.length; ++i) {\n            if (charCount[i] != 0) {\n                min = Math.min(min, charCount[i]);\n            }\n        }\n\t\t\n        return min;\n    }\n    \n    private int getMaxCount(int[] charCount) {\n        int max = 0;\n\t\t\n        for (int i = 0; i < charCount.length; ++i) {\n            max = Math.max(max, charCount[i]);\n        }\n\t\t\n        return max;\n    }\n    \n    public int beautySum(String s) {\n        int sum = 0;\n        \n        for (int i = 0; i < s.length(); ++i) {\n            int[] charCount = new int[26]; // initialize charCount to all 0\n            \n            for (int j = i; j < s.length(); ++j) {\n                ++charCount[s.charAt(j) - 'a'];\n\n\t\t\t\t// get beauty of substring from i to j\n\t\t\t\tint beauty = getMaxCount(charCount) - getMinCount(charCount);\n                sum += beauty;\n            }\n        }\n        \n        return sum;\n    }\n}",1096        "solution_c": "class Solution {\npublic:\n    int beautySum(string s) {\n        int n = s.length(), sum = 0;\n        for (int i = 0; i < n - 1; i++) {\n            vector<int> dp(26, 0);\n            dp[s[i] - 'a']++;\n            for (int j = i + 1; j < n; j++) {\n                dp[s[j] - 'a']++;\n                int minNum = INT_MAX, maxNum = INT_MIN;\n                for (int k = 0; k < 26; k++) {\n                    if (dp[k]) minNum = min(minNum, dp[k]);\n                    if (dp[k]) maxNum = max(maxNum, dp[k]);\n                }\n                sum = sum + (maxNum - minNum);\n            }\n        }\n        return sum;\n    }\n};"1097    },1098    {1099        "title": "String Without AAA or BBB",1100        "algo_input": "Given two integers a and b, return any string s such that:\n\n\n\ts has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,\n\tThe substring 'aaa' does not occur in s, and\n\tThe substring 'bbb' does not occur in s.\n\n\n&nbsp;\nExample 1:\n\nInput: a = 1, b = 2\nOutput: \"abb\"\nExplanation: \"abb\", \"bab\" and \"bba\" are all correct answers.\n\n\nExample 2:\n\nInput: a = 4, b = 1\nOutput: \"aabaa\"\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= a, b &lt;= 100\n\tIt is guaranteed such an s exists for the given a and b.\n\n",1101        "solution_py": "class Solution:\n    def strWithout3a3b(self, a: int, b: int) -> str:\n        if a<3 and b<3:\n            return 'a'*a+'b'*b\n        s=''\n        if a>=b:\n            k=a//b\n            \n            if a//b!=a/b:\n              \n                k+=1\n            if k>=3:\n                k=2\n            while a>0 or b>0:\n               \n                if a>k:\n                    s+='a'*k  \n                else:\n                    s+='a'*a\n                a-=k\n                if b>0:\n                    s+='b'\n                b-=1\n                if a==b:\n                    k=1\n        if a<b:\n            k=b//a\n            if b//a!=b/a:\n               \n                k+=1\n            if k>=3:\n                k=2\n            while b>0 or a>0:\n                \n                if b>k:\n                    s+='b'*k  \n                else:\n                    s+='b'*b\n                b-=k\n                if a>0:\n                    s+='a'\n                a-=1\n                if a==b:\n                    k=1\n        return s",1102        "solution_js": "/**\n * @param {number} a\n * @param {number} b\n * @return {string}\n */\nvar strWithout3a3b = function(a, b) {\n    let r = '';\n\n    let A = 'a', AA = A + A;\n    let B = 'b', BB = B + B;\n\n    while (a > 0 || b > 0) {\n        if (a > b) {\n            a = calculate(a, A, AA);\n            b = calculate(b, B, BB, true);\n        }\n        else {\n            b = calculate(b, B, BB);\n            a = calculate(a, A, AA, true);\n        }\n    }\n\n    return r;\n\n    function calculate(v, s, ss, l = false) {\n        if (l) {\n            if (v > 0) {\n                r += s, v -= 1;\n            }\n\n            return v;\n        }\n\n        let c = v >= 2 && r[r.length - 1] !== s;\n\n        r += c ? ss : s;\n        v -= c ? 2 : 1;\n\n        return v;\n    }\n};",1103        "solution_java": "class Solution {\n    public String strWithout3a3b(int a, int b) {\n        StringBuilder sb = new StringBuilder();\n        int x = Math.min(a, Math.min(b, Math.abs(a - b))); // TAKE THE MIN OF (a, b, abs(a - b))\n        if (a > b){\n            sb.append(\"aab\".repeat(x));\n            b -= x;\n            a -= 2 * x;\n        }\n        if (a < b){\n            sb.append(\"bba\".repeat(x));\n            b -= 2 * x;\n            a -= x;\n        }\n        if (a == b){\n            sb.append(\"ab\".repeat(a));\n        }\n        if (a == 0){\n            sb.append(\"b\".repeat(b));\n        }\n        if (b == 0){\n            sb.append(\"a\".repeat(a));\n        }\n        return sb.toString();\n    }\n}",1104        "solution_c": "class Solution {\npublic:\n    string strWithout3a3b(int a, int b) {\n        string ans=\"\";\n        while(a and b){\n            if(a > b) ans += \"aab\", a--;\n            else if(b > a) ans +=\"bba\", b--;\n            else ans += \"ab\";\n            a--, b--;\n        }\n        while(a) ans +='a' , a--;\n        while(b) ans +='b' , b--;\n        return ans;\n    }\n};"1105    },1106    {1107        "title": "Maximum Score After Splitting a String",1108        "algo_input": "Given a&nbsp;string s&nbsp;of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).\n\nThe score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.\n\n&nbsp;\nExample 1:\n\nInput: s = \"011101\"\nOutput: 5 \nExplanation: \nAll possible ways of splitting s into two non-empty substrings are:\nleft = \"0\" and right = \"11101\", score = 1 + 4 = 5 \nleft = \"01\" and right = \"1101\", score = 1 + 3 = 4 \nleft = \"011\" and right = \"101\", score = 1 + 2 = 3 \nleft = \"0111\" and right = \"01\", score = 1 + 1 = 2 \nleft = \"01110\" and right = \"1\", score = 2 + 1 = 3\n\n\nExample 2:\n\nInput: s = \"00111\"\nOutput: 5\nExplanation: When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5\n\n\nExample 3:\n\nInput: s = \"1111\"\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= s.length &lt;= 500\n\tThe string s consists of characters '0' and '1' only.\n\n",1109        "solution_py": "class Solution:\n    def maxScore(self, s: str) -> int:\n        m0=0\n        m1=0\n        for i in s:\n            if i==\"0\":\n                m0+=1\n            else:\n                m1+=1\n        if m0==0 or m1==0:\n            return max(m0-1,m1-1)\n        l=len(s)\n        i=0\n        max_=0\n        c0=0\n        c1=m1\n        idx=-1\n        while i <l:\n            if s[i]==\"0\":\n                c0+=1\n            else:\n                c1-=1\n            if max_<c1+c0:\n                max_=c1+c0\n                idx=i\n            max_=max(max_,c1+c0)\n            i+=1\n        if idx==l-1:\n            return max_-1\n        return max_",1110        "solution_js": " * @param {string} s\n * @return {number}\n */\nvar maxScore = function(s) {\n    const leftScores = []\n    const rightScores = []\n    let score = 0\n    for (let i = 0; i < s.length-1; i++) {\n        if (s[i] === '0') \n            score++\n        leftScores.push(score)\n    }\n    score = 0\n    for (let i = s.length-1; i > 0; i--) {\n        if (s[i] === '1')\n            score++\n        rightScores.unshift(score)\n    }\n    \n    const scores = leftScores.map((val, idx) => val + rightScores[idx])\n    return Math.max(...scores)\n};",1111        "solution_java": "class Solution {\n    public int maxScore(String s) {\n        int max =0;\n        for(int i =0; i<s.length()-1; i++)\n            max = Math.max(max,s.substring(0,i+1).replace(\"1\",\"\").length()+s.substring(i+1).replace(\"0\",\"\").length());\n        \n        return max;\n    }\n}",1112        "solution_c": "class Solution {\npublic:\n    int maxScore(string s) {\n        int ones = 0;\n        int res = -s.length();\n        for (int i = 0; i < s.length() - 1; i++) {\n            if (s[i] == '1') ones += 2;\n            if (i - ones > res) res = i - ones;\n        };\n\n        ones >>= 1;\n        if (s[s.length() - 1] == '1') ones++;\n\n        return ones + res + 1;\n    }\n};"1113    },1114    {1115        "title": "Design Browser History",1116        "algo_input": "You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.\n\nImplement the BrowserHistory class:\n\n\n\tBrowserHistory(string homepage) Initializes the object with the homepage&nbsp;of the browser.\n\tvoid visit(string url)&nbsp;Visits&nbsp;url from the current page. It clears up all the forward history.\n\tstring back(int steps)&nbsp;Move steps back in history. If you can only return x steps in the history and steps &gt; x, you will&nbsp;return only x steps. Return the current url&nbsp;after moving back in history at most steps.\n\tstring forward(int steps)&nbsp;Move steps forward in history. If you can only forward x steps in the history and steps &gt; x, you will&nbsp;forward only&nbsp;x steps. Return the current url&nbsp;after forwarding in history at most steps.\n\n\n&nbsp;\nExample:\n\nInput:\n[\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n[[\"leetcode.com\"],[\"google.com\"],[\"facebook.com\"],[\"youtube.com\"],[1],[1],[1],[\"linkedin.com\"],[2],[2],[7]]\nOutput:\n[null,null,null,null,\"facebook.com\",\"google.com\",\"facebook.com\",null,\"linkedin.com\",\"google.com\",\"leetcode.com\"]\n\nExplanation:\nBrowserHistory browserHistory = new BrowserHistory(\"leetcode.com\");\nbrowserHistory.visit(\"google.com\");       // You are in \"leetcode.com\". Visit \"google.com\"\nbrowserHistory.visit(\"facebook.com\");     // You are in \"google.com\". Visit \"facebook.com\"\nbrowserHistory.visit(\"youtube.com\");      // You are in \"facebook.com\". Visit \"youtube.com\"\nbrowserHistory.back(1);                   // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.back(1);                   // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\nbrowserHistory.forward(1);                // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\nbrowserHistory.visit(\"linkedin.com\");     // You are in \"facebook.com\". Visit \"linkedin.com\"\nbrowserHistory.forward(2);                // You are in \"linkedin.com\", you cannot move forward any steps.\nbrowserHistory.back(2);                   // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\nbrowserHistory.back(7);                   // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= homepage.length &lt;= 20\n\t1 &lt;= url.length &lt;= 20\n\t1 &lt;= steps &lt;= 100\n\thomepage and url consist of&nbsp; '.' or lower case English letters.\n\tAt most 5000&nbsp;calls will be made to visit, back, and forward.\n\n",1117        "solution_py": "class Node:\n    def __init__(self, val):\n        self.val = val\n        self.prev = None\n        self.next = None\n\nclass BrowserHistory:\n    def __init__(self, web):\n        self.Node = Node(web)\n        self.ptr = self.Node\n\n    def visit(self, web):\n        self.newWeb = Node(web)\n        self.newWeb.prev = self.ptr\n        self.ptr.next = self.newWeb\n        self.ptr = self.ptr.next\n\n    def back(self, steps):\n        i = 0\n        while i < steps:\n            if self.ptr.prev:\n                self.ptr = self.ptr.prev\n            else:\n                break\n            i += 1\n        return self.ptr.val\n\n    def forward(self, steps):\n        i = 0\n        while i < steps:\n            if self.ptr.next:\n                self.ptr = self.ptr.next\n            else:\n                break\n            i += 1\n        return self.ptr.val",1118        "solution_js": "var BrowserHistory = function(homepage) {\n    this.page = {\n        url: homepage,\n        back: null,\n        next: null,\n    };\n};\n\nBrowserHistory.prototype.visit = function(url) {\n    this.page.next = {\n        url,\n        back: this.page,\n        next: null\n    };\n    this.page = this.page.next;\n};\n\nBrowserHistory.prototype.back = function(steps) {\n    while (this.page.back && steps) {\n        this.page = this.page.back;\n        steps--;\n    }\n    \n    return this.page.url;\n};\n\nBrowserHistory.prototype.forward = function(steps) {\n    while (this.page.next && steps) {\n        this.page = this.page.next;\n        steps--;\n    }\n    \n    return this.page.url;\n};",1119        "solution_java": "class BrowserHistory {\n    int current;\n    ArrayList<String> history;\n    public BrowserHistory(String homepage) {\n        this.history = new ArrayList<>();\n        history.add(homepage);\n        this.current = 0;\n    }\n\n    public void visit(String url) {\n        while (history.size()-1 > current) {//delete forward history\n            history.remove(history.size()-1);//which means delete everything beyond our current website\n        }\n        history.add(url);\n        ++current;\n    }\n\n    public String back(int steps) {\n        if (steps>current) current = 0;//if we can't get enough back, we return first thing in our history\n        else current -= steps;//if there will be no arrayindexoutofrange error, go back\n        return history.get(current);//return current webpage\n    }\n\n    public String forward(int steps) {\n        //if we are going to move more than our arraylist, then we will return the last element\n        if (steps+current>=history.size()) current = history.size() - 1;\n        else current += steps;//if there will be no arrayindexoutofrange error, go forward!\n        return history.get(current);//return the current webpage\n    }\n}\n\n/**\n * Your BrowserHistory object will be instantiated and called as such:\n * BrowserHistory obj = new BrowserHistory(homepage);\n * obj.visit(url);\n * String param_2 = obj.back(steps);\n * String param_3 = obj.forward(steps);\n */",1120        "solution_c": "class Node{\npublic:\n    string url;\n    Node* next;\n    Node* back;\n    Node(string s){\n        url = s;\n        next = NULL;\n        back = NULL;\n    }\n};\n\nclass BrowserHistory {\n    Node* head;\npublic:\n    BrowserHistory(string homepage) {\n        head = new Node(homepage);\n    }\n\n    void visit(string url) {\n        Node* ptr = new Node(url);\n        head->next = ptr;\n        ptr->back = head;\n        head = ptr;\n    }\n\n    string back(int steps) {\n        while(head->back && steps--){ head = head->back; }\n        return head->url;\n    }\n\n    string forward(int steps) {\n        while(head->next && steps--){ head = head->next; }\n        return head->url;\n    }\n};"1121    },1122    {1123        "title": "Flip String to Monotone Increasing",1124        "algo_input": "A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).\n\nYou are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.\n\nReturn the minimum number of flips to make s monotone increasing.\n\n&nbsp;\nExample 1:\n\nInput: s = \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\n\n\nExample 2:\n\nInput: s = \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\n\n\nExample 3:\n\nInput: s = \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts[i] is either '0' or '1'.\n\n",1125        "solution_py": "class Solution:\n    def minFlipsMonoIncr(self, s: str) -> int:\n        n = len(s)\n        min_flip = n\n        one_left = 0\n        # zero_right = 0\n        # for c in s:\n        #     if c == \"0\":\n        #         zero_right += 1\n        \n        zero_right = s.count(\"0\") # since we will start with 11...11 then every zero in s will be on the right side of the border\n        \n        # for each i imagine that we have the borderline at i index any index >= i will be 1 and index < i will be 0.\n        # i = 0, n = 5 -> 11111\n        # i = 1, n = 5 -> 01111\n        # i = 5        -> 00000\n        for i in range(n + 1):\n            # the number of flip will be equal number of 1 on the left side of the border + number of zero on the right side of the border\n            # from example     00110\n            #                    v \n            # comparing with   00111  : i = 2, one_left = 0, zero_right = 1, then we have to do 0 + 1 flip in this i\n            min_flip = min(min_flip,one_left+zero_right)\n            \n            # edge case for i = n or all zero (00...00)\n            if i == len(s):\n                continue\n            # reduce count of zero_right when 0 is moving to the 0-zone or left side of border\n            if s[i] == \"0\":\n                zero_right -= 1\n            else:\n                one_left += 1 # increase one on the left side when we move 1 into the left side\n        \n        return min_flip\n            \n            ",1126        "solution_js": "function getPrefixSumArray(s) {\n    const prefixSumOfOnes = Array(s.length).fill(0);\n    \n    let currentSum = 0;\n    for (let x = 0; x < s.length; x++) {\n        if (s[x] === '1')\n            currentSum++;\n        \n        prefixSumOfOnes[x] = currentSum;\n    }\n    \n    return prefixSumOfOnes;\n}\n\nvar minFlipsMonoIncr = function(s) {\n    const prefixSumOfOnes = getPrefixSumArray(s);\n    \n    let answer = prefixSumOfOnes[s.length - 1]; // Case where we want to change to '0000'\n    \n    for (let x = 0; x < s.length; x++) {\n        const sizeOfRightHandSide = s.length - x;\n        let numChangesRequired = null;\n        \n        if (x === 0) { \n            // Case where we want to change to '1111'\n            const numOfOnesToChangeToZero = 0;\n            \n            const numOfOnesOnRightHandSide = prefixSumOfOnes[s.length - 1];\n            const numOfZerosToChangeToOne = sizeOfRightHandSide - numOfOnesOnRightHandSide;\n            \n            numChangesRequired = numOfOnesToChangeToZero + numOfZerosToChangeToOne;\n        }\n        else { \n            // Cases like '0111', '0011', '0001'\n            const numOfOnesToChangeToZero = prefixSumOfOnes[x - 1];\n            \n            const numOfOnesOnRightHandSide = prefixSumOfOnes[s.length - 1] - prefixSumOfOnes[x - 1];\n            const numOfZerosToChangeToOne = sizeOfRightHandSide - numOfOnesOnRightHandSide;\n            \n            numChangesRequired = numOfOnesToChangeToZero + numOfZerosToChangeToOne;\n        }\n        \n        answer = Math.min(answer, numChangesRequired);\n    }\n    \n    return answer;\n};",1127        "solution_java": "class Solution {\n    public int minFlipsMonoIncr(String s) {\n        int n = s.length();\n        int zeroToOne =0;\n        int countOfOnes=0;\n        for(int i=0;i<n;i++)\n        {\n            if(s.charAt(i)=='0')\n                zeroToOne=Math.min(zeroToOne+1,countOfOnes);\n            else\n                countOfOnes=countOfOnes+1;\n        }\n        return zeroToOne;\n        \n    }\n}",1128        "solution_c": "class Solution {\npublic:\n    int minFlipsMonoIncr(string s) {\n        //assume start making 1 from i th index\n        // what number of 0s we need to flip at right side\n        // what number of 1s we need to flip at left side\n        // for this maintain prefix and suffix\n\n        int n = s.size();\n        vector<int> noOfZerosToRight(n,0); // R to L\n        vector<int> noOfOnesToLeft(n,0); // L to R\n\n        if(s[0] == '1') noOfOnesToLeft[0] = 1;\n        for(int i=1;i<n;i++){\n            if(s[i] == '1') noOfOnesToLeft[i] = noOfOnesToLeft[i-1] + 1;\n            else noOfOnesToLeft[i] = noOfOnesToLeft[i-1];\n        }\n\n        if(s[n-1] == '0') noOfZerosToRight[n-1] = 1;\n        for(int i=n-2;i>=0;i--){\n            if(s[i] == '0') noOfZerosToRight[i] = noOfZerosToRight[i+1] + 1;\n            else noOfZerosToRight[i] = noOfZerosToRight[i+1];\n        }\n\n        // starting treating i as partition of 0 and 1:\n        // 0 at the lefts and 1 at the rights including i:\n        int ans = 1e9;\n        for(int i=0;i<n;i++){\n            int leftFlips = 0; //when we want all 1s\n            int rightFlips = noOfZerosToRight[i];\n\n            if(i-1 >= 0) leftFlips = noOfOnesToLeft[i-1];\n            ans = min(ans, (leftFlips + rightFlips));\n        }\n\n        ans = min(ans, noOfOnesToLeft.back() + 0); //when want all 0s\n        return ans;\n    }\n    //O(N) + O(N)\n};"1129    },1130    {1131        "title": "Find Mode in Binary Search Tree",1132        "algo_input": "Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.\n\nIf the tree has more than one mode, return them in any order.\n\nAssume a BST is defined as follows:\n\n\n\tThe left subtree of a node contains only nodes with keys less than or equal to the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than or equal to the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [1,null,2,2]\nOutput: [2]\n\n\nExample 2:\n\nInput: root = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-105 &lt;= Node.val &lt;= 105\n\n\n&nbsp;\nFollow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).",1133        "solution_py": "class Solution(object):\n    prev = None\n    max_count = 0\n    current_count = 0 \n    result = []\n\n    def findMode(self, root):\n        self.dfs(root)\n        return self.result\n\n    def dfs(self, node):\n        if not node: return\n        self.dfs(node.left)\n        self.current_count = 1 if node.val != self.prev else self.current_count + 1\n        if self.current_count == self.max_count:\n            self.result.append(node.val)\n        elif self.current_count > self.max_count:\n            self.result = [node.val]\n            self.max_count = self.current_count\n        self.prev = node.val\n        self.dfs(node.right)",1134        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n *     this.val = (val===undefined ? 0 : val)\n *     this.left = (left===undefined ? null : left)\n *     this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {number[]}\n */\nvar findMode = function(root) {\n\tconst dup = new Map();\n\n\thelper(root, dup);\n\n\tlet res = [];\n\tlet max = Number.MIN_VALUE;\n\tfor(const [key, value] of dup) {\n\t\tif (value > 1 && value >= max) {\n\t\t\tres.push(key);\n\t\t\tmax = Math.max(max, value);\n\t\t}\n\t}\n\n\treturn res.length > 0 ? res : [...dup.keys()];\n};\n\nfunction helper(root, dup) {\n\tif(root !== null) {\n\t\tdup.set(root.val, ~~dup.get(root.val) + 1);\n\t\thelper(root.left, dup);\n\t\thelper(root.right, dup);\n\t}\n}",1135        "solution_java": "class Solution {\n    public int[] findMode(TreeNode root) {\n        if(root==null) return new int[0];\n        Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //we are taking map to count each and every value of the tree and the no of times they occurs in the tree\n        Queue<TreeNode> qu = new LinkedList<TreeNode>(); // to itereate over the tree\n        List<Integer> list = new ArrayList<Integer>(); //to save our result into a dynamic arraylist then will convert into static array for return it\n        qu.add(root);                     // add the first root node into queue to iterate over the tree\n        while(!qu.isEmpty()) {   \n            TreeNode tmp = qu.poll();               //we poll out the node which is last inputed to the queue\n            if(map.containsKey(tmp.val)) {           //we are checking through the map wheather the value this node have already stored into the map or not\n                map.put(tmp.val, map.get(tmp.val)+1);     //the value is already stored then we just increase the count by 1\n            }\n            else {\n                map.put(tmp.val, 1);     //if the value is unique then we store it to the map with the count 1\n            }\n            if(tmp.left!=null) qu.add(tmp.left);    //this way we are checking wheather left node has any value or not respect to the current poped element of queue\n            if(tmp.right!=null) qu.add(tmp.right);    //the same thing of the above just this is for right node of respective poped out node\n        }\n        int max = Integer.MIN_VALUE;   //we are taking it because of requirement to identify highest no of repeated node available in this tree \n        for(Integer key : map.keySet()) {  //we are using keySet() for iterating over the map here key is differernt nodes and value is the no of count they have in this tree\n            if(map.get(key)>max) { //if anything we find have greater value then previous maximum no of node like 2 2 2 - value 3, 3 3 3 3 - value 4 so now 4 is the maximum now \n                list.clear(); //just to clear previous data that are stored into that list\n                max = map.get(key);   //now max will replaced by the new no of count of a node\n                list.add(key);    //we are adding the key which has most no of count\n            }\n            else if(max==map.get(key)) { //if we found another node which also has present maximum no of node count in the tree\n                list.add(key);  //we are also adding those key\n            }\n        }\n\t\t//now we just create an array transfer hole data that arraylist has and then return\n        int[] res = new int[list.size()];\n        for(int i=0; i<list.size(); i++) {\n            res[i] = list.get(i);\n        }\n        return res;\n    }\n}",1136        "solution_c": "class Solution {\npublic:\n\n    void inorder(TreeNode* root, unordered_map<int,int>& mp){\n        if(root==NULL) return;\n\n        inorder(root->left, mp);\n        mp[root->val]++;\n        inorder(root->right, mp);\n    }\n\n    vector<int> findMode(TreeNode* root) {\n        unordered_map<int,int> mp;\n        int maxf=INT_MIN;\n        vector<int> ans;\n\n        inorder(root, mp);\n\n        for(auto i=mp.begin(); i!=mp.end(); i++){\n            maxf = max(i->second, maxf);\n        }\n\n        for(auto i=mp.begin(); i!=mp.end(); i++){\n            if(i->second==maxf) ans.push_back(i->first);\n        }\n\n        return ans;\n\n    }\n};"1137    },1138    {1139        "title": "Delivering Boxes from Storage to Ports",1140        "algo_input": "You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.\n\nYou are given an array boxes, where boxes[i] = [ports​​i​, weighti], and three integers portsCount, maxBoxes, and maxWeight.\n\n\n\tports​​i is the port where you need to deliver the ith box and weightsi is the weight of the ith box.\n\tportsCount is the number of ports.\n\tmaxBoxes and maxWeight are the respective box and weight limits of the ship.\n\n\nThe boxes need to be delivered in the order they are given. The ship will follow these steps:\n\n\n\tThe ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.\n\tFor each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.\n\tThe ship then makes a return trip to storage to take more boxes from the queue.\n\n\nThe ship must end at storage after all the boxes have been delivered.\n\nReturn the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n\n&nbsp;\nExample 1:\n\nInput: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput: 4\nExplanation: The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n\n\nExample 2:\n\nInput: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput: 6\nExplanation: The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\n\nExample 3:\n\nInput: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput: 6\nExplanation: The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= boxes.length &lt;= 105\n\t1 &lt;= portsCount, maxBoxes, maxWeight &lt;= 105\n\t1 &lt;= ports​​i &lt;= portsCount\n\t1 &lt;= weightsi &lt;= maxWeight\n\n",1141        "solution_py": "from sortedcontainers import SortedList as MonoQueue\nclass Solution:\n    def boxDelivering(self, A, __, B, W):\n        n = len(A)\n        def slidingWindow():\n            l=0\n            cW = 0\n            for r in range(n):\n                cW+=A[r][1]\n                while cW>W or r-l+1>B:\n                    cW-=A[l][1]\n                    l+=1\n                yield l,r\n        Seg=MonoQueue(key=lambda t:t[1])\n        addAll = 0\n        olddp = 0\n        for l,r in slidingWindow():\n            if r!=0:\n                addAll+= ( A[r][0]!=A[r-1][0] )\n            Seg.add((r, olddp-addAll+2))\n            while Seg[0][0]<l:\n                Seg.pop(0)\n            olddp = Seg[0][1]+addAll\n        return olddp",1142        "solution_js": "/**\n * @param {number[][]} boxes\n * @param {number} portsCount\n * @param {number} maxBoxes\n * @param {number} maxWeight\n * @return {number}\n */\nvar boxDelivering = function(boxes, portsCount, maxBoxes, maxWeight) {\n\n    const trips = Array(boxes.length + 1).fill(0);\n    let left = 0;\n    let diff = 0;\n\n    for (let right = 0; right < boxes.length; right++) {\n        maxBoxes--;\n        maxWeight -= boxes[right][1];\n        if (right > 0 && boxes[right][0] !== boxes[right - 1][0]) diff++;\n\n        while (maxBoxes < 0 || maxWeight < 0 || (left < right && trips[left + 1] === trips[left])) {\n            maxBoxes++;\n            maxWeight += boxes[left++][1];\n            if (boxes[left][0] !== boxes[left - 1][0]) diff--;\n        }\n\n        trips[right + 1] = diff + 2 + trips[left];\n    }\n\n    return trips[boxes.length];\n};",1143        "solution_java": "class Solution {\n    public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {\n        int[] diffCity = new int[boxes.length+1];\n        int[] weights = new int[boxes.length+1];\n        \n        for (int i = 0; i < boxes.length; i++) {\n            diffCity[i+1] = diffCity[i] + ((i != 0 && boxes[i][0] == boxes[i-1][0]) ? 0 : 1);\n            weights[i+1] = weights[i] + boxes[i][1];\n        }\n        int[] dp = new int[boxes.length+1];\n        Arrays.fill(dp, Integer.MAX_VALUE);\n        dp[0] = 0;\n        diffCity[0] = 1;\n        for (int i = 1; i <= boxes.length; i++) { // offset by 1 since our above logic reaches dp[-1]\n            for (int j = i - 1; j >= 0; j--) {\n                int dC= diffCity[i] - diffCity[j+1]; // computes # of different cities from i to j. (add 1 to j is necessary here)\n                int w = weights[i] - weights[j]; \n                int b = i - j;\n                if (b <= maxBoxes && w <= maxWeight) {\n                    dp[i] = Math.min(dp[i], 2 + dC + dp[j]); \n                }\n            }\n        }\n        return dp[boxes.length];\n    }\n}",1144        "solution_c": "class Solution {\npublic:\n    vector<int> stree;\n    void update(int tidx, int s, int e, int idx, int val){\n        if(s == e){\n            stree[tidx] = val;\n            return;\n        }\n        int mid = (s + e)/2;\n        if(idx <= mid) update(2*tidx, s, mid, idx, val);\n        else update(2*tidx+1, mid+1, e, idx, val);\n        stree[tidx] = min(stree[2*tidx], stree[2*tidx+1]);\n    }\n    int query(int tidx, int s, int e, int l, int r){\n        if(s > r or e < l) return INT_MAX;\n        else if(s >= l and e <= r) return stree[tidx];\n        int mid = (s + e)/2;\n        int left = query(2*tidx, s, mid, l, r);\n        int right = query(2*tidx+1, mid+1, e, l, r);\n        return min(left, right);\n    }\n    int boxDelivering(vector<vector<int>>& boxes, int port, int box, int weigh) {\n        int n = boxes.size();\n        vector<long long> trips(n+1), pref(n);\n        trips[0] = 0, pref[0] = boxes[0][1];\n        for(int i=1;i<n;i++){\n            pref[i] = pref[i-1] + boxes[i][1];\n            if(boxes[i][0] != boxes[i-1][0]){\n                trips[i] = trips[i-1] + 1;\n            }\n            else{\n                trips[i] = trips[i-1];\n            }\n        }\n        trips[n] = trips[n-1];\n        vector<long long> dp(n);\n        stree = vector<int> (4*n + 1, INT_MAX);\n        update(1, 0, n-1, 0, 0);\n        // dp[i] = dp[j] + (trips[i] - trips[j+1]) + 2\n        for(int i=0;i<n;i++){\n            // L nikalo ?\n            int l = 0, r = i;\n            while(l < r){\n                int mid = (l + r)/2;\n                long long tot = pref[i] - ((mid-1>=0)?pref[mid-1]:0);\n                if(tot <= weigh and i-mid+1 <= box){\n                    r = mid;\n                }\n                else{\n                    l = mid + 1;\n                }\n            }\n            int mini = query(1, 0, n, l, i);\n            dp[i] = mini + trips[i] + 2;\n            update(1, 0, n, i+1, dp[i] - trips[i+1]);\n        }\n        return dp[n-1];\n    }\n};"1145    },1146    {1147        "title": "Compare Version Numbers",1148        "algo_input": "Given two version numbers,&nbsp;version1 and version2, compare them.\n\n\n\n\nVersion numbers consist of one or more revisions joined by a dot&nbsp;'.'. Each revision&nbsp;consists of digits&nbsp;and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example&nbsp;2.5.33&nbsp;and&nbsp;0.1&nbsp;are valid version numbers.\n\nTo compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their&nbsp;integer value ignoring any leading zeros. This means that revisions&nbsp;1&nbsp;and&nbsp;001&nbsp;are considered&nbsp;equal. If a version number does not specify a revision at an index, then&nbsp;treat the revision as&nbsp;0. For example, version&nbsp;1.0 is less than version&nbsp;1.1&nbsp;because their revision 0s are the same, but their revision 1s are&nbsp;0&nbsp;and&nbsp;1&nbsp;respectively, and&nbsp;0 &lt; 1.\n\nReturn the following:\n\n\n\tIf version1 &lt; version2, return -1.\n\tIf version1 &gt; version2, return 1.\n\tOtherwise, return 0.\n\n\n&nbsp;\nExample 1:\n\nInput: version1 = \"1.01\", version2 = \"1.001\"\nOutput: 0\nExplanation: Ignoring leading zeroes, both \"01\" and \"001\" represent the same integer \"1\".\n\n\nExample 2:\n\nInput: version1 = \"1.0\", version2 = \"1.0.0\"\nOutput: 0\nExplanation: version1 does not specify revision 2, which means it is treated as \"0\".\n\n\nExample 3:\n\nInput: version1 = \"0.1\", version2 = \"1.1\"\nOutput: -1\nExplanation: version1's revision 0 is \"0\", while version2's revision 0 is \"1\". 0 &lt; 1, so version1 &lt; version2.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= version1.length, version2.length &lt;= 500\n\tversion1 and version2&nbsp;only contain digits and '.'.\n\tversion1 and version2&nbsp;are valid version numbers.\n\tAll the given revisions in&nbsp;version1 and version2&nbsp;can be stored in&nbsp;a&nbsp;32-bit integer.\n\n",1149        "solution_py": "class Solution:\n    def compareVersion(self, v1: str, v2: str) -> int:\n        v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.')))  \n        for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):\n            if rev1 == rev2:\n                continue\n\n            return -1 if rev1 < rev2 else 1 \n\n        return 0",1150        "solution_js": "var compareVersion = function(version1, version2) {\n    const v1 = version1.split('.')\n    const v2 = version2.split('.')\n\t\n\tlet max=Math.max(v1.length,v2.length);\n    \n    for(let i=0;i<max;i++){\n        if(v1[i]&&v2[i]){ // if both v1 and v2 are present\n            if(+v1[i] > +v2[i])return 1\n            else if(+v1[i] < +v2[i])return -1\n        }else if(v1[i] && +v1[i]!==0){ // if v1 is larger than v2 but make sure those digits are not 0.\n            return 1\n        }else if(v2[i] && +v2[i]!==0){ // if v2 is larger than v1 but make sure those digits are not 0.\n            return -1\n        }\n    }\n    return 0\n};",1151        "solution_java": "class Solution {\n    public int compareVersion(String version1, String version2) {\n\t//Here we are going to Split the numbers by  . but since we cannot do that in java we will replace . with # and then do it \n        version1=version1.replace('.', '#');\n        version2=version2.replace('.', '#');\n        \n        String v1[]=version1.split(\"#\");\n        String v2[]=version2.split(\"#\");\n        \n        int i=0;\n        \n\t\t\n        while(i<v1.length || i<v2.length){\n            //we will have inital value  0 as our array can out out index so taking that in considerration \n            Integer i1= 0;\n            Integer i2= 0;\n\t\t\t//Here we are using removeing Zero function which will remove all the zeros before the string \n            if(i<v1.length){\n                i1= Integer.valueOf(removezero(v1[i]));\n            }\n            if(i<v2.length){\n                i2= Integer.valueOf(removezero(v2[i]));\n            }\n            //and the rest is just the comparison\n            if(i1<i2){\n                return -1;\n            }\n            else if(i1>i2){\n                return 1;\n            }\n            i++;\n        }\n\t\t//if all the statments are false then at last we can say that they are equal\n        return 0;\n    }\n    String removezero(String s){\n        String result =\"\";\n        int i =0;\n        while(i<s.length()){\n            if(s.charAt(i)!='0'){\n                result=s.substring(i, s.length());\n                break;\n            }\n            i++;\n        }\n        return result!=\"\"?result:\"0\";\n    }\n}",1152        "solution_c": "class Solution {\npublic:\n    int compareVersion(string v1, string v2) {\n        int ans = 0;\n        int n1 = v1.size(), n2 = v2.size();\n        \n        for(int i=0,j=0; i<n1 || j<n2; ++i, ++j) {\n            \n            string s1 = \"\", s2 = \"\";\n\n            while(i<n1 && v1[i] != '.') {\n                if(s1.size() == 0 && v1[i] == '0') {\n                    ++i; continue;\n                }\n                \n                s1 += v1[i++];\n            }\n            \n            while(j<n2 && v2[j] != '.') {\n                if(s2.size() == 0 && v2[j] == '0') {\n                    ++j; continue;\n                }\n                \n                s2 += v2[j++];\n            }\n            \n            if(s1.size() < s2.size()) return -1;\n            else if(s2.size() < s1.size()) return 1;\n            \n            ans = s1.compare(s2);\n            if(ans < 0) return -1;\n            else if(ans > 0) return 1;\n        }\n        \n        return 0;\n        \n    }\n};"1153    },1154    {1155        "title": "Brick Wall",1156        "algo_input": "There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.\n\nDraw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.\n\nGiven the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.\n\n&nbsp;\nExample 1:\n\nInput: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\nOutput: 2\n\n\nExample 2:\n\nInput: wall = [[1],[1],[1]]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\tn == wall.length\n\t1 &lt;= n &lt;= 104\n\t1 &lt;= wall[i].length &lt;= 104\n\t1 &lt;= sum(wall[i].length) &lt;= 2 * 104\n\tsum(wall[i]) is the same for each row i.\n\t1 &lt;= wall[i][j] &lt;= 231 - 1\n\n",1157        "solution_py": "class Solution:\n    def leastBricks(self, wall: List[List[int]]) -> int:\n        m = len(wall)\n        ctr = {}\n        res = m\n        for i in range(m):\n            n = len(wall[i])\n            curr = 0\n            for j in range(n - 1):\n                curr += wall[i][j]\n                x = ctr.get(curr, m) - 1\n                ctr[curr] = x\n                res = min(res, x)\n        return res",1158        "solution_js": "var leastBricks = function(wall) {\n\tconst hash = wall.reduce((map, row) => {\n\t\tlet sum = 0;\n\n\t\tfor (let index = 0; index < row.length - 1; index++) {\n\t\t\tsum += row[index];\n\t\t\tconst hashCount = map.get(sum) ?? 0;\n\t\t\tmap.set(sum, hashCount + 1);\n\t\t}\n\t\treturn map;\n\t}, new Map());\n\n\tlet result = wall.length;\n\thash.forEach(value => result = Math.min(result, wall.length - value));\n\n\treturn result;\n};",1159        "solution_java": "class Solution {\n    public int leastBricks(List<List<Integer>> wall) \n    {\n        HashMap<Integer, Integer> edge_frequency = new HashMap<>(); //HashMap to store the number of common edges among the rows\n        int max_frequency = 0; //Variable to store the frequency of most occuring edge\n        \n        for(int row=0; row<wall.size(); row++) //Iterating through each row\n        {\n            int edge_postion = 0; //Variable to store different edge postion\n            \n            for(int brick_no=0; brick_no<wall.get(row).size()-1; brick_no++) //Iterating through each brick inside a row\n            {\n                int current_brick_length = wall.get(row).get(brick_no); //Length of the current brick\n                edge_postion = edge_postion + current_brick_length; //Next Edge Position = Previous Edge Position + Current Brick's Length\n                edge_frequency.put(edge_postion,edge_frequency.getOrDefault(edge_postion,0)+1); //Incrementing the Frequency of just calculated Edge Postion\n                max_frequency = Math.max(edge_frequency.get(edge_postion),max_frequency); //Comparing the \"Frequency of just calculated Edge Postion\" with \"Max Frequency seen till now\" & storing whichever is greater.\n            }\n        }\n        return wall.size() - max_frequency; // returning (Number of Bricks Crossed by Line) i.e. (Number of Rows in Wall - Frequency of Most Occuring Edge)\n    }\n}",1160        "solution_c": "class Solution {\npublic:\n    int leastBricks(vector<vector<int>>& wall) {\n        vector<unordered_set<int>> v;\n        for(auto i : wall) {\n            int cs = 0;\n            unordered_set<int> st;\n            for(int j=0; j<i.size() - 1; j++) {\n                cs += i[j];\n                st.insert(cs);\n            }\n            v.push_back(st);\n        }\n        \n        unordered_map<int, int> m;\n        for(auto i : v) {\n            for(auto j : i) m[j]++;\n        }\n        \n        int mxfr = INT_MIN, mxel;\n        for(auto i : m) {\n            if(i.second > mxfr) mxel = i.first, mxfr = i.second;\n        }\n        \n        int ans = 0;\n        for(auto s : v) {\n            if(s.find(mxel) == s.end()) ans++;\n        }\n        return ans;\n    }\n};"1161    },1162    {1163        "title": "Count Vowel Substrings of a String",1164        "algo_input": "A substring is a contiguous (non-empty) sequence of characters within a string.\n\nA vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.\n\nGiven a string word, return the number of vowel substrings in word.\n\n&nbsp;\nExample 1:\n\nInput: word = \"aeiouu\"\nOutput: 2\nExplanation: The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"\n\n\nExample 2:\n\nInput: word = \"unicornarihan\"\nOutput: 0\nExplanation: Not all 5 vowels are present, so there are no vowel substrings.\n\n\nExample 3:\n\nInput: word = \"cuaieuouac\"\nOutput: 7\nExplanation: The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= word.length &lt;= 100\n\tword consists of lowercase English letters only.\n\n",1165        "solution_py": "class Solution:\n    def countVowelSubstrings(self, word: str) -> int:\n        vowels = {'a','e','i','o','u'}\n        pointer = 0\n        res = 0\n        if len(word) <= 4:\n            return 0\n        while pointer != len(word)-4:\n            # if set(list(word[pointer:pointer+5])) == vowels:\n            #     temp = 1\n            #     res += 1\n            #     while set(list(word[pointer:pointer+temp+5])) == vowels and pointer+temp+4 != len(word):\n            #         res += 1\n            #         temp += 1\n            # elif word[pointer] in vowels:\n            #     temp = 1\n            #     while set(list(word[pointer:pointer+5+temp])) != vowels:\n            #         temp += 1\n            #     res += 1\n            # pointer += 1\n            temp = 0\n            if word[pointer] in vowels:\n                while temp+pointer != len(word)-4:\n                    test_1 = set(list(word[pointer:pointer+temp+5]))\n                    test_2 = word[pointer:pointer+temp+5]\n                    if set(list(word[pointer:pointer+temp+5])).issubset(vowels): \n                        if set(list(word[pointer:pointer+temp+5])) == vowels:\n                            res += 1\n                        temp+=1\n                    else:\n                        break\n                    \n            pointer += 1\n        return res\n\n            ",1166        "solution_js": "/**\n * @param {string} word\n * @return {number}\n */\nvar isVowel = function(c) {\n    return (c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u');\n}\n\nvar countVowelSubstrings = function(word) {\n    let vowelMap = new Map();\n    let total = 0;\n    let totalLen = word.length - 1;\n    for(let i = 0 ; i <= totalLen; i++){\n        vowelMap.clear();\n        for(let j = i; j <= totalLen && isVowel(word[j]); j++){\n            vowelMap.set(word[j], (vowelMap.get(word[j]) ?? 0) + 1);\n            if(vowelMap.size == 5)\n                total++;\n        }\n    }\n    return total;\n};",1167        "solution_java": "class Solution\n{\n    public int countVowelSubstrings(String word)\n    {\n        int vow = 0;\n        int n = word.length();\n        Set<Character> set = new HashSet<>();\n        for(int i = 0; i < n-4; i++)\n        {\n            set.clear();\n            for(int j = i; j < n; j++)\n            {\n                char ch = word.charAt(j);\n                if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')\n                {\n                    set.add(ch);\n                    if(set.size() == 5)\n                        vow++;\n                }\n                else\n                    break;\n            }\n        }\n        return vow;\n    }\n}",1168        "solution_c": "class Solution {\npublic:\n    int countVowelSubstrings(string word) {\n        int n = word.size();\n        int res = 0;\n        \n        unordered_set<char> vowels {'a', 'e', 'i', 'o', 'u'};\n        \n        for (int i = 0; i < n; i++)\n        {\n            unordered_set<char> letters;\n            // string temp = \"\";\n            for (int j = i; j < n; j++)\n            {\n                // temp += word[j];\n                letters.insert(word[j]);\n                if (letters == vowels)\n                res++;\n            }\n        }\n        \n        return res;\n    }\n}; "1169    },1170    {1171        "title": "Minimum Sum of Squared Difference",1172        "algo_input": "You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.\n\nThe sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 &lt;= i &lt; n.\n\nYou are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.\n\nReturn the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.\n\nNote: You are allowed to modify the array elements to become negative integers.\n\n&nbsp;\nExample 1:\n\nInput: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\nOutput: 579\nExplanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2&nbsp;= 579.\n\n\nExample 2:\n\nInput: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\nOutput: 43\nExplanation: One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2&nbsp;= 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.\n\n&nbsp;\nConstraints:\n\n\n\tn == nums1.length == nums2.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= nums1[i], nums2[i] &lt;= 105\n\t0 &lt;= k1, k2 &lt;= 109\n\n",1173        "solution_py": "class Solution:\n    def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:\n        n = len(nums1)\n        k = k1+k2 # can combine k's because items can be turned negative\n        diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))\n        \n        # First binary search to find our new max for our diffs array\n        l, r = 0, max(diffs)\n        while l < r:\n            mid = (l+r)//2\n            \n            # steps needed to reduce all nums greater than newMax\n            steps = sum(max(0, num-mid) for num in diffs)\n            \n            if steps <= k:\n                r = mid\n            else:\n                l = mid+1\n                \n        newMax = l\n        k -= sum(max(0, num-newMax) for num in diffs) # remove used k\n\n        # Second binary search to find first index to replace with max val\n        l, r = 0, n-1\n        while l < r:\n            mid = (l+r)//2\n            if diffs[mid] < newMax:\n                l = mid+1\n            else:\n                r = mid\n\n        # Replace items at index >= l with newMax\n        diffs = diffs[:l]+[newMax]*(n-l)\n        \n        # Use remaining steps to reduce overall score\n        for i in range(len(diffs)-1,-1,-1):\n            if k == 0 or diffs[i] == 0: break\n            diffs[i] -= 1\n            k -= 1\n            \n        return sum(diff*diff for diff in diffs)",1174        "solution_js": "var minSumSquareDiff = function(nums1, nums2, k1, k2) {\n    const len = nums1.length;\n    const diff = new Array(len).fill(0);\n    for(let i = 0; i < len; i++) {\n        diff[i] = Math.abs(nums1[i] - nums2[i]);\n    }\n    diff.sort((a, b) => b - a);\n    const bucket = new Array(diff[0] + 1).fill(0);\n    let tk = k1 + k2;\n    for(let i of diff) {\n        bucket[i]++;\n    }\n    for(let i = bucket.length - 1; tk > 0 && i >= 0; i--) {\n        if(bucket[i] == 0) continue; \n        const reduce = Math.min(bucket[i], tk);\n        bucket[i] -= reduce;\n        bucket[i-1] += reduce;\n        tk -= reduce;\n    }\n    let ans = 0;\n    for(let i = bucket.length - 1; i >= 1; i--) {\n        ans += bucket[i] * i * i;\n    }\n    return ans;\n};",1175        "solution_java": "class Solution {\n    /** Algorithm\n        1. Count the differences between each nums1[i] and nums2[i] and store them into an int[100_001], as nums is between 0 and 100_000.\n        2. Let's look at the example of [1,4,10,12], [4,8,6,7]. k1= 1, k2 =1\n             Looking at the pairs of abs diff we have 3,4,4,5.\n             So a total of 16 diff points with k = 2.\n             As we observe, if we use the k operations on the first pair, we can decrease 3 to 1.\n             but this would only help with 3^2 (9) -> 1. So we decrease the totam sum diff by 8.\n             However, if we operate on the diff of 5, this would have much more impact.\n             5 - 1 => (4^2)25 - 16 . so we save 9 points by using 1 k\n             5 - 2 => (3^2) 25 - 9. So we save 16 points.\n         3. As we can see, we need to operate on the highest diff, lowering them.\n         4. As we have counted them on step #1, we would have an array like this\n           [0,0,0,1,2,1] : 1 diff of 3, 2 of 4 and 1 of 5.\n         5. While k is > 0 (k1 + k2), start from the back (highest) and decrease it one group at a time.\n           So make all 5 diffs into 4 diff, only if their cardinal is <= k. If it's greater than k, we can only\n           lower k diff to diff -1.\n           So [0,0,0,1,2,1] and k = 2 => [0,0,0,1,3,0] and k =1\n           We have 3 diff of 4 and just k =1 so we can turn one 4 into a 3.\n           => [0,0,0,2,2,0]. Thus. the diff becomes 2 of 3 and 2 of 4.\n    */\n    public long minSumSquareDiff(int[] nums1, int[] nums2, int k1, int k2) {\n        long minSumSquare = 0;\n        int[] diffs = new int[100_001];\n        long totalDiff = 0;\n        long kSum = k1 + k2;\n        int currentDiff;\n        int maxDiff = 0;\n        for (int i = 0; i < nums1.length; i++) {\n            // get current diff.\n            currentDiff = Math.abs(nums1[i] - nums2[i]);\n            // if current diff > 0, count/store it. If not,then ignore it.\n            if (currentDiff > 0) {\n                totalDiff += currentDiff;\n                diffs[currentDiff]++;\n                maxDiff = Math.max(maxDiff, currentDiff);\n            }\n        }\n        // if kSum (k1 + k2) < totalDifferences, it means we can make all numbers/differences 0s\n        if (totalDiff <= kSum) {\n            return 0;\n        }\n        // starting from the back, from the highest difference, lower that group one by one to the previous group.\n         // we need to make all n diffs to n-1, then n-2, as long as kSum allows it.\n        for (int i = maxDiff; i> 0 && kSum > 0; i--) {\n            if (diffs[i] > 0) {\n                // if current group has more differences than the totalK, we can only move k of them to the lower level.\n                if (diffs[i] >= kSum) {\n                    diffs[i] -= kSum;\n                    diffs[i-1] += kSum;\n                    kSum = 0;\n                } else {\n                    // else, we can make this whole group one level lower.\n                    diffs[i-1] += diffs[i];\n                    kSum -= diffs[i];\n                    diffs[i] = 0;\n                }\n            }\n        }\n\n        for (int i = 0; i <= maxDiff; i++) {\n            if (diffs[i] > 0) {\n                minSumSquare += (long) (Math.pow((long)i, 2)) * diffs[i];\n            }\n        }\n        return minSumSquare;\n    }\n}",1176        "solution_c": "class Solution {\npublic:\n    long long minSumSquareDiff(vector<int>& nums1, vector<int>& nums2, int k1, int k2) {\n        int n = nums1.size();\n        vector<int> diff(n);\n        for(int i = 0; i<n; ++i) {\n            diff[i] = abs(nums1[i] - nums2[i]);\n        }\n        int M = *max_element(diff.begin(), diff.end());\n        vector<int> bucket(M+1);\n        for(int i = 0 ; i<n; ++i) {\n            bucket[diff[i]]++;\n        }\n        int k = k1 + k2;\n        for(int i = M; i > 0; --i) {\n            if(bucket[i] > 0) {\n                int minus = min(bucket[i], k);\n                bucket[i] -= minus;\n                bucket[i-1] += minus;\n                k -= minus;\n            }\n        }\n        long long ans = 0;\n        for(long long i = M; i > 0; --i) {\n            ans += bucket[i]*i*i;\n        }\n        return ans;\n    }\n};"1177    },1178    {1179        "title": "Iterator for Combination",1180        "algo_input": "Design the CombinationIterator class:\n\n\n\tCombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.\n\tnext() Returns the next combination of length combinationLength in lexicographical order.\n\thasNext() Returns true if and only if there exists a next combination.\n\n\n&nbsp;\nExample 1:\n\nInput\n[\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[\"abc\", 2], [], [], [], [], [], []]\nOutput\n[null, \"ab\", true, \"ac\", true, \"bc\", false]\n\nExplanation\nCombinationIterator itr = new CombinationIterator(\"abc\", 2);\nitr.next();    // return \"ab\"\nitr.hasNext(); // return True\nitr.next();    // return \"ac\"\nitr.hasNext(); // return True\nitr.next();    // return \"bc\"\nitr.hasNext(); // return False\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= combinationLength &lt;= characters.length &lt;= 15\n\tAll the characters of characters are unique.\n\tAt most 104 calls will be made to next and hasNext.\n\tIt is guaranteed that all calls of the function next are valid.\n\n",1181        "solution_py": "class CombinationIterator:\n\n    def __init__(self, characters: str, combinationLength: int):\n        res = []\n        def dfs(low, path):\n            if len(path) == combinationLength:\n                res.append(path)\n                return\n            for idx in range(low, len(characters)):\n                dfs(idx+1, path+characters[idx])\n        \n        dfs(0, \"\")\n        self.combinations = res\n        self.currIdx = 0\n            \n    def next(self) -> str:\n        self.currIdx += 1\n        return self.combinations[self.currIdx-1]\n\n    def hasNext(self) -> bool:\n        return self.currIdx <= len(self.combinations) - 1",1182        "solution_js": "var CombinationIterator = function(characters, combinationLength) {\n    this.stack = Array.from({ length: combinationLength }, (_, i) => i);\n    this.combinationLength = combinationLength;\n    this.characters = characters;\n};\n\nCombinationIterator.prototype.next = function() {\n    const word = this.stack.map((i) => this.characters[i]).join(\"\");\n\n    for (let lastIndex = this.characters.length - 1; this.stack.at(-1) == lastIndex; )\n        lastIndex = this.stack.pop() - 1;\n\n    if (this.stack.length > 0)\n        for (let i = this.stack.pop() + 1; this.stack.length < this.combinationLength; i++)\n            this.stack.push(i);\n    \n    return word;\n};\n\nCombinationIterator.prototype.hasNext = function() {\n    return this.stack.length > 0;\n};",1183        "solution_java": "class CombinationIterator {\n\n    private Queue<String> allCombinations;\n    public CombinationIterator(String characters, int combinationLength) {\n        this.allCombinations = new LinkedList<>();\n        generateAllCombinations(characters,0,combinationLength,new StringBuilder());\n    }\n    \n    private void generateAllCombinations(String characters,int index,int combinationLength,StringBuilder currentString){\n        \n        if(currentString.length() == combinationLength){\n            this.allCombinations.offer(currentString.toString());\n            return;\n        }\n        \n        for(int i = index ; i < characters.length() ; i++){\n            currentString.append(characters.charAt(i));\n            generateAllCombinations(characters,i+1,combinationLength,currentString);\n            currentString.deleteCharAt(currentString.length()-1);\n        }\n        \n    }\n    \n    public String next() {\n        return this.allCombinations.poll();\n    }\n    \n    public boolean hasNext() {\n      return !this.allCombinations.isEmpty();\n    }\n}",1184        "solution_c": "class CombinationIterator {\npublic:\n\tvector<string>ans;\n\tint j=0;\n\tvoid comb(int i,string& s,int k,string& t){\n\t\tif(i==s.size()){\n\t\t\tif(t.size()==k) ans.push_back(t);\n\t\t\treturn;\n\t\t}\n//      Pick\n\t\tt.push_back(s[i]);\n\t\tcomb(i+1,s,k,t);\n\t\tt.pop_back();\n//      NotPick\n\t\tcomb(i+1,s,k,t);\n\t}\n\n\tCombinationIterator(string characters, int combinationLength) {\n\t\tsort(characters.begin(),characters.end());\n\t\tstring t=\"\";\n\t\tcomb(0,characters,combinationLength,t);\n\t}\n\n\tstring next() {\n\t\treturn ans[j++];\n\t}\n\n\tbool hasNext() {\n\t\tif(j==ans.size())return false;\n\t\treturn true;\n\t}\n};"1185    },1186    {1187        "title": "The Number of Weak Characters in the Game",1188        "algo_input": "You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.\n\nA character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj &gt; attacki and defensej &gt; defensei.\n\nReturn the number of weak characters.\n\n&nbsp;\nExample 1:\n\nInput: properties = [[5,5],[6,3],[3,6]]\nOutput: 0\nExplanation: No character has strictly greater attack and defense than the other.\n\n\nExample 2:\n\nInput: properties = [[2,2],[3,3]]\nOutput: 1\nExplanation: The first character is weak because the second character has a strictly greater attack and defense.\n\n\nExample 3:\n\nInput: properties = [[1,5],[10,4],[4,3]]\nOutput: 1\nExplanation: The third character is weak because the second character has a strictly greater attack and defense.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= properties.length &lt;= 105\n\tproperties[i].length == 2\n\t1 &lt;= attacki, defensei &lt;= 105\n\n",1189        "solution_py": "class Solution:\n    def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n\n        properties.sort(key=lambda x: (-x[0],x[1]))\n\n        ans = 0\n        curr_max = 0\n\n        for _, d in properties:\n            if d < curr_max:\n                ans += 1\n            else:\n                curr_max = d\n        return ans",1190        "solution_js": " var numberOfWeakCharacters = function(properties) {\n    // sort strongest to weakest\n    properties.sort((a, b) => {\n        if (b[0] - a[0]) {\n            return b[0] - a[0];\n        }\n        return b[1] - a[1];\n    });\n\n    // map all the unique index 0 values to a (descending)\n    // sorted array\n    const uniqueZeroIndexToOneIndex = new Map();\n    for (const [a, b] of properties) {\n        if (!uniqueZeroIndexToOneIndex.has(a)) {\n            uniqueZeroIndexToOneIndex.set(a, []);\n        }\n        uniqueZeroIndexToOneIndex.get(a).push(b);\n    }\n\n    // get all the unique index 0 values\n    const nums = [...uniqueZeroIndexToOneIndex.keys()];\n\n    let maxValue = -1;\n    let numWeakCharacters = 0;\n    for (let i = 0; i < nums.length; i++) {\n        // skip key in case if we deleted the key\n        if (!uniqueZeroIndexToOneIndex.has(nums[i])) continue;\n\n        const maxValOfI = uniqueZeroIndexToOneIndex.get(nums[i])[0];\n        if (maxValOfI <= maxValue) continue;\n        maxValue = maxValOfI;\n\n        for (let j = i + 1; j < nums.length; j++) {\n            // skip key in case if we deleted the key\n            if (!uniqueZeroIndexToOneIndex.has(nums[j])) continue;\n\n            // valuesOfJ will be sorted in descending order\n            const valuesOfJ = uniqueZeroIndexToOneIndex.get(nums[j])\n\n            // pop off all the weak values and add to numWeakCharacters\n            for (let k = valuesOfJ.length - 1; k >= 0; k--) {\n                if (maxValue > valuesOfJ[k]) {\n                    valuesOfJ.pop();\n                    numWeakCharacters++;\n                } else {\n                    // we won't be able to find any more weak characters\n                    // in valuesOfJ\n                    break;\n                }\n            }\n            if (valuesOfJ.length === 0) {\n                // delete the key if all the values were weak characters\n                uniqueZeroIndexToOneIndex.delete(nums[j]);\n            } else {\n                // if there is a stronger character updated it so we can\n                // eliminate more characters\n                maxValue = Math.max(valuesOfJ[0], maxValue);\n            }\n        }\n    }\n    return numWeakCharacters;\n};",1191        "solution_java": "class Solution {\n    public int numberOfWeakCharacters(int[][] properties) {\n        int[] maxH = new int[100002];\n        int count = 0;\n        for(int[] point:properties){\n            maxH[point[0]] = Math.max(point[1],maxH[point[0]]);\n        }\n        for(int i=100000;i>=0;i--){\n            maxH[i] = Math.max(maxH[i+1],maxH[i]);\n        }\n\n        for(int[] point:properties){\n            if(point[1]<maxH[point[0]+1])\n                count++;\n        }\n        return count;\n    }\n}",1192        "solution_c": "class Solution {\npublic:\n    static bool cmp(vector<int>& a, vector<int>& b) {\n        if (a[0] != b[0]) return a[0] > b[0];\n        return a[1] < b[1];\n    }\n    \n    int numberOfWeakCharacters(vector<vector<int>>& properties) {\n        sort(properties.begin(), properties.end(), cmp);\n\n        int res = 0, mx = INT_MIN;\n        for (auto p : properties) {\n            if (mx > p[1]) res++;\n            else mx = p[1];\n        }\n        return res;\n    }\n};"1193    },1194    {1195        "title": "Backspace String Compare",1196        "algo_input": "Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.\n\nNote that after backspacing an empty text, the text will continue empty.\n\n&nbsp;\nExample 1:\n\nInput: s = \"ab#c\", t = \"ad#c\"\nOutput: true\nExplanation: Both s and t become \"ac\".\n\n\nExample 2:\n\nInput: s = \"ab##\", t = \"c#d#\"\nOutput: true\nExplanation: Both s and t become \"\".\n\n\nExample 3:\n\nInput: s = \"a#c\", t = \"b\"\nOutput: false\nExplanation: s becomes \"c\" while t becomes \"b\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, t.length &lt;= 200\n\ts and t only contain lowercase letters and '#' characters.\n\n\n&nbsp;\nFollow up: Can you solve it in O(n) time and O(1) space?\n",1197        "solution_py": "class Solution:\n    def backspaceCompare(self, s: str, t: str) -> bool:\n        def backwardResult(string):\n            debt = 0\n            \n            for c in reversed(string):\n                if c == '#':\n                    debt += 1\n                \n                elif debt > 0:\n                    debt -= 1\n                \n                else:\n                    yield c\n        \n        return all(a == b for (a, b) in zip_longest(backwardResult(s), backwardResult(t)))",1198        "solution_js": "var backspaceCompare = function(s, t) {\n    let stack1 = [];\n    let stack2 = [];\n    \n    for(let i=0; i<s.length; i++) {\n        if(s[i] == '#') {\n            if(stack1.length != 0) {\n                stack1.pop();\n            }\n        } else {\n            stack1.push(s[i]);\n        }\n    }\n    \n    for(let j=0; j<t.length; j++) {\n        if(t[j] == '#') {\n            if(stack2.length != 0) {\n                stack2.pop();\n            }\n        } else {\n            stack2.push(t[j]);\n        }\n    }\n    return stack1.join('') === stack2.join('');\n};",1199        "solution_java": "class Solution {\n    public boolean backspaceCompare(String s, String t) {\n        int i = s.length() - 1, j = t.length() - 1;\n        while(i >= 0 || j >= 0) {\n            i = getCurPos(i, s);\n            j = getCurPos(j, t);\n            if (i >= 0 && j >= 0 && s.charAt(i) != t.charAt(j)) return false;\n            if ((i >= 0) != (j >= 0)) return false;\n            i--;\n            j--;\n        }\n        return true;\n    }\n    private int getCurPos(int i, String s) {\n        int dels = 0;\n        while( i >= 0) {\n            if (s.charAt(i) == '#') {\n                dels++;\n                i--;\n            } else if (dels > 0) {\n                dels--;\n                i--;\n            } else break;\n        }\n        return i;\n    }\n}",1200        "solution_c": "class Solution {\npublic:\n    bool backspaceCompare(string s, string t) {\n        stack<int> st1;\n        stack<int> st2;\n        int len = s.length();\n        int len2 = t.length();\n\n        for(int i=0; i<len; i++){\n            if(s[i] != '#'){\n                st1.push(s[i]);\n            }\n            else{\n                if(!st1.empty()){\n                    st1.pop();\n                }\n            }\n        }\n        for(int i=0; i<len2; i++){\n            if(t[i] != '#'){\n                st2.push(t[i]);\n            }\n            else{\n                if(!st2.empty()){\n                    st2.pop();\n                }\n            }\n        }\n\n        while(!st1.empty() && !st2.empty()){\n            if(st1.top() != st2.top()){\n                return false;\n            }\n            st1.pop();\n            st2.pop();\n        }\n        if(st1.empty() && st2.empty()){\n            return true;\n        }\n        return false;\n    }\n};"

Showing the first 1,200 of 1226 lines. Download the file for the rest.