[ { "title": "Maximum Absolute Sum of Any Subarray", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\n", "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", "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 0)\n currentMinSum = 0;\n }\n return Math.max(maxSum, -minSum);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxAbsoluteSum(vector& nums) {\n int mx1=0;\n int sum=0;\n for(int i=0;i=0)sum=0;\n mx2=min(sum,mx2);\n }\n \n return max(mx1,abs(mx2));\n }\n};" }, { "title": "Verifying an Alien Dictionary", "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 \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] > 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\" > \"app\", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length <= 20\n\torder.length == 26\n\tAll characters in words[i] and order are English lowercase letters.\n\n", "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", "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};", "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 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}", "solution_c": "class Solution {\npublic:\n bool isAlienSorted(vector& words, string order)\n {\n unordered_map 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;" }, { "title": "Minimum Time to Make Rope Colorful", "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 \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 \nConstraints:\n\n\n\tn == colors.length == neededTime.length\n\t1 <= n <= 105\n\t1 <= neededTime[i] <= 104\n\tcolors contains only lowercase English letters.\n\n", "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 ", "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};", "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}", "solution_c": "class Solution {\npublic:\n int minCost(string colors, vector& neededTime) {\n int time=0;\n for(int i=0;ineededTime[i+1]){\n swap(neededTime[i],neededTime[i+1]);\n }\n time+=min(neededTime[i],neededTime[i+1]);\n }\n }return time;\n }\n};" }, { "title": "Construct Binary Tree from Preorder and Inorder Traversal", "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 \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 \nConstraints:\n\n\n\t1 <= preorder.length <= 3000\n\tinorder.length == preorder.length\n\t-3000 <= preorder[i], inorder[i] <= 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", "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", "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};", "solution_java": "class Solution {\n Map 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 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}", "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::iterator vecIt;\n\n TreeNode* buildTree(vector& preorder, vector& 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& preorder, vector& inorder) {\n TreeNode* retNode;\n\n return (buildTree(preorder, inorder, retNode, inorder.begin(), inorder.end()));\n }\n};" }, { "title": "Best Time to Buy and Sell Stock IV", "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 \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 \nConstraints:\n\n\n\t0 <= k <= 100\n\t0 <= prices.length <= 1000\n\t0 <= prices[i] <= 1000\n\n", "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]", "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};", "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& prices, vector>>& 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& prices) {\n vector>> dp(prices.size(), vector> (2, vector (k+1, -1)));\n return solve(0, 1, k, prices, dp);\n }\n};" }, { "title": "Get Watched Videos by Your Friends", "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 friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your 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. \n\n \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 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 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 \nConstraints:\n\n\n\tn == watchedVideos.length == friends.length\n\t2 <= n <= 100\n\t1 <= watchedVideos[i].length <= 100\n\t1 <= watchedVideos[i][j].length <= 8\n\t0 <= friends[i].length < n\n\t0 <= friends[i][j] < n\n\t0 <= id < n\n\t1 <= level < n\n\tif friends[i] contains j, then friends[j] contains i\n\n", "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 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};", "solution_java": "class Solution {\n public List watchedVideosByFriends(List> watchedVideos, int[][] friends, int id, int level) {\n int n = friends.length;\n boolean[] visited = new boolean[n];\n List> graph = new ArrayList<>();\n for(int i=0;i());\n for(int i=0;i queue = new ArrayDeque<>();\n queue.offer(id);\n visited[id] = true;\n Map answer = new HashMap<>();\n while(!queue.isEmpty() && level>0){\n int size = queue.size();\n for(int i=0;i 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 finalAnswer = new ArrayList<>();\n while(!sortedQueue.isEmpty()) finalAnswer.add(sortedQueue.remove()[0]);\n return finalAnswer;\n }\n}", "solution_c": "class Solution {\npublic:\n vector watchedVideosByFriends(vector>& watchedVideos, vector>& friends, int id, int level) {\n vector>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 vectorvis(watchedVideos.size(),0);\n vectorans;\n \n queueq;\n q.push(id);\n while(!q.empty()){\n if(tmp_level++ == level){\n unordered_mapmp;\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>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};" }, { "title": "Snapshot Array", "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 \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 \nConstraints:\n\n\n\t1 <= length <= 5 * 104\n\t0 <= index < length\n\t0 <= val <= 109\n\t0 <= snap_id < (the total number of times we call snap())\n\tAt most 5 * 104 calls will be made to set, snap, and get.\n\n", "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", "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}", "solution_java": "class SnapshotArray {\n\n TreeMap[] snapshotArray;\n int currSnapId;\n\n public SnapshotArray(int length) {\n snapshotArray = new TreeMap[length];\n for(int i=0;i> 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 */" }, { "title": "1-bit and 2-bit Characters", "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 \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 \nConstraints:\n\n\n\t1 <= bits.length <= 1000\n\tbits[i] is either 0 or 1.\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n bool isOneBitCharacter(vector& 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};" }, { "title": "Remove Duplicates from Sorted Array", "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 should hold the final result. It does not matter what you leave beyond the first k 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 < k; i++) {\n assert nums[i] == expectedNums[i];\n}\n\n\nIf all assertions pass, then your solution will be accepted.\n\n \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 \nConstraints:\n\n\n\t1 <= nums.length <= 3 * 104\n\t-100 <= nums[i] <= 100\n\tnums is sorted in non-decreasing order.\n\n", "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", "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};", "solution_java": "class Solution {\n public int removeDuplicates(int[] arr) {\n int i=0;\n for(int j=1;j& nums) {\n int ans=0;\n for(int i=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};", "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}", "solution_c": "class Solution {\npublic:\n bool find132pattern(vector& nums) {\n // Initialise a empty stack \"s\"...\n stack 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};" }, { "title": "Reveal Cards In Increasing Order", "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 \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 \nConstraints:\n\n\n\t1 <= deck.length <= 1000\n\t1 <= deck[i] <= 106\n\tAll the values of deck are unique.\n\n", "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)", "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};", "solution_java": "class Solution {\n public int[] deckRevealedIncreasing(int[] deck) { // deck=[ 17,13,11,2,3,5,7 ]\n Queue ql = new LinkedList();\n for(int i=0;i deckRevealedIncreasing(vector& deck) {\n int n = deck.size(), idx = 0, idx1 = 0;\n vector 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};" }, { "title": "Slowest Key", "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, 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 \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 \nConstraints:\n\n\n\treleaseTimes.length == n\n\tkeysPressed.length == n\n\t2 <= n <= 1000\n\t1 <= releaseTimes[i] <= 109\n\treleaseTimes[i] < releaseTimes[i+1]\n\tkeysPressed contains only lowercase English letters.\n\n", "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", "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};", "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= 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}", "solution_c": "class Solution {\npublic:\n char slowestKey(vector& 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};" }, { "title": "Partition Array Into Two Arrays to Minimize Sum Difference", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 15\n\tnums.length == 2 * n\n\t-107 <= nums[i] <= 107\n\n", "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 ", "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};", "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[] 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<();\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<& nums) {\n int n = nums.size()/2; \n vector left(nums.begin(), nums.begin()+n), right(nums.begin()+n, nums.begin()+2*n); \n \n vector> vals(n+1); \n for (int mask = 0; mask < (1< 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", "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};", "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& 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= 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", "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};", "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}", "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};" }, { "title": "Last Substring in Lexicographical Order", "algo_input": "Given a string s, return the last substring of s in lexicographical order.\n\n \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 \nConstraints:\n\n\n\t1 <= s.length <= 4 * 105\n\ts contains only lowercase English letters.\n\n", "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:]", "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};", "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}", "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};" }, { "title": "Minimum Time to Complete Trips", "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 \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 \nConstraints:\n\n\n\t1 <= time.length <= 105\n\t1 <= time[i], totalTrips <= 107\n\n", "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", "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}", "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}", "solution_c": "class Solution {\npublic:\n long long minimumTime(vector& 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};" }, { "title": "Selling Pieces of Wood", "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 \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 \nConstraints:\n\n\n\t1 <= m, n <= 200\n\t1 <= prices.length <= 2 * 104\n\tprices[i].length == 3\n\t1 <= hi <= m\n\t1 <= wi <= n\n\t1 <= pricei <= 106\n\tAll the shapes of wood (hi, wi) are pairwise distinct.\n\n", "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)", "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};", "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}", "solution_c": "class Solution {\nprivate:\n\tlong long f(int row, int col, map,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>& prices) {\n\t\t//Declaring the HashMap\n\t\tmap,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};" }, { "title": "Shortest Distance to a Character", "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 \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 \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts[i] and c are lowercase English letters.\n\tIt is guaranteed that c occurs at least once in s.\n\n", "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", "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};", "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=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}", "solution_c": "class Solution {\npublic:\n vector shortestToChar(string s, char c) {\n vectorsk;\n vectorres;\n vectortemp;\n int ss=0;\n int mins;\n for(int i=0;i 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", "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};", "solution_java": "class FindSumPairs {\n\n private int [] nums1;\n private int [] nums2;\n Map 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 */", "solution_c": "class FindSumPairs {\npublic:\n //use map to store the element as key and its frequency as its value\n unordered_map freq;\n vector v1;\n vector v2;\n FindSumPairs(vector& nums1, vector& 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 */" }, { "title": "Queens That Can Attack the King", "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 \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:  \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 \nConstraints:\n\n\n\t1 <= queens.length <= 63\n\tqueens[i].length == 2\n\t0 <= queens[i][j] < 8\n\tking.length == 2\n\t0 <= king[0], king[1] < 8\n\tAt most one piece is allowed in a cell.\n\n", "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", "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};", "solution_java": "class Solution {\n public List> queensAttacktheKing(int[][] queens, int[] king) {\n List> 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(Arrays.asList(r, j)));\n break;\n }\n }\n for(i=r;i(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=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(Arrays.asList(i, j)));\n break;\n }\n }\n for(i=r,j=l;j>=0 && i(Arrays.asList(i, j)));\n break;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> queensAttacktheKing(vector>& queens, vector& king) \n {\n vector> ans;\n vector> board(8, vector(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};" }, { "title": "First Unique Character in a String", "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 \nExample 1:\nInput: s = \"leetcode\"\nOutput: 0\nExample 2:\nInput: s = \"loveleetcode\"\nOutput: 2\nExample 3:\nInput: s = \"aabb\"\nOutput: -1\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of only lowercase English letters.\n\n", "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", "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};", "solution_java": "class Solution {\n public int firstUniqChar(String s) {\n HashMaphmap=new HashMap<>();\n for(int i=0;i mp;\n\n for(int i=0; i 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", "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}", "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> 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> 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}", "solution_c": "class Solution {\n vector ans;\n vector> graph;\n string global;\npublic:\n \n \n vector getAns(int u, int parent){\n ans[u] = 1;\n char rootChar = global[u];\n vector 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 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 countSubTrees(int n, vector>& edges, string labels) {\n ans.resize(n);\n graph.resize(n);\n global = labels;\n \n \n \n for(vector 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};" }, { "title": "Maximum Value at a Given Index in a Bounded Array", "algo_input": "You are given three positive integers: 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 <= i < n.\n\tabs(nums[i] - nums[i+1]) <= 1 where 0 <= i < 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 >= 0, and -x otherwise.\n\n \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 \nConstraints:\n\n\n\t1 <= n <= maxSum <= 109\n\t0 <= index < n\n\n", "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", "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 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}", "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};" }, { "title": "Copy List with Random Pointer", "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 --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> 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 \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 \nConstraints:\n\n\n\t0 <= n <= 1000\n\t-104 <= Node.val <= 104\n\tNode.random is null or is pointing to some node in the linked list.\n\n", "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 ", "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};", "solution_java": "class Solution {\n public Node copyRandomList(Node head) {\n \n if(head == null)\n return null;\n \n HashMap 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}", "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};" }, { "title": "Distinct Echo Substrings", "algo_input": "Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).\n\n \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 \nConstraints:\n\n\n\t1 <= text.length <= 2000\n\ttext has only lowercase English letters.\n\n", "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 ", "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};", "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 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}", "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 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 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", "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}", "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 findDuplicateSubtrees(TreeNode root) {\n List list = new ArrayList();\n HashSet hashes = new HashSet();\n HashSet added = new HashSet();\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 s = new Stack();\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 list, HashSet set, HashSet added){\n\n Stack stack = new Stack();\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}", "solution_c": "class Solution {\npublic:\n unordered_map dp ;\n vector 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 findDuplicateSubtrees(TreeNode* root) {\n string dummy = solve(root) ;\n return ans ;\n }\n};" }, { "title": "Best Time to Buy and Sell Stock III", "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 \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 \nConstraints:\n\n\n\t1 <= prices.length <= 105\n\t0 <= prices[i] <= 105\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n int maxProfit(vector& prices) {\n int n=prices.size();\n vector left(n);\n vector right(n);\n int mini=INT_MAX;\n int ans1=0;\n for(int i=0;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 prices[R]){\n L = R;\n }else {\n result = Math.max(result, prices[R] - prices[L]);\n\n }\n }\n return result;\n};", "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}", "solution_c": "class Solution {\npublic:\n int maxProfit(vector& 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};" }, { "title": "Binary Tree Right Side View", "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 \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 \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 100].\n\t-100 <= Node.val <= 100\n\n", "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", "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 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 rightSideView(TreeNode root) {\n // create a list\n List 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*/", "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 &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 rightSideView(TreeNode* root) {\n vector ans ; \n int level = 0 ; \n\n solve(root, ans, level) ;\n \n return ans ; \n }\n};" }, { "title": "Race Car", "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 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.\n\nGiven a target position target, return the length of the shortest sequence of instructions to get there.\n\n \nExample 1:\n\nInput: target = 3\nOutput: 2\nExplanation: \nThe shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.\n\n\nExample 2:\n\nInput: target = 6\nOutput: 5\nExplanation: \nThe shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.\n\n\n \nConstraints:\n\n\n\t1 <= target <= 104\n\n", "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", "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};", "solution_java": "class Solution {\n public int racecar(int target) {\n Queue queue = new LinkedList<>();\n queue.add(new int[]{0, 1, 0});\n Set 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}", "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 q;\n Position p(0, 1, 0);\n q.push(p);\n\n set> 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};" }, { "title": "Print Binary Tree", "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 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 \nExample 1:\n\nInput: root = [1,2]\nOutput: \n[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]\n\n\nExample 2:\n\nInput: root = [1,2,3,null,4]\nOutput: \n[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 210].\n\t-99 <= Node.val <= 99\n\tThe depth of the tree will be in the range [1, 10].\n\n", "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", "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> printTree(TreeNode root) {\n List> 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 list = new ArrayList();\n for(int i=0; i> 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}", "solution_c": "class Solution {\npublic:\n vector> 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> printTree(TreeNode* root) {\n int h = height(root);\n int c = pow(2, h) - 1;\n res.resize(h, vector(c, \"\"));\n fill(root, 0, (c - 1) / 2, h - 1);\n return res;\n }\n};" }, { "title": "Largest Submatrix With Rearrangements", "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 \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 \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m * n <= 105\n\tmatrix[i][j] is either 0 or 1.\n\n", "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", "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};", "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 pq = new PriorityQueue();// minheap\n for(int j=0;j0) 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}", "solution_c": "class Solution {\npublic:\n int largestSubmatrix(vector>& matrix) {\n int m = matrix.size(), n = matrix[0].size();\n int ans = 0;\n vector 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 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};" }, { "title": "Minimize Malware Spread", "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 \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 \nConstraints:\n\n\n\tn == graph.length\n\tn == graph[i].length\n\t2 <= n <= 300\n\tgraph[i][j] is 0 or 1.\n\tgraph[i][j] == graph[j][i]\n\tgraph[i][i] == 1\n\t1 <= initial.length <= n\n\t0 <= initial[i] <= n - 1\n\tAll the integers in initial are unique.\n\n", "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]", "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}", "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 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}", "solution_c": "class Solution {\npublic:\n void dfs(int i,int n,vector &visited,vector&cur,map& ind,int &cnt,map >&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>& graph, vector& initial) {\n int n=graph.size();\n map > mp; //Adjacency list creation for the graph\n for(int i=0;i ind; // This map is for storing the component number to which a particular node belongs to\n vector > v; //Store all the connected components\n vector 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 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 > help; //This map tells that how many node that is present in inital vector are of same component\n for(int i=0;ifirst].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]first][0];\n }\n }\n }\n if(ans!=n)\n return ans;\n for(int i=0;i 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};", "solution_java": "class Solution {\n public String minRemoveToMakeValid(String s) {\n Stack stack = new Stack<>();\n for(int i=0;i set = new HashSet<>(stack);\n for(int i=0;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};" }, { "title": "Powerful Integers", "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 >= 0 and j >= 0.\n\nYou may return the answer in any order. In your answer, each value should occur at most once.\n\n \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 \nConstraints:\n\n\n\t1 <= x, y <= 100\n\t0 <= bound <= 106\n\n", "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)", "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}", "solution_java": "class Solution {\n public List powerfulIntegers(int x, int y, int bound) {\n HashSet set = new HashSet<>();\n for(int i = 1; i(set);\n }\n}", "solution_c": "class Solution {\npublic:\n vector powerfulIntegers(int x, int y, int bound) {\n unordered_set 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 (s.begin(), s.end());\n }\n};" }, { "title": "Masking Personal Information", "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 \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 \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 <= s.length <= 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 <= s.length <= 20\n\t\ts consists of digits, spaces, and the symbols '(', ')', '-', and '+'.\n\t\n\t\n\n", "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 ", "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};", "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}", "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};" }, { "title": "Longest Happy Prefix", "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 \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 \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts contains only lowercase English letters.\n\n", "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]]", "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};", "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; i0 && 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;i0){ // 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 */", "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};" }, { "title": "Exclusive Time of Functions", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 100\n\t1 <= logs.length <= 500\n\t0 <= function_id < n\n\t0 <= timestamp <= 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", "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", "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}", "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 logs) {\n if (n == 0) {\n return new int[0];\n }\n\n int[] result = new int[n];\n\n Stack> 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 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 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 replacementPair = new Pair(pair.getKey(), timestamp + 1);\n stack.push(replacementPair);\n }\n }\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector exclusiveTime(int n, vector& logs) {\n vector ret(n, 0);\n stack> 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};" }, { "title": "Map Sum Pairs", "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 \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 \nConstraints:\n\n\n\t1 <= key.length, prefix.length <= 50\n\tkey and prefix consist of only lowercase English letters.\n\t1 <= val <= 1000\n\tAt most 50 calls will be made to insert and sum.\n\n", "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", "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};", "solution_java": "class MapSum {\n private Map map;\n private Map 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 */", "solution_c": "class MapSum {\npublic:\n mapmp;\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 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)", "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};", "solution_java": "class SeatManager {\n PriorityQueue 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}", "solution_c": "class SeatManager {\npublic:\n priority_queue, greater > 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};" }, { "title": "Jewels and Stones", "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 \nExample 1:\nInput: jewels = \"aA\", stones = \"aAAbbbb\"\nOutput: 3\nExample 2:\nInput: jewels = \"z\", stones = \"ZZ\"\nOutput: 0\n\n \nConstraints:\n\n\n\t1 <= jewels.length, stones.length <= 50\n\tjewels and stones consist of only English letters.\n\tAll the characters of jewels are unique.\n\n", "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", "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};", "solution_java": "class Solution {\n public int numJewelsInStones(String jewels, String stones) {\n HashSet hs=new HashSet<>();\n int count=0;\n for(int i=0;i mp;\n\n\t\tfor(int i=0 ; i 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", "solution_js": "var getWinner = function(arr, k) {\n let ws=0;\n let currentWinner=0;\n for(let i=1;iarr[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};", "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;iarr[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}", "solution_c": "class Solution {\npublic:\n int getWinner(vector& arr, int k) {\n int winner = arr[0];\n int wins = 0;\n for (int i=1; i 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};" }, { "title": "Find Nearest Point That Has the Same X or Y Coordinate", "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 \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 \nConstraints:\n\n\n\t1 <= points.length <= 104\n\tpoints[i].length == 2\n\t1 <= x, y, ai, bi <= 104\n\n", "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{\n if(a===x || b===y){\n const dist = Math.abs(x-a) + Math.abs(y-b)\n if(dist no longer needed as index is initialized as -1 in the declartion.\n return index;\n \n }\n}", "solution_c": "class Solution {\npublic:\n int nearestValidPoint(int x, int y, vector>& points) {\n int pos = -1;\n int ans = INT_MAX;\n\n for(int i=0; i 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 )", "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;iarr[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= 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}", "solution_c": "class Solution {\npublic:\n int longestMountain(vector& arr) {\n vector v;\n for(int i=0;iarr[i])v.push_back(1);\n else if(arr[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};", "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}", "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;i6)\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};" }, { "title": "Time Needed to Inform All Employees", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 105\n\t0 <= headID < n\n\tmanager.length == n\n\t0 <= manager[i] < n\n\tmanager[headID] == -1\n\tinformTime.length == n\n\t0 <= informTime[i] <= 1000\n\tinformTime[i] == 0 if employee i has no subordinates.\n\tIt is guaranteed that all the employees can be informed.\n\n", "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", "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};", "solution_java": "class Solution {\n public int numOfMinutes(int n, int headID, int[] manager, int[] informTime) {\n Map> graph = new HashMap<>();\n for(int i=0; i());\n graph.get(manager[i]).add(i);\n }\n return dfs(graph, headID, informTime);\n }\n\n int dfs(Map> 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}", "solution_c": "class Solution {\npublic:\n int ans = INT_MIN, tmp=0;\n unordered_map> mp;//manager to each subordination\n vector* pInformTime;\n int numOfMinutes(int n, int headID, vector& manager, vector& informTime) {\n pInformTime = &informTime;\n for(int i = 0; i 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 ", "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 a + parseInt(b.join(''),2),0);\n};", "solution_java": "class Solution {\n public int matrixScore(int[][] grid) {\n ArrayList arr=new ArrayList();\n for(int i=0;ione)\n {\n arr.add(i);\n }\n }\n for(int i:arr)\n {\n for(int j=0;j> mat){\n int score = 0;\n \n \n \n for(int i=0;i>& grid) {\n// if(grid.size()==1){\n// return ;\n// }\n \n \n for(int i=0;i ind;\n \n for(int i=1;i 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])", "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= 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};", "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}", "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 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 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};" }, { "title": "Greatest Common Divisor of Strings", "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 \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 \nConstraints:\n\n\n\t1 <= str1.length, str2.length <= 1000\n\tstr1 and str2 consist of English uppercase letters.\n\n", "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 \"\"", "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}", "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}", "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};" }, { "title": "Smallest Subtree with all the Deepest Nodes", "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 \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 \nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 500].\n\t0 <= Node.val <= 500\n\tThe values of the nodes in the tree are unique.\n\n\n \nNote: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/\n", "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", "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};", "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 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 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 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}", "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 &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 mapm;\n help(r,NULL,m);\n queueq;\n vectorans;\n q.push(root); \n while(!q.empty())\n {\n int s=q.size();\n vectora;\n for(int i=0;ileft!=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 sets;\n while(s.size()!=1)\n {\n s.clear();\n for(int i=0;i 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", "solution_js": "var uncommonFromSentences = function(s1, s2) {\n return (s1+' '+s2).split(' ').filter((el,i,arr)=>arr.indexOf(el)===arr.lastIndexOf(el))\n};", "solution_java": "class Solution {\n public String[] uncommonFromSentences(String s1, String s2) {\n List list=new LinkedList<>();\n Map map=new HashMap<>();\n String[] arr1=s1.split(\" \");\n String[] arr2=s2.split(\" \");\n for(int i=0;i 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&mp) {\n string word=\"\";\n for(int i=0; i uncommonFromSentences(string s1, string s2) {\n vector ans;\n unordered_map mp;\n uncommon(s1,mp);\n uncommon(s2,mp);\n for(pair p : mp) {\n if(p.second==1) ans.push_back(p.first);\n }\n return ans;\n }\n};" }, { "title": "Find the Kth Largest Integer in the Array", "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 \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 \nConstraints:\n\n\n\t1 <= k <= nums.length <= 104\n\t1 <= nums[i].length <= 100\n\tnums[i] consists of only digits.\n\tnums[i] will not have any leading zeros.\n\n", "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])", "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};", "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;ib1) return 1;\n if(b1>a1) return -1;\n }\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n static bool cmp(string &a,string &b)\n {\n if(a.size()==b.size())\n {\n return a& nums, int k)\n {\n sort(nums.begin(),nums.end(),cmp);\n int n=nums.size();\n return nums[n-k];\n }\n};" }, { "title": "Partition to K Equal Sum Subsets", "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 \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 \nConstraints:\n\n\n\t1 <= k <= nums.length <= 16\n\t1 <= nums[i] <= 104\n\tThe frequency of each element is in the range [1, 4].\n\n", "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)", "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};", "solution_java": "class Solution {\n private final List> 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 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 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 set1, Set set2) {\n for (Integer num: set1) if(set2.contains(num)) return false;\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n unordered_map dp;\n int solve(vector& 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<& 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};" }, { "title": "Find Array Given Subset Sums", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 15\n\tsums.length == 2n\n\t-104 <= sums[i] <= 104\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector recoverArray(int n, vector& sums) {\n sort(sums.begin(), sums.end());\n\n vector ans;\n while (n--) {\n int diff = sums[1] - sums[0];\n unordered_map freq;\n vector 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};" }, { "title": "Add Digits", "algo_input": "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.\n\n \nExample 1:\n\nInput: num = 38\nOutput: 2\nExplanation: The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.\n\n\nExample 2:\n\nInput: num = 0\nOutput: 0\n\n\n \nConstraints:\n\n\n\t0 <= num <= 231 - 1\n\n\n \nFollow up: Could you do it without any loop/recursion in O(1) runtime?\n", "solution_py": "class Solution:\n def addDigits(self, num: int) -> int:\n while num > 9:\n num = num % 10 + num // 10\n return num", "solution_js": "var addDigits = function(num) {\n return 1 + (num - 1) % 9;\n};", "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}", "solution_c": "class Solution {\npublic:\n int addDigits(int n) {\n return n < 10 ? n : addDigits(n / 10 + n % 10);\n }\n};" }, { "title": "Tag Validator", "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 : <TAG_NAME>TAG_CONTENT</TAG_NAME>. Among them, <TAG_NAME> is the start tag, and </TAG_NAME> 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 <, 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 < is unmatched if you cannot find a subsequent >. And when you find a < or </, all the subsequent characters until the next > should be parsed as TAG_NAME (not necessarily valid).\n\tThe cdata has the following format : <![CDATA[CDATA_CONTENT]]>. The range of CDATA_CONTENT is defined as the characters between <![CDATA[ and the first subsequent ]]>.\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 \nExample 1:\n\nInput: code = \"<DIV>This is the first line <![CDATA[<div>]]></DIV>\"\nOutput: true\nExplanation: \nThe code is wrapped in a closed tag : <DIV> and </DIV>. \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 = \"<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>\"\nOutput: true\nExplanation:\nWe first separate the code into : start_tag|tag_content|end_tag.\nstart_tag -> \"<DIV>\"\nend_tag -> \"</DIV>\"\ntag_content could also be separated into : text1|cdata|text2.\ntext1 -> \">> ![cdata[]] \"\ncdata -> \"<![CDATA[<div>]>]]>\", where the CDATA_CONTENT is \"<div>]>\"\ntext2 -> \"]]>>]\"\nThe reason why start_tag is NOT \"<DIV>>>\" is because of the rule 6.\nThe reason why cdata is NOT \"<![CDATA[<div>]>]]>]]>\" is because of the rule 7.\n\n\nExample 3:\n\nInput: code = \"<A> <B> </A> </B>\"\nOutput: false\nExplanation: Unbalanced. If \"<A>\" is closed, then \"<B>\" must be unmatched, and vice versa.\n\n\n \nConstraints:\n\n\n\t1 <= code.length <= 500\n\tcode consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '.\n\n", "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] == '': 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", "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 parseCData(string& s, int pos) {\n //cout << \"Parse cdata \" << s.substr(pos) << endl; \n const string startPattern = \"\";\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 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& 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 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};", "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 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}", "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 parseCData(string& s, int pos) {\n //cout << \"Parse cdata \" << s.substr(pos) << endl;\n const string startPattern = \"\";\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 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& 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 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};" }, { "title": "Delete Operation for Two Strings", "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 \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 \nConstraints:\n\n\n\t1 <= word1.length, word2.length <= 500\n\tword1 and word2 consist of only lowercase English letters.\n\n", "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] )", "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};", "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> table(s1.length() + 1, vector(s2.length() + 1));\n for(int i=1; i 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)", "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*/", "solution_java": "class Solution {\n Mapmap= new HashMap<>();\n public boolean wordBreak(String s, List 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& wordDict) {\n int m = wordDict.size();\n int n = s.size();\n vector 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};" }, { "title": "Minimum Garden Perimeter to Collect Enough Apples", "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 >= 0\n\t-x if x < 0\n\n\n \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 \nConstraints:\n\n\n\t1 <= neededApples <= 1015\n\n", "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 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", "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)", "solution_java": "class Solution {\n\npublic List findNumOfValidWords(String[] words, String[] puzzles) {\n \n Map 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 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}", "solution_c": "class Solution {\npublic:\n vector findNumOfValidWords(vector& words, vector& puzzles) {\n unordered_map maskCnt;\n for(const auto& w: words) ++maskCnt[bitmask(w)];\n vector 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};" }, { "title": "Capitalize the Title", "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 \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 \nConstraints:\n\n\n\t1 <= title.length <= 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", "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)", "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};", "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}", "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};" }, { "title": "Reorder List", "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 \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 \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 5 * 104].\n\t1 <= Node.val <= 1000\n\n", "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 ", "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}", "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}", "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};" }, { "title": "Rotting Oranges", "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 \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 \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 10\n\tgrid[i][j] is 0, 1, or 2.\n\n", "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=0 and r+Rows0:\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", "solution_js": "let convertAdjacentCellsToRotten = (grid, locations, rottenOranges) => {\n let didConvertAny = false;\n let newLocations = [];\n for(let i=0;i= 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 q = new LinkedList<>();\n for(int i=0;i= 0 && c >= 0 && r >& grid) {\n int R = grid.size();\n int C = grid[0].size();\n queue> 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 xDir {-1, 0, 0, 1};\n vector 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& 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};" }, { "title": "Maximum Number of Words Found in Sentences", "algo_input": "A sentence is a list of words that are separated by a single space 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 \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 \nConstraints:\n\n\n\t1 <= sentences.length <= 100\n\t1 <= sentences[i].length <= 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", "solution_py": "class Solution:\n def mostWordsFound(self, ss: List[str]) -> int:\n return max(s.count(\" \") for s in ss) + 1", "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};", "solution_java": "class Solution {\n public int mostWordsFound(String[] sentences) {\n int max=0;\n for(int i=0; i& 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};" }, { "title": "Sort Even and Odd Indices Independently", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i] <= 100\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector sortEvenOdd(vector& nums) {\n vector 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());\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};" }, { "title": "Happy Number", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "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", "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};", "solution_java": "class Solution {\n public boolean isHappy(int n) {\n // Create a hash set...\n Set hset = new HashSet();\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}", "solution_c": "class Solution {\npublic:\n bool isHappy(int n) {\n // Create a set...\n set 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};" }, { "title": "Similar String Groups", "algo_input": "Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.\n\nFor example, \"tars\" and \"rats\" 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\"}.  Notice that \"tars\" and \"arts\" are in the same group even though they are not similar.  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 \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 \nConstraints:\n\n\n\t1 <= strs.length <= 300\n\t1 <= strs[i].length <= 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", "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", "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};", "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}", "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;i2)return 0;\n }\n return 1;\n }\n\n void dfs(string x,unordered_map>&adj,unordered_set&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& strs) {\n int n = strs.size();\n unordered_map>adj;\n for(int i=0;ivisited;\n for(auto x:strs)\n {\n if(visited.find(x)==visited.end())\n {\n //cout< 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", "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};", "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 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}", "solution_c": "class Solution {\npublic:\n bool isValid(string s) {\n stackst;\n for(int i=0;i 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", "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{\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};", "solution_java": "class Solution {\n public List> accountsMerge(List> accounts) {\n \n int l = accounts.size();\n UnionFind uf = new UnionFind(l);\n \n Map emailToNameId = new HashMap<>();\n \n for(int i=0; i account = accounts.get(i);\n for(int j=1; j> nameIdToEmails = new HashMap<>();\n for(int i=0; i());\n List account = accounts.get(i);\n List 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> out = new ArrayList<>();\n for(int id : nameIdToEmails.keySet()) {\n String name = accounts.get(id).get(0);\n List 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 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}", "solution_c": "class Solution {\npublic:\n vector> accountsMerge(vector>& accounts) {\n mapstop;\n mapname;\n int count=0;\n vectorpar(1005,0),sz(1005,1);\n for(int i=1;i<=1000;i++)\n {\n par[i]=i;\n }\n function findpar = [&](int a) -> int {\n if(a==par[a])return par[a];\n return par[a]=findpar(par[a]);\n };\n function dounion =[&](int a,int b) ->void {\n a=findpar(a);\n b=findpar(b);\n if(a!=b)\n {\n if(sz[a]curpar;\n for(int i=1;i>ans;\n \n for(int i=1;i<=1000;i++)\n {\n vector 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};" }, { "title": "Minimum Area Rectangle II", "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 \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 \nConstraints:\n\n\n\t1 <= points.length <= 50\n\tpoints[i].length == 2\n\t0 <= xi, yi <= 4 * 104\n\tAll the given points are unique.\n\n", "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", "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};", "solution_java": "class Solution {\n public double minAreaFreeRect(int[][] points) {\n Map, Map>> 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 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}", "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>& points) {\n int ans = INT_MAX;\n sort(points.begin(),points.end());\n set>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};" }, { "title": "Queries on Number of Points Inside a Circle", "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 \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 \nConstraints:\n\n\n\t1 <= points.length <= 500\n\tpoints[i].length == 2\n\t0 <= x​​​​​​i, y​​​​​​i <= 500\n\t1 <= queries.length <= 500\n\tqueries[j].length == 3\n\t0 <= xj, yj <= 500\n\t1 <= rj <= 500\n\tAll coordinates are integers.\n\n\n \nFollow up: Could you find the answer for each query in better complexity than O(n)?\n", "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", "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};", "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>& 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 &p, const vector &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> &t, const vector &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 countPoints(vector>& points, vector>& queries) {\n buildTree(points, 0, 0, points.size());\n\n vector 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};" }, { "title": "Course Schedule IV", "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 \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 \nConstraints:\n\n\n\t2 <= numCourses <= 100\n\t0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)\n\tprerequisites[i].length == 2\n\t0 <= ai, bi <= n - 1\n\tai != bi\n\tAll the pairs [ai, bi] are unique.\n\tThe prerequisites graph has no cycles.\n\t1 <= queries.length <= 104\n\t0 <= ui, vi <= n - 1\n\tui != vi\n\n", "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", "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};", "solution_java": "class Solution {\n public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {\n // Generating Map\n Map> 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 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> adj, Set 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}", "solution_c": "// question similar to find all ancestors of current node\n\nclass Solution {\n\npublic:\n\n void dfs(vector>&adj,vector>&Anc,int u,int par,vector&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 checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) {\n\n int n = numCourses ;\n vector>adj(n);\n vector>Anc(n);\n vectorans;\n\n for(auto&edge:prerequisites)\n {\n adj[edge[0]].push_back(edge[1]) ;\n }\n\n for(int i=0;ivis(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};" }, { "title": "K-Concatenation Maximum Sum", "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 \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 \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t1 <= k <= 105\n\t-104 <= arr[i] <= 104\n\n", "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)", "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;iresult) result = temp;\n }\n return (sum>0&&k>2) ? (result+sum*(k-2))%MOD : result%MOD;\n};", "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=0 )\n return (int)( (kadane(temp)%mod)+ ((sum%mod) * (k-2)%mod) %mod);\n else\n return (kadane(temp)%mod );\n }\n}", "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& 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 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(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};" }, { "title": "Stone Game", "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 \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 \nConstraints:\n\n\n\t2 <= piles.length <= 500\n\tpiles.length is even.\n\t1 <= piles[i] <= 500\n\tsum(piles[i]) is odd.\n\n", "solution_py": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n return True", "solution_js": "var stoneGame = function(piles) {\n return true;\n};", "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}", "solution_c": "class Solution {\npublic:\n\n int solve(vector&piles, int i, int j, vector>&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& piles) {\n int n = piles.size();\n vector>dp(n, vector(n,-1));\n return solve(piles, 0, n-1, dp);\n }\n};" }, { "title": "Convert Sorted Array to Binary Search Tree", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-104 <= nums[i] <= 104\n\tnums is sorted in a strictly increasing order.\n\n", "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)", "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};", "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}", "solution_c": "class Solution {\npublic:\n TreeNode* sortedArrayToBST(vector& 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 l (nums.begin(), nums.begin()+mid); //left subarray\n vector 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};" }, { "title": "Count Special Quadruplets", "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 < b < c < d\n\n\n \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 \nConstraints:\n\n\n\t4 <= nums.length <= 50\n\t1 <= nums[i] <= 100\n\n", "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])", "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};", "solution_java": "class Solution {\n public int countQuadruplets(int[] nums) {\n int res = 0;\n int len = nums.length;\n \n Map 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}", "solution_c": "class Solution {\npublic:\n int countQuadruplets(vector& nums) {\n int n=nums.size();\n unordered_map m;\n int ans=0;\n for(int i=1;i 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", "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 strs[i+1]) {\n inOrder = false;\n for(let index = 0; index strs[i+1][index]) {\n deleteIndex = index;\n break;\n }\n }\n }\n }\n for(let i=0; istrs[j+1].charAt(i)){\n res++;\n break;\n } \n }\n if(j 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& a){\n for(int i:a){\n if(arr[i]!=-1){\n return 1;\n }\n }\n return 0;\n }\nint minDeletionSize(vector& strs) {\n\n int ans=0;\n// for iterating columns\n for(int i=0;istrs[j+1][i]){\n\n ans++;\n arr[i]=-1; // make the column invalid\n break;\n }\n if(strs[j][i] 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)", "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};", "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) {\n int even=0,odd=0;\n for(int i=0;i 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 ", "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};", "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 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)", "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};", "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}", "solution_c": "class Solution {\npublic:\n int maxSubarraySumCircular(vector& 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;i0 ? max(ansmax,sum-ansmin) : ansmax;\n }\n};" }, { "title": "Number of Digit One", "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 \nExample 1:\n\nInput: n = 13\nOutput: 6\n\n\nExample 2:\n\nInput: n = 0\nOutput: 0\n\n\n \nConstraints:\n\n\n\t0 <= n <= 109\n\n", "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", "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};", "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)", "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))" }, { "title": "Fibonacci Number", "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 > 1.\n\n\nGiven n, calculate F(n).\n\n \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 \nConstraints:\n\n\n\t0 <= n <= 30\n\n", "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]", "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};", "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}", "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};" }, { "title": "Longest Path With Different Adjacent Characters", "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 \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 -> 1 -> 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 -> 0 -> 3. The length of this path is 3, so 3 is returned.\n\n\n \nConstraints:\n\n\n\tn == parent.length == s.length\n\t1 <= n <= 105\n\t0 <= parent[i] <= n - 1 for all i >= 1\n\tparent[0] == -1\n\tparent represents a valid tree.\n\ts consists of only lowercase English letters.\n\n", "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]", "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};", "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> 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> 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}", "solution_c": "class Solution {\npublic:\n vector>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 vectorv(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]& parent, string s) {\n int n = s.size();\n \n ans =0;\n g.assign(n+1,{});\n for(int i=1;i 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", "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};", "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}", "solution_c": "class Solution {\npublic:\n bool check(stack 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 stackst;\n string str = \"\" ;\n for(int i=0;i= 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};" }, { "title": "Sum of Even Numbers After Queries", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-104 <= nums[i] <= 104\n\t1 <= queries.length <= 104\n\t-104 <= vali <= 104\n\t0 <= indexi < nums.length\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector sumEvenAfterQueries(vector& nums, vector>& 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 ans(queries.size());\n bool a=false,b=false;\n for(int i=0;i 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", "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};", "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}", "solution_c": "class Solution {\npublic:\n\n int fun( int i , int k , int p , vector& rollMax ,vector< vector< vector > > &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) {\n vector< vector< vector > > dp(n+1, vector< vector >(7 , vector(16,-1)));\n int ans=fun(n,0,1,rollMax,dp) ;\n return ans ;\n }\n};" }, { "title": "Nim Game", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def canWinNim(self, n: int) -> bool:\n return n%4", "solution_js": "var canWinNim = function(n) {\n if(n%4==0) return false;\n else return true;\n};", "solution_java": "class Solution {\n public boolean canWinNim(int n) {\n if(n%4==0) return false;\n\n return true;\n }\n}", "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 dp(n+1);\n dp[1]=true,dp[2]=true,dp[3]=true,dp[4]=false;\n for(int i=5;i 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]", "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 */", "solution_java": "class ProductOfNumbers {\n List 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}", "solution_c": "class ProductOfNumbers {\nprivate:\n vector 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};" }, { "title": "Different Ways to Add Parentheses", "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 \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 \nConstraints:\n\n\n\t1 <= expression.length <= 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", "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", "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> memo = new HashMap<>();\n public List diffWaysToCompute(String expression) {\n List res = new LinkedList<>();\n if(memo.containsKey(expression)) return memo.get(expression);\n\n for(int i = 0; i left = diffWaysToCompute(expression.substring(0, i));\n List 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}", "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 rec(string &s, int i, int j, vector>> &dp)\n {\n if(dp[i][j].size() > 0){\n return dp[i][j];\n }\n vector ans;\n for (int k = i; k <= j; k++)\n {\n if(s[k] == '+' || s[k] == '*' || s[k] == '-'){\n vector v1 = rec(s, i, k - 1, dp);\n vector 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 diffWaysToCompute(string expression) {\n int n = expression.length() + 1;\n vector>> dp(n, vector>(n, vector()));\n return rec(expression, 0, expression.length()-1, dp);\n }\n};" }, { "title": "Groups of Special-Equivalent Strings", "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\" -> \"xzzy\" -> \"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 \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 \nConstraints:\n\n\n\t1 <= words.length <= 1000\n\t1 <= words[i].length <= 20\n\twords[i] consist of lowercase English letters.\n\tAll the strings are of the same length.\n\n", "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]))", "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};", "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 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 evens = new HashMap<>();\n HashMap 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}", "solution_c": "class Solution {\npublic:\n int numSpecialEquivGroups(vector& words) {\n int n = words.size();\n vector>v;\n for(auto it:words) {\n string even = \"\";\n string odd = \"\";\n for(int i = 0;im;\n for(auto it:v) {\n m[it.second]++;\n }\n\n return m.size();\n }\n};" }, { "title": "UTF-8 Validation", "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 \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 \nConstraints:\n\n\n\t1 <= data.length <= 2 * 104\n\t0 <= data[i] <= 255\n\n", "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", "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);", "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>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}", "solution_c": "class Solution{\npublic:\n bool validUtf8(vector &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};" }, { "title": "Count Negative Numbers in a Sorted Matrix", "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 \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 \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 100\n\t-100 <= grid[i][j] <= 100\n\n\n \nFollow up: Could you find an O(n + m) solution?", "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", "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= 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}", "solution_c": "class Solution {\npublic:\n int countNegatives(vector>& grid) {\n int ans = 0; for (auto hehe : grid) for (int i : hehe) if (i < 0) ans++; return ans;\n }\n};" }, { "title": "Shopping Offers", "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 \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 \nConstraints:\n\n\n\tn == price.length == needs.length\n\t1 <= n <= 6\n\t0 <= price[i], needs[i] <= 10\n\t1 <= special.length <= 100\n\tspecial[i].length == n + 1\n\t0 <= special[i][j] <= 50\n\n", "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)", "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};", "solution_java": "class Solution {\n public static int fun(int index,List price,List> special, List needs){\n // Base \n if(index < 0){\n int addAmount = 0;\n for(int i=0;i(needs));\n\n // Take Offer \n int takeOffer = 1000000000;\n if(canTakeOffer(special.get(index),new ArrayList<>(needs))){\n List current_special = special.get(index);\n for(int i=0;i(needs));\n }\n return Math.min(notTakeOffer,takeOffer);\n }\n\n public static boolean canTakeOffer(List current_special, List needs){\n boolean canTake = true;\n for(int i=0;i price, List> special, List needs) {\n int items = price.size();\n int offers = special.size();\n return fun(offers-1,price,special,needs);\n }\n}", "solution_c": "/* Note: This code results in a Timeout. */\nclass Solution {\npublic:\n int n, c;\n vector dp;\n int compute(const vector &price, const vector> &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>(i*4))&0xf);\n best += c * price[i];\n }\n if(best == 0) return 0;\n for(const vector &offer : offers){\n new_needs = 0;\n for(i=0; i>(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& price, vector>& special, vector& needs) {\n dp.resize((1<<24)+10, -1);\n n = needs.size();\n int needs_hash{};\n for(int i=0; i 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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector sortArrayByParity(vector& nums)\n {\n vector v;\n vector 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};" }, { "title": "Arranging Coins", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "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", "solution_js": "var arrangeCoins = function(n) {\n if(n===1) return n\n for(let i=1; i<=n; i++){\n if(n 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}", "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};" }, { "title": "Intersection of Two Arrays II", "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 \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 \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 1000\n\t0 <= nums1[i], nums2[i] <= 1000\n\n\n \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", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector intersect(vector& nums1, vector& 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 vectorres;\n\n while(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};" }, { "title": "Maximum Number of Visible Points", "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 \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 \nConstraints:\n\n\n\t1 <= points.length <= 105\n\tpoints[i].length == 2\n\tlocation.length == 2\n\t0 <= angle < 360\n\t0 <= posx, posy, xi, yi <= 100\n\n", "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", "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> points, int angle, List location) {\n int overlap = 0;\n List list = new ArrayList<>(points.size());\n for (List 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}", "solution_c": "class Solution {\npublic:\n int visiblePoints(vector>& points, int angle, vector& location) {\n vector 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; iangle)\n l++;\n ret = max(ret, r-l+1);\n }\n return ret+at_start;\n }\n};" }, { "title": "Robot Return to Origin", "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 \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 \nConstraints:\n\n\n\t1 <= moves.length <= 2 * 104\n\tmoves only contains the characters 'U', 'D', 'L' and 'R'.\n\n", "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", "solution_js": "var judgeCircle = function(moves) {\n let x=0,y=0\n for(i=0;i findErrorNums(vector& nums) \n {\n unordered_map 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.", "solution_js": "class Solution {\npublic:\n vector findErrorNums(vector& nums) \n {\n unordered_map 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.", "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)", "solution_c": "class Solution {\npublic:\n vector findErrorNums(vector& nums)\n {\n unordered_map 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." }, { "title": "All Possible Full Binary Trees", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 20\n\n", "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 😊", "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};", "solution_java": "class Solution {\n List[] memo;\n public List allPossibleFBT(int n) {\n memo = new ArrayList[n+1];\n return dp(n);\n }\n\n public List dp(int n){\n if(n==0 || n==2){\n return new ArrayList();\n }\n if(n==1){\n List temp = new ArrayList<>();\n temp.add(new TreeNode(0));\n return temp;\n }\n List res = new ArrayList<>();\n for(int i=1;i right;\n List 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}", "solution_c": "class Solution {\npublic:\n unordered_map> dp;\n int hash(int i,int j){\n return (i*21 + j);\n }\n vector 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 res;\n if(r left = fn(l,i-1);\n vector 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 allPossibleFBT(int n) {\n return fn(1,n);\n }" }, { "title": "Count Asterisks", "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 \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 \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts consists of lowercase English letters, vertical bars '|', and asterisks '*'.\n\ts contains an even number of vertical bars '|'.\n\n", "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 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", "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};", "solution_java": "class Solution {\n Map 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}", "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 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};" }, { "title": "Find the Most Competitive Subsequence", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 109\n\t1 <= k <= nums.length\n\n", "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]", "solution_js": "var mostCompetitive = function(nums, k) {\n let nbToRemove = nums.length - k,stack=[];\n for (const num of nums) {\n while (num0 && stack[j-1]>nums[i] && j+nums.length-i>k) {\n j--;\n }\n if(j mostCompetitive(vector& nums, int k) {\n vector 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(stack.begin(), stack.begin()+k);\n }\n};" }, { "title": "Binary Trees With Factors", "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 \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 \nConstraints:\n\n\n\t1 <= arr.length <= 1000\n\t2 <= arr[i] <= 109\n\tAll the values of arr are unique.\n\n", "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)", "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};", "solution_java": "class Solution {\n int mod = 1000000007;\n HashMap dp;\n HashSet 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}", "solution_c": "class Solution {\npublic:\n const int mod=1e9+7;\n int numFactoredBinaryTrees(vector& arr) {\n\n sort(arr.begin(),arr.end());\n int n=arr.size();\n\n vector dp(n,1);\n\n for(int i=1;iarr[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};" }, { "title": "Count Good Meals", "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 \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 \nConstraints:\n\n\n\t1 <= deliciousness.length <= 105\n\t0 <= deliciousness[i] <= 220\n\n", "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```", "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};", "solution_java": "class Solution {\n int mod = 1000000007;\n public int countPairs(int[] arr) {\n Map 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}", "solution_c": "class Solution {\npublic:\n int countPairs(vector& deliciousness) {\n int cnt=0;\n unordered_map mp;\n mp[deliciousness[0]]++;\n int mod=1e9+7;\n for(int i=1;i 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))", "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};", "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 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 buildRepeatList(String password) {\n List 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}", "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 };" }, { "title": "Binary Tree Level Order Traversal", "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 \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 \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 2000].\n\t-1000 <= Node.val <= 1000\n\n", "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", "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};", "solution_java": "class Solution {\n public List> levelOrder(TreeNode root) {\n List> result = new ArrayList<>();\n if(root == null)\n return result;\n List 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> result) {\n if(root == null)\n return;\n List 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 exploreChildren(TreeNode root) {\n List 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}", "solution_c": "class Solution {\npublic:\n vector> levelOrder(TreeNode* root) {\n queueq;\n vector> result;\n if(root==NULL) return result;\n q.push(root);\n q.push(NULL);\n vectortemp;\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};" }, { "title": "Maximum Sum Obtained of Any Permutation", "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 \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] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> 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] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> 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 \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t0 <= nums[i] <= 105\n\t1 <= requests.length <= 105\n\trequests[i].length == 2\n\t0 <= starti <= endi < n\n\n", "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)", "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};", "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 createPermutation(vector&nums , vector> &requests){\n sort(begin(nums),end(nums)) ;\n \n vectorsweep(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 aux(nums.size()) ;\n set> 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& nums, vector>& requests) {\n vector aux = createPermutation(nums,requests);\n vectorpref ;\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};" }, { "title": "Stock Price Fluctuation", "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 \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 \nConstraints:\n\n\n\t1 <= timestamp, price <= 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", "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", "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 */", "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 max = new PriorityQueue<>((sr1, sr2) -> (sr2.price - sr1.price));\n PriorityQueue min = new PriorityQueue<>((sr1, sr2) -> (sr1.price - sr2.price));\n StockRecord current_record;\n Map 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}", "solution_c": "class StockPrice {\n map stock; \n map prices;\n pair 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};" }, { "title": "Flip Equivalent Binary Trees", "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 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 \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 \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", "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)", "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};", "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}", "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};" }, { "title": "Array of Doubled Pairs", "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 <= i < len(arr) / 2, or false otherwise.\n\n \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 \nConstraints:\n\n\n\t2 <= arr.length <= 3 * 104\n\tarr.length is even.\n\t-105 <= arr[i] <= 105\n\n", "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", "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};", "solution_java": "class Solution {\n public boolean canReorderDoubled(int[] arr) {\n Map 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}", "solution_c": "class Solution {\npublic:\n bool func(vector pos){\n map mp;\n for(int i=0;imp[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& arr) {\n int n=arr.size();\n vector 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 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", "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=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>& mat) {\n int n = mat.size(), m = mat[0].size();\n vector> v(n,vector(m+1,0));\n for(int i=0; i 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)", "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};", "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 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}", "solution_c": "class Solution {\npublic:\n\n int get_max(vector&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&arr , int idx , int k , vector>&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 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& arr, int k) {\n vector>dp(arr.size()+1 , vector( k + 1 , -1 ));\n\n return solve( arr , 0 , k , dp );\n }\n};" }, { "title": "Count Items Matching a Rule", "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 \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 \nConstraints:\n\n\n\t1 <= items.length <= 104\n\t1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10\n\truleKey is equal to either \"type\", \"color\", or \"name\".\n\tAll strings consist only of lowercase letters.\n\n", "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)", "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};", "solution_java": "class Solution {\n public int countMatches(List> items, String ruleKey, String ruleValue) {\n int res = 0;\n\n for(int i = 0 ;i>& 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 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)", "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};", "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 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 */", "solution_c": "class StockSpanner {\npublic:\n stack>s; //val , index\n vectorprices;\n vectorres;\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 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", "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};", "solution_java": "class Solution {\n public int secondHighest(String s) {\n int[] arr = new int[10];\n for(int i = 0;i=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}", "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};" }, { "title": "Design Underground System", "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 < t2. All events happen in chronological order.\n\n \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\" -> \"Waterloo\" in 15-3 = 12\nundergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\nundergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\nundergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"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\" -> \"Waterloo\" in 38-24 = 14\nundergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"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\" -> \"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\" -> \"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\" -> \"Paradise\" in 30-21 = 9\nundergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n\n\n \nConstraints:\n\n\n\t1 <= id, t <= 106\n\t1 <= stationName.length, startStation.length, endStation.length <= 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", "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])", "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};", "solution_java": "class UndergroundSystem {\n HashMap travelMap;\n HashMap 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}", "solution_c": "typedef pair PSI;\ntypedef pair PSS;\ntypedef vector VI;\ntypedef vector VPSI;\ntypedef map HPSSVI;\ntypedef map 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;icheckIn(id,stationName,t);\n * obj->checkOut(id,stationName,t);\n * double param_3 = obj->getAverageTime(startStation,endStation);\n */" }, { "title": "Prime Arrangements", "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 is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)\n\nSince the answer may be large, return the answer modulo 10^9 + 7.\n\n \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 \nConstraints:\n\n\n\t1 <= n <= 100\n\n", "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", "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 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};", "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 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};" }, { "title": "Vowels of All Substrings", "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 \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 \nConstraints:\n\n\n\t1 <= word.length <= 105\n\tword consists of lowercase English letters.\n\n", "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", "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};", "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}", "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};" }, { "title": "Jump Game V", "algo_input": "Given an array of integers arr and an integer d. In one step you can jump from index i to index:\n\n\n\ti + x where: i + x < arr.length and 0 < x <= d.\n\ti - x where: i - x >= 0 and 0 < x <= d.\n\n\nIn addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).\n\nYou can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\n\nNotice that you can not jump outside of the array at any time.\n\n \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 --> 8 --> 6 --> 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 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 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 \nConstraints:\n\n\n\t1 <= arr.length <= 1000\n\t1 <= arr[i] <= 105\n\t1 <= d <= arr.length\n\n", "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)", "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};", "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 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 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}", "solution_c": "class Solution {\n vector dp;\n int countJumps(vector& 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& 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};" }, { "title": "Count and Say", "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 \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 \nConstraints:\n\n\n\t1 <= n <= 30\n\n", "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", "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}", "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 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", "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};", "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}", "solution_c": "const vector> 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> rotateGrid(vector>& 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 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};" }, { "title": "Replace Non-Coprime Numbers in Array", "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) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.\n\n \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 \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\tThe test cases are generated such that the values in the final array are less than or equal to 108.\n\n", "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", "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};", "solution_java": "class Solution {\n\tpublic List replaceNonCoprimes(int[] nums) \n\t{\n\t\tList al=new ArrayList<>();\n\t\tlong n1=nums[0];\n\t\tint idx=1;\n\n\t\twhile(idx replaceNonCoprimes(vector& nums) {\n vector 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};" }, { "title": "Consecutive Characters", "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 \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 \nConstraints:\n\n\n\t1 <= s.length <= 500\n\ts consists of only lowercase English letters.\n\n", "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", "solution_js": "var maxPower = function(s) {\n let count = 1;\n let maxNum =1;\n\n for(let i=0;i 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}", "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};" }, { "title": "Sequentially Ordinal Rank Tracker", "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 \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 > 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 \nConstraints:\n\n\n\tname consists of lowercase English letters, and is unique among all locations.\n\t1 <= name.length <= 10\n\t1 <= score <= 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", "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", "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,node1node1.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.nodeCountthis.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) //node0)\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> map;\n private int queryNum;\n\n // Find suitable position for name in the list\n private int getIndex(String name, List 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 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}", "solution_c": "struct compareMin\n{\n bool operator() (pair p1, pair 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 p1, pair 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 , vector>, compareMin> min_heap;\n priority_queue , vector>, 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 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 s = max_heap.top();\n max_heap.pop();\n min_heap.push(s);\n return s.second;\n }\n};" }, { "title": "Count Good Triplets in an Array", "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 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.\n\nReturn the total number of good triplets.\n\n \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 < pos1y < 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 < pos2y < 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 \nConstraints:\n\n\n\tn == nums1.length == nums2.length\n\t3 <= n <= 105\n\t0 <= nums1[i], nums2[i] <= n - 1\n\tnums1 and nums2 are permutations of [0, 1, ..., n - 1].\n\n", "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", "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}", "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;i0;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}", "solution_c": "typedef long long ll;\ntypedef long double ld;\n#define mod 1000000007\n#define all(x) begin(x),end(x)\n#include \n#include \nusing namespace __gnu_pbds;\n#define ordered_set tree, rb_tree_tag,tree_order_statistics_node_update>\n\n\nclass Solution {\npublic:\n long long goodTriplets(vector& nums1, vector& nums2) {\n unordered_map 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};" }, { "title": "Numbers With Same Consecutive Differences", "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 \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 \nConstraints:\n\n\n\t2 <= n <= 9\n\t0 <= k <= 9\n\n", "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 ", "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 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}", "solution_c": "class Solution {\npublic:\n vector 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 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};" }, { "title": "Intervals Between Identical Elements", "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 \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 \nConstraints:\n\n\n\tn == arr.length\n\t1 <= n <= 105\n\t1 <= arr[i] <= 105\n\n", "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 ", "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};", "solution_java": "class Solution {\n public long[] getDistances(int[] arr) {\n long[] output = new long[arr.length];\n Map sumMap = new HashMap<>();\n Map 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}", "solution_c": "class Solution {\npublic:\n vector getDistances(vector& arr) {\n int size=arr.size();\n vectorpre(size,0),suf(size,0),ans(size,0);\n unordered_map>mp;\n \n // store index of the same elements.\n for(int i=0;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& 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};" }, { "title": "Minimum Absolute Difference Queries", "algo_input": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < 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 >= 0.\n\t-x if x < 0.\n\n\n \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 \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t1 <= nums[i] <= 100\n\t1 <= queries.length <= 2 * 104\n\t0 <= li < ri < nums.length\n\n", "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", "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};", "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 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}", "solution_c": "class Solution {\npublic:\n vector> tree;\n vector minDifference(vector& nums, vector>& queries) {\n int n = nums.size();\n\n tree = vector>(4*(n+1) + 1);\n buildtree(1, 0, n-1, nums);\n\n vector 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& 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};" }, { "title": "Minimum Swaps to Arrange a Binary Grid", "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 \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 \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 <= n <= 200\n\tgrid[i][j] is either 0 or 1\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n int minSwaps(vector>& grid) {\n\n int n = grid.size();\n vector mr(n,0);\n vector br(n,0);\n for(int i=0;ii)\n return -1;\n int count = 0;\n for(int i=0;ii){\n swap(br[i],br[j]);\n count++;\n }\n }\n }\n return count;\n }\n};" }, { "title": "Removing Minimum and Maximum From Array", "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 \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 \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-105 <= nums[i] <= 105\n\tThe integers in nums are distinct.\n\n", "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", "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;imax){\n max = nums[i];\n maxInd = i;\n }\n \n if(nums[i]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}", "solution_c": "class Solution {\npublic:\n int minimumDeletions(vector& nums) {\n\n int indmin, indmax, mini(INT_MAX), maxi(INT_MIN), n(nums.size());\n\n for (int i=0; i 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};" }, { "title": "RLE Iterator", "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 \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 \nConstraints:\n\n\n\t2 <= encoding.length <= 1000\n\tencoding.length is even.\n\t0 <= encoding[i] <= 109\n\t1 <= n <= 109\n\tAt most 1000 calls will be made to next.\n\n", "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", "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}", "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 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}", "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 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& 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 */" }, { "title": "Course Schedule III", "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 \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 \nConstraints:\n\n\n\t1 <= courses.length <= 104\n\t1 <= durationi, lastDayi <= 104\n\n", "solution_py": "class Solution {\npublic:\n bool static cmp(vector &a,vector&b) {\n return a[1] < b[1];\n }\n int scheduleCourse(vector>& courses) {\n sort(courses.begin(),courses.end(),cmp);\n int sm = 0;\n priority_queue pq;\n for(int i=0; icourses[i][1]) { \n sm-=pq.top(); // remove the biggest invalid course duration!\n pq.pop();\n }\n }\n return pq.size();\n }\n};", "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};", "solution_java": "class Solution {\n public int scheduleCourse(int[][] courses) {\n Arrays.sort(courses, (a,b)->(a[1]-b[1]));\n PriorityQueue 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}", "solution_c": "class Solution {\npublic:\n bool static cmp(vector &a,vector&b) {\n return a[1] < b[1];\n }\n int scheduleCourse(vector>& courses) {\n sort(courses.begin(),courses.end(),cmp);\n int sm = 0;\n priority_queue pq;\n for(int i=0; icourses[i][1]) {\n sm-=pq.top(); // remove the biggest invalid course duration!\n pq.pop();\n }\n }\n return pq.size();\n }\n};" }, { "title": "Decode XORed Permutation", "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 \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 \nConstraints:\n\n\n\t3 <= n < 105\n\tn is odd.\n\tencoded.length == n - 1\n\n", "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", "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};", "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}", "solution_c": "class Solution {\npublic:\n vector decode(vector& 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 res;\n res.push_back(x);\n for(int i = 0; i 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", "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};", "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}", "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 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};" }, { "title": "String Without AAA or BBB", "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 \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 \nConstraints:\n\n\n\t0 <= a, b <= 100\n\tIt is guaranteed such an s exists for the given a and b.\n\n", "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=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", "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};", "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}", "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};" }, { "title": "Maximum Score After Splitting a String", "algo_input": "Given a string s 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 \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 \nConstraints:\n\n\n\t2 <= s.length <= 500\n\tThe string s consists of characters '0' and '1' only.\n\n", "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 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};", "solution_java": "class Solution {\n public int maxScore(String s) {\n int max =0;\n for(int i =0; i 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};" }, { "title": "Design Browser History", "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 of the browser.\n\tvoid visit(string url) Visits url from the current page. It clears up all the forward history.\n\tstring back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.\n\tstring forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.\n\n\n \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 \nConstraints:\n\n\n\t1 <= homepage.length <= 20\n\t1 <= url.length <= 20\n\t1 <= steps <= 100\n\thomepage and url consist of  '.' or lower case English letters.\n\tAt most 5000 calls will be made to visit, back, and forward.\n\n", "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", "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};", "solution_java": "class BrowserHistory {\n int current;\n ArrayList 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 */", "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};" }, { "title": "Flip String to Monotone Increasing", "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 \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 \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts[i] is either '0' or '1'.\n\n", "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 ", "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};", "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 noOfZerosToRight(n,0); // R to L\n vector noOfOnesToLeft(n,0); // L to R\n\n if(s[0] == '1') noOfOnesToLeft[0] = 1;\n for(int i=1;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= 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};" }, { "title": "Find Mode in Binary Search Tree", "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 \nExample 1:\n\nInput: root = [1,null,2,2]\nOutput: [2]\n\n\nExample 2:\n\nInput: root = [0]\nOutput: [0]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-105 <= Node.val <= 105\n\n\n \nFollow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).", "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)", "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}", "solution_java": "class Solution {\n public int[] findMode(TreeNode root) {\n if(root==null) return new int[0];\n Map map = new HashMap(); //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 qu = new LinkedList(); // to itereate over the tree\n List list = new ArrayList(); //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& 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 findMode(TreeNode* root) {\n unordered_map mp;\n int maxf=INT_MIN;\n vector 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};" }, { "title": "Delivering Boxes from Storage to Ports", "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 \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 \nConstraints:\n\n\n\t1 <= boxes.length <= 105\n\t1 <= portsCount, maxBoxes, maxWeight <= 105\n\t1 <= ports​​i <= portsCount\n\t1 <= weightsi <= maxWeight\n\n", "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] 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};", "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}", "solution_c": "class Solution {\npublic:\n vector 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>& boxes, int port, int box, int weigh) {\n int n = boxes.size();\n vector trips(n+1), pref(n);\n trips[0] = 0, pref[0] = boxes[0][1];\n for(int i=1;i dp(n);\n stree = vector (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=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};" }, { "title": "Compare Version Numbers", "algo_input": "Given two version numbers, version1 and version2, compare them.\n\n\n\n\nVersion numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits 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 2.5.33 and 0.1 are valid version numbers.\n\nTo compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.\n\nReturn the following:\n\n\n\tIf version1 < version2, return -1.\n\tIf version1 > version2, return 1.\n\tOtherwise, return 0.\n\n\n \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 < 1, so version1 < version2.\n\n\n \nConstraints:\n\n\n\t1 <= version1.length, version2.length <= 500\n\tversion1 and version2 only contain digits and '.'.\n\tversion1 and version2 are valid version numbers.\n\tAll the given revisions in version1 and version2 can be stored in a 32-bit integer.\n\n", "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", "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 +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};", "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(ii2){\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 0) return 1;\n }\n \n return 0;\n \n }\n};" }, { "title": "Brick Wall", "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 \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 \nConstraints:\n\n\n\tn == wall.length\n\t1 <= n <= 104\n\t1 <= wall[i].length <= 104\n\t1 <= sum(wall[i].length) <= 2 * 104\n\tsum(wall[i]) is the same for each row i.\n\t1 <= wall[i][j] <= 231 - 1\n\n", "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", "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};", "solution_java": "class Solution {\n public int leastBricks(List> wall) \n {\n HashMap 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) {\n vector> v;\n for(auto i : wall) {\n int cs = 0;\n unordered_set st;\n for(int j=0; j 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};" }, { "title": "Count Vowel Substrings of a String", "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 \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 \nConstraints:\n\n\n\t1 <= word.length <= 100\n\tword consists of lowercase English letters only.\n\n", "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 ", "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};", "solution_java": "class Solution\n{\n public int countVowelSubstrings(String word)\n {\n int vow = 0;\n int n = word.length();\n Set 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}", "solution_c": "class Solution {\npublic:\n int countVowelSubstrings(string word) {\n int n = word.size();\n int res = 0;\n \n unordered_set vowels {'a', 'e', 'i', 'o', 'u'};\n \n for (int i = 0; i < n; i++)\n {\n unordered_set 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}; " }, { "title": "Minimum Sum of Squared Difference", "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 <= i < 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 \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 = 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 = 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 \nConstraints:\n\n\n\tn == nums1.length == nums2.length\n\t1 <= n <= 105\n\t0 <= nums1[i], nums2[i] <= 105\n\t0 <= k1, k2 <= 109\n\n", "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)", "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};", "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}", "solution_c": "class Solution {\npublic:\n long long minSumSquareDiff(vector& nums1, vector& nums2, int k1, int k2) {\n int n = nums1.size();\n vector diff(n);\n for(int i = 0; i bucket(M+1);\n for(int i = 0 ; 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};" }, { "title": "Iterator for Combination", "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 \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 \nConstraints:\n\n\n\t1 <= combinationLength <= characters.length <= 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", "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", "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};", "solution_java": "class CombinationIterator {\n\n private Queue 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}", "solution_c": "class CombinationIterator {\npublic:\n\tvectorans;\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};" }, { "title": "The Number of Weak Characters in the Game", "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 > attacki and defensej > defensei.\n\nReturn the number of weak characters.\n\n \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 \nConstraints:\n\n\n\t2 <= properties.length <= 105\n\tproperties[i].length == 2\n\t1 <= attacki, defensei <= 105\n\n", "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", "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};", "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]& a, vector& b) {\n if (a[0] != b[0]) return a[0] > b[0];\n return a[1] < b[1];\n }\n \n int numberOfWeakCharacters(vector>& 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};" }, { "title": "Backspace String Compare", "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 \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 \nConstraints:\n\n\n\t1 <= s.length, t.length <= 200\n\ts and t only contain lowercase letters and '#' characters.\n\n\n \nFollow up: Can you solve it in O(n) time and O(1) space?\n", "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)))", "solution_js": "var backspaceCompare = function(s, t) {\n let stack1 = [];\n let stack2 = [];\n \n for(let i=0; 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}", "solution_c": "class Solution {\npublic:\n bool backspaceCompare(string s, string t) {\n stack st1;\n stack st2;\n int len = s.length();\n int len2 = t.length();\n\n for(int i=0; i int:\n \"\"\"\n Eqn is: yi + yj + |xi - xj|\n Since points is sorted by x values, \n therefore, xj will always be greater than xi\n therefore xi - xj will always be negative\n So the above eqn can be rewritten as,\n (yj+xj) + (yi-xi)\n Now the problem boils down to finding maximum in sliding window of k size.\n (https://leetcode.com/problems/sliding-window-maximum/discuss/1911533/Python-or-Dequeue-or-Sliding-Window-or-Simple-Solution)\n \"\"\"\n queue = deque()\n maxVal = -sys.maxsize\n for x,y in points:\n while queue and abs(queue[0][0] - x) > k:\n queue.popleft()\n \n if queue:\n maxVal = max(maxVal, y+x+queue[0][1])\n \n while queue and queue[-1][1] <= y-x:\n queue.pop()\n \n queue.append((x, y-x))\n \n return maxVal", "solution_js": "var findMaxValueOfEquation = function(points, k) {\n let result = -Infinity;\n let queue = [];\n for(let point of points) {\n while(queue.length && point[0] - queue[0][1] > k) {\n queue.shift();\n }\n if(queue.length) {\n result = Math.max(result, queue[0][0] + point[1] + point[0]);\n }\n while(queue.length && point[1] - point[0] > queue[queue.length - 1][0]) {\n queue.pop();\n }\n queue.push([point[1] - point[0], point[0]]);\n }\n return result;\n};", "solution_java": "class Solution {\n public int findMaxValueOfEquation(int[][] points, int k) {\n int ans=Integer.MIN_VALUE;\n int i=0;\n int f=1;\n while(i < points.length) {\n if(f(points[i][0]+k))\n break;\n if((points[i][1]+points[j][1]+points[j][0]-points[i][0])>ans){\n ans=points[i][1]+points[j][1]+points[j][0]-points[i][0];\n f=j-1;\n }\n }\n i++;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int findMaxValueOfEquation(vector>& points, int k) {\n deque> dq;\n int res = -INT_MAX;\n for(auto point: points){\n while(!dq.empty() && point[0]-dq.front().second>k){\n dq.pop_front();\n }\n if(!dq.empty()){\n res = max(res, dq.front().first+point[0]+point[1]);\n }\n while(!dq.empty() && point[1]-point[0]>=dq.back().first){\n dq.pop_back();\n }\n dq.push_back({point[1]-point[0], point[0]});\n }\n return res;\n }\n};" }, { "title": "Minimum Number of Vertices to Reach All Nodes", "algo_input": "Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.\n\nFind the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.\n\nNotice that you can return the vertices in any order.\n\n \nExample 1:\n\n\n\nInput: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\nOutput: [0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].\n\nExample 2:\n\n\n\nInput: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\nOutput: [0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 10^5\n\t1 <= edges.length <= min(10^5, n * (n - 1) / 2)\n\tedges[i].length == 2\n\t0 <= fromi, toi < n\n\tAll pairs (fromi, toi) are distinct.\n", "solution_py": "class Solution:\n\tdef findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n\n\t\tparent=[[] for i in range(n)]\n\t\tfor i in edges:\n\t\t\tparent[i[1]].append(i[0])\n\t\tans=[]\n\t\tfor i in range(n):\n\t\t\tif len(parent[i])==0:\n\t\t\t\tans.append(i)\n\t\treturn ans", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[]}\n */\nvar findSmallestSetOfVertices = function(n, edges) {\n let indegree=[];\n for(let i=0;i findSmallestSetOfVertices(int n, List> edges) {\n\n int[] indegree = new int[n];\n\n for(List edge : edges) {\n indegree[edge.get(1)]++;\n }\n\n List result = new ArrayList<>();\n\n for(int i=0; i findSmallestSetOfVertices(int n, vector>& edges) {\n vectorans;\n vectorindegree(n+2),outdegree(n+2);\n for(auto i:edges)\n {\n indegree[i[1]]++;\n outdegree[i[0]]++;\n }\n for(int i=0;i List[str]:\n\n\t\tgraph = defaultdict(list)\n\t\tin_degree = defaultdict(int)\n\t\tfor r,ing in zip(recipes,ingredients):\n\t\t\tfor i in ing:\n\t\t\t\tgraph[i].append(r)\n\t\t\t\tin_degree[r]+=1\n\n\t\tqueue = supplies[::]\n\t\tres = []\n\t\twhile queue:\n\t\t\ting = queue.pop(0)\n\t\t\tif ing in recipes:\n\t\t\t\tres.append(ing)\n\n\t\t\tfor child in graph[ing]:\n\t\t\t\tin_degree[child]-=1\n\t\t\t\tif in_degree[child]==0:\n\t\t\t\t\tqueue.append(child)\n\n\t\treturn res", "solution_js": "var findAllRecipes = function(recipes, ingredients, supplies) {\n const setOfIngredients = new Set(supplies);\n const recipesWithIngredients = new Map();\n const progress = new Map();\n //map recipes to it's ingredients and set each recipe to false in another map called progress\n for(let i = 0; i < recipes.length; i++) {\n recipesWithIngredients.set(recipes[i], ingredients[i]);\n progress.set(recipes[i], false)\n }\n\n const result = [];\n\n for(const rec of recipes) {\n if(recurse(rec, recipesWithIngredients, setOfIngredients, progress)) {\n result.push(rec);\n setOfIngredients.add(rec);\n }\n }\n\n return result;\n};\n\nfunction recurse(rec, recipesWithIngredients, setOfIngredients, progress) {\n const currentIngredients = recipesWithIngredients.get(rec);\n for(const ingredient of currentIngredients) {\n if(setOfIngredients.has(rec)) continue;\n if(setOfIngredients.has(ingredient)) continue;\n\n else if(recipesWithIngredients.has(ingredient)) {\n if(progress.get(ingredient)) return false;\n progress.set(ingredient, true);\n let hasCycle = recurse(ingredient, recipesWithIngredients, setOfIngredients, progress);\n if(!hasCycle) return false;\n setOfIngredients.add(ingredient);\n } else {\n return false;\n }\n }\n return true;\n}", "solution_java": "class Solution {\n private static final int NOT_VISITED = 0;\n private static final int VISITING = 1;\n private static final int VISITED = 2;\n\n public List findAllRecipes(String[] recipes, List> ingredients, String[] supplies) {\n Map status = new HashMap<>();\n Map> prereqs = new HashMap<>();\n\n for (int i = 0; i < recipes.length; ++ i) {\n status.put(recipes[i], NOT_VISITED);\n prereqs.put(recipes[i], ingredients.get(i));\n }\n\n for (String s: supplies) {\n status.put(s, VISITED);\n }\n\n List output = new ArrayList<>();\n for (String s: recipes) {\n dfs (s, prereqs, status, output);\n }\n\n return output;\n }\n\n public boolean dfs(String s, Map> prereqs, Map status, List output) {\n if (!status.containsKey(s)) {\n return false;\n }\n\n if (status.get(s) == VISITING) {\n return false;\n }\n\n if (status.get(s) == VISITED) {\n return true;\n }\n\n status.put(s, VISITING);\n for (String p: prereqs.get(s)) {\n if (!dfs(p, prereqs, status, output)) {\n return false;\n }\n }\n status.put(s, VISITED);\n output.add(s);\n\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n \n // idea is to use TOPOLOGICAL SORTING\n \n // where any foood item with indegree 0 means that item can be created\n \n vector findAllRecipes(vector& recipes, vector>& ingredients, vector& supplies) {\n \n // store what all dependencies exist for any item\n // similar to adjacent list of any node N\n // here node N is string, and all neighbour nodes are stored as vector\n map> adjList;\n \n // to keep track of whether item can be made or still needs something before we can make it\n mapindegree;\n \n // check for each row of 2D matrix\n for(int i=0; iq;\n \n // check from the list of given supplies, if some item is independent and we can make it or use it to make others\n for(auto &x : supplies)\n if(indegree[x]==0)\n q.push(x);\n \n \n \n while(!q.empty())\n {\n string node = q.front();\n q.pop();\n \n \n for(auto &nei : adjList[node])\n {\n // remove link of all neighbours of 'node'\n indegree[nei]--;\n \n // if something becomes independent, add it to our queue\n if(indegree[nei]==0)\n q.push(nei);\n }\n }\n \n \n vector ans;\n \n // all things which have 0 indegree means that they can be made. hence, they will be part of our answer\n for(auto &x : recipes)\n if(indegree[x]==0)\n ans.push_back(x);\n \n return ans;\n }\n};" } ]