[ { "title": "Stone Game V", "algo_input": "There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\n\nIn each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\n\nThe game ends when there is only one stone remaining. Alice's is initially zero.\n\nReturn the maximum score that Alice can obtain.\n\n \nExample 1:\n\nInput: stoneValue = [6,2,3,4,5,5]\nOutput: 18\nExplanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n\n\nExample 2:\n\nInput: stoneValue = [7,7,7,7,7,7,7]\nOutput: 28\n\n\nExample 3:\n\nInput: stoneValue = [4]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= stoneValue.length <= 500\n\t1 <= stoneValue[i] <= 106\n\n", "solution_py": "from collections import defaultdict\nfrom itertools import accumulate\n\nclass Solution:\n\n def stoneGameV(self, stoneValue: List[int]) -> int:\n n = len(stoneValue)\n dp = [[0]*n for _ in range(n)]\n left = [[0]*n for _ in range(n)]\n prefix = list(accumulate(stoneValue))\n prefix = [0]+prefix+[prefix[-1]]\n\n def sum(i,j):\n return prefix[j+1]-prefix[i]\n\n row_idx = [i for i in range(n)]\n for i in range(n):\n left[i][i] = stoneValue[i]\n for d in range(1,n):\n for i in range(n-d):\n j = i+d\n while sum(i,row_idx[i]) < sum(row_idx[i]+1,j):\n row_idx[i] +=1\n if sum(i, row_idx[i]) == sum(row_idx[i]+1,j):\n dp[i][j] = max(left[i][row_idx[i]], left[j][row_idx[i]+1])\n else:\n if row_idx[i] == i:\n dp[i][j] = left[j][i+1]\n elif row_idx[i] == j:\n dp[i][j] = left[i][j-1]\n else:\n dp[i][j] = max(left[i][row_idx[i]-1], left[j][row_idx[i]+1])\n left[j][i] = max(left[j][i+1],sum(i,j)+dp[i][j])\n left[i][j] = max(left[i][j-1],sum(i,j)+dp[i][j])\n return dp[0][n-1]", "solution_js": "var stoneGameV = function(stoneValue) {\n // Find the stoneValue array's prefix sum\n let prefix = Array(stoneValue.length).fill(0);\n for (let i = 0; i < stoneValue.length; i++) {\n prefix[i] = stoneValue[i] + (prefix[i - 1] || 0);\n }\n\n let dp = Array(stoneValue.length).fill().map(() => Array(stoneValue.length).fill(0));\n\n function game(start, end) {\n if (dp[start][end]) return dp[start][end];\n if (start === end) return 0;\n\n let max = 0;\n for (let i = start + 1; i <= end; i++) {\n let sumL = prefix[i - 1] - (prefix[start - 1] || 0);\n let sumR = prefix[end] - (prefix[i - 1] || 0);\n if (sumL > sumR) {\n max = Math.max(max, sumR + game(i, end));\n } else if (sumL < sumR) {\n max = Math.max(max, sumL + game(start, i - 1));\n } else {\n // If tied, check both rows\n let left = sumR + game(i, end);\n let right = sumL + game(start, i - 1);\n max = Math.max(max, left, right);\n }\n } return dp[start][end] = max;\n }\n\n return game(0, stoneValue.length - 1);\n};", "solution_java": "class Solution {\n int dp[][];\n public int fnc(int a[], int i, int j, int sum){\n //System.out.println(i+\" \"+j);\n int n=a.length;\n if(i>j)\n return 0;\n if(j>n)\n return 0;\n if(i==j){\n dp[i][j]=-1;\n return 0;\n }\n if(dp[i][j]!=0)\n return dp[i][j];\n\n int temp=0;\n int ans=Integer.MIN_VALUE;\n\n for(int index=i;index<=j;index++){\n temp+=a[index];\n if(temp>sum-temp){\n ans=Math.max(ans,((sum-temp)+fnc(a,index+1,j,sum-temp)));\n }\n else if(temp &v,int i,int j){\n\n if(i>=j) return 0;\n\n if(dp[i][j]!=-1) return dp[i][j];\n\n int r=0;\n for(int k=i;k<=j;k++) r+=v[k];\n\n int l=0,ans=0;\n for(int k=i;k<=j;k++){\n l+=v[k];\n r-=v[k];\n if(l& stoneValue) {\n\n memset(dp,-1,sizeof(dp));\n return f(stoneValue,0,stoneValue.size()-1);\n\n }\n};" }, { "title": "Power of Two", "algo_input": "Given an integer n, return true if it is a power of two. Otherwise, return false.\n\nAn integer n is a power of two, if there exists an integer x such that n == 2x.\n\n \nExample 1:\n\nInput: n = 1\nOutput: true\nExplanation: 20 = 1\n\n\nExample 2:\n\nInput: n = 16\nOutput: true\nExplanation: 24 = 16\n\n\nExample 3:\n\nInput: n = 3\nOutput: false\n\n\n \nConstraints:\n\n\n\t-231 <= n <= 231 - 1\n\n\n \nFollow up: Could you solve it without loops/recursion?", "solution_py": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n \n if n == 0: return False\n \n k = n\n while k != 1:\n if k % 2 != 0:\n return False\n k = k // 2\n \n \n return True\n\n count = 0\n for i in range(33):\n mask = 1 << i\n \n if mask & n:\n count += 1\n \n if count > 1:\n return False\n \n if count == 1:\n return True\n return False\n\t\t", "solution_js": "var isPowerOfTwo = function(n) {\n let i=1;\n while(in)\n return false;\n return power2(index+1,n);\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPowerOfTwo(int n) {\n if(n==0) return false;\n while(n%2==0) n/=2;\n return n==1;\n }\n};" }, { "title": "N-Queens", "algo_input": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n\nGiven an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.\n\nEach solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.\n\n \nExample 1:\n\nInput: n = 4\nOutput: [[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\nExplanation: There exist two distinct solutions to the 4-queens puzzle as shown above\n\n\nExample 2:\n\nInput: n = 1\nOutput: [[\"Q\"]]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 9\n\n", "solution_py": "class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n coord = self.findNextRows(0, n)\n ans = []\n for c in coord:\n temp = []\n for j in c:\n temp.append(\".\"*j+\"Q\"+\".\"*(n-j-1))\n ans.append(temp)\n return ans\n \n def findNextRows(self, i, n, h_occ=set(), d_occ=set(), ad_occ=set()):\n\t\t'''\n\t\th_occ: occupied horizontal coordinate\n\t\td_occ: occupied diagonal\n\t\tad_occ: occupied anti-diagonal\n\t\t'''\n ans = []\n if i==n:\n return [[]]\n for j in range(n):\n if (j not in h_occ) and (j-i not in d_occ) and ((j-n+1)+i not in ad_occ):\n h_occ.add(j)\n d_occ.add(j-i)\n ad_occ.add((j-n+1)+i)\n temp = self.findNextRows(i+1, n, h_occ, d_occ, ad_occ)\n h_occ.remove(j)\n d_occ.remove(j-i)\n ad_occ.remove((j-n+1)+i)\n ans += [[j]+l for l in temp]\n return ans\n \n ", "solution_js": "// time O(n!) | space O(n^n)\nvar solveNQueens = function(n) {\n let res = [];\n \n function backtrack(board, r) {\n if (r === n) {\n // - 1 to account for adding a Q that takes up a space\n res.push(board.map((c) => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)));\n return;\n }\n \n for (let c = 0; c < n; c++) {\n // bc is the current element\n // br is the index of the element bc\n //\n // bc === c | checks row and col\n // bc === c - r + br | checks lower diagonal\n // bc === c + r - br | checks upper diagonal\n if (!board.some((bc, br) => bc === c || bc === c - r + br || bc === c + r - br)) {\n backtrack(board.concat(c), r + 1);\n }\n }\n }\n \n backtrack([], 0);\n \n return res;\n};", "solution_java": "Simple backtracking logic, try out each row and col and check position is valid or not.\n\nsince we are going row one by one, there is no way queen is placed in that row.\n\nso, we need to check col, diagonals for valid position.\n\n// col is straightforward flag for each column\n\n// dia1\n// 0 1 2 3\n// 1 2 3 4\n// 2 3 4 5\n// 3 4 5 6\n\n// dia2\n// 0 -1 -2 -3\n// 1 0 -1 -2\n// 2 1 0 -1\n// 3 2 1 0\n\nnegative numbers are not allowed as index, so we add n - 1 to diagonal2.\n\nclass Solution {\n List> ans = new LinkedList<>();\n int n;\n public List> solveNQueens(int n) {\n this.n = n;\n int[][] board = new int[n][n];\n \n boolean[] col = new boolean[n];\n boolean[] dia1 = new boolean[2 * n];\n boolean[] dia2 = new boolean[2 * n];\n \n solve(0, col, dia1, dia2, board);\n return ans;\n }\n \n public void solve(int row, boolean[] col, boolean[] dia1, boolean[] dia2, int[][] board){\n if(row == n){\n copyBoardToAns(board);\n return;\n }\n // brute force all col in that row\n for(int i = 0; i < n; i++){\n if(isValid(col, dia1, dia2, i, row)){\n col[i] = true; dia1[row + i] = true; dia2[row - i + n - 1] = true;\n board[row][i] = 1;\n solve(row + 1, col, dia1, dia2, board);\n col[i] = false; dia1[row + i] = false; dia2[row - i + n - 1] = false;\n board[row][i] = 0;\n }\n }\n }\n \n public boolean isValid(boolean[] col, boolean[] dia1, boolean[] dia2, int curCol, int curRow){\n return !col[curCol] && !dia1[curCol + curRow] && !dia2[curRow - curCol + n - 1];\n }\n \n public void copyBoardToAns(int[][] board){\n List res = new LinkedList<>();\n for(int i = 0; i < n; i++){\n String row = \"\";\n for(int j = 0; j < n; j++){\n if(board[i][j] == 1){\n row += \"Q\";\n }else{\n row += \".\";\n }\n }\n res.add(row);\n }\n ans.add(res);\n }\n}", "solution_c": "class Solution {\n bool isSafe(vector board, int row, int col, int n){\n int r=row;\n int c=col;\n \n // Checking for upper left diagonal\n while(row>=0 && col>=0){\n if(board[row][col]=='Q') return false;\n row--;\n col--;\n }\n \n row=r;\n col=c;\n // Checking for left\n while(col>=0){\n if(board[row][col]=='Q') return false;\n col--;\n }\n \n row=r;\n col=c;\n // Checking for lower left diagonal\n while(row=0){\n if(board[row][col]=='Q') return false;\n row++;\n col--;\n }\n \n return true;\n }\n \n void solve(vector> &ans, vector &board, int n, int col){\n if(col==n){\n ans.push_back(board);\n return;\n }\n \n for(int row=0;row> solveNQueens(int n) {\n vector> ans;\n vector board;\n string s(n,'.');\n for(int i=0;i bool:\n ct=0\n for i in range(1,len(num)):\n if num[i-1]>num[i]:\n ct+=1\n if num[len(num)-1]>num[0]:\n ct+=1\n return ct<=1", "solution_js": "var check = function(nums) {\n let decreased = false\n for (let i = 1; i < nums.length; i += 1) {\n if (nums[i] < nums[i - 1]) {\n if (decreased) {\n return false\n }\n decreased = true\n }\n }\n return decreased ? nums[0] >= nums[nums.length - 1] : true\n};", "solution_java": "class Solution {\n public boolean check(int[] nums) {\n // here we compare all the neighbouring elemnts and check whether they are in somewhat sorted\n // there will be a small change due to rotation in the array at only one place.\n // so if there are irregularities more than once, return false\n // else return true;\n int irregularities = 0;\n int length = nums.length;\n for (int i=0; i nums[(i + 1) % length])\n irregularities += 1;\n }\n return irregularities > 1 ? false : true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool check(vector& nums) {\n int count=0;\n for(int i=0;inums[(i+1)%nums.size()])\n count++;\n }\n return (count<=1);\n }\n};" }, { "title": "Special Positions in a Binary Matrix", "algo_input": "Given an m x n binary matrix mat, return the number of special positions in mat.\n\nA position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).\n\n \nExample 1:\n\nInput: mat = [[1,0,0],[0,0,1],[1,0,0]]\nOutput: 1\nExplanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.\n\n\nExample 2:\n\nInput: mat = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\nExplanation: (0, 0), (1, 1) and (2, 2) are special positions.\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 100\n\tmat[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution(object):\n def numSpecial(self, mat):\n \"\"\"\n :type mat: List[List[int]]\n :rtype: int\n \"\"\"\n r=len(mat)\n c=len(mat[0])\n \n r_c={}\n l_c={}\n \n for i in range(r):\n flag=0\n for j in range(c):\n if(mat[i][j]==1):\n flag+=1\n r_c[i]=flag\n for i in range(c):\n flag=0\n for j in range(r):\n if(mat[j][i]==1):\n flag+=1\n l_c[i]=flag\n ret=0\n for i in range(r):\n for j in range(c):\n if(mat[i][j]==1 and l_c[j]==1 and r_c[i]==1):\n ret+=1\n return ret", "solution_js": "/**\n * @param {number[][]} mat\n * @return {number}\n */\nvar numSpecial = function(mat) {\n let specialPostions = [];\n for(let i in mat){\n for(let j in mat[i]){\n if(mat[i][j] == 1 ){\n let horizontalOnes = 0;\n let verticalOnes = 0;\n \n for(let k in mat[i]){\n if(k != j && mat[i][k] == 1){\n horizontalOnes++;\n }\n }\n \n for(let k = 0 ; k < mat.length ; k++ ){\n if(k != i && mat[k][j] == 1){\n verticalOnes++;\n }\n }\n \n if(horizontalOnes == 0 && verticalOnes == 0){\n specialPostions.push([i,j]);\n }\n \n }\n }\n }\n \n return specialPostions.length;\n \n};", "solution_java": "class Solution {\n public int numSpecial(int[][] mat) {\n int count=0;\n for(int i=0;i>& mat) {\n vector>v;\n map>m;\n\n for(int i=0;itemp = mat[i];\n\n for(int j=0;jtemp = v[column];\n for(auto i:temp){\n if(i==1){\n countone++;\n }\n }\n if(countone==1){\n counter++;\n }\n }\n }\n return counter;\n }\n};" }, { "title": "Design Circular Deque", "algo_input": "Design your implementation of the circular double-ended queue (deque).\n\nImplement the MyCircularDeque class:\n\n\n\tMyCircularDeque(int k) Initializes the deque with a maximum size of k.\n\tboolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.\n\tboolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.\n\tint getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.\n\tint getRear() Returns the last item from Deque. Returns -1 if the deque is empty.\n\tboolean isEmpty() Returns true if the deque is empty, or false otherwise.\n\tboolean isFull() Returns true if the deque is full, or false otherwise.\n\n\n \nExample 1:\n\nInput\n[\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 2, true, true, true, 4]\n\nExplanation\nMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4\n\n\n \nConstraints:\n\n\n\t1 <= k <= 1000\n\t0 <= value <= 1000\n\tAt most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.\n\n", "solution_py": "class MyCircularDeque {\npublic:\n \n deque dq;\n \n int max_size;\n \n MyCircularDeque(int k) {\n \n max_size = k; \n }\n \n bool insertFront(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_front(value);\n \n return true;\n }\n \n return false;\n }\n \n bool insertLast(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_back(value);\n \n return true;\n }\n \n return false;\n }\n \n bool deleteFront() {\n \n if(dq.size() > 0)\n {\n dq.pop_front();\n \n return true;\n }\n \n return false;\n }\n \n bool deleteLast() {\n \n if(dq.size() > 0)\n {\n dq.pop_back();\n \n return true;\n }\n \n return false; \n }\n \n int getFront() {\n \n if(dq.size() > 0)\n return dq.front();\n \n return -1;\n }\n \n int getRear() {\n \n if(dq.size() > 0)\n return dq.back();\n \n return -1;\n }\n \n bool isEmpty() {\n \n return dq.empty();\n }\n \n bool isFull() {\n \n return dq.size() == max_size;\n }\n};", "solution_js": "class MyCircularDeque {\npublic:\n \n deque dq;\n \n int max_size;\n \n MyCircularDeque(int k) {\n \n max_size = k; \n }\n \n bool insertFront(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_front(value);\n \n return true;\n }\n \n return false;\n }\n \n bool insertLast(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_back(value);\n \n return true;\n }\n \n return false;\n }\n \n bool deleteFront() {\n \n if(dq.size() > 0)\n {\n dq.pop_front();\n \n return true;\n }\n \n return false;\n }\n \n bool deleteLast() {\n \n if(dq.size() > 0)\n {\n dq.pop_back();\n \n return true;\n }\n \n return false; \n }\n \n int getFront() {\n \n if(dq.size() > 0)\n return dq.front();\n \n return -1;\n }\n \n int getRear() {\n \n if(dq.size() > 0)\n return dq.back();\n \n return -1;\n }\n \n bool isEmpty() {\n \n return dq.empty();\n }\n \n bool isFull() {\n \n return dq.size() == max_size;\n }\n};", "solution_java": "class MyCircularDeque {\npublic:\n \n deque dq;\n \n int max_size;\n \n MyCircularDeque(int k) {\n \n max_size = k; \n }\n \n bool insertFront(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_front(value);\n \n return true;\n }\n \n return false;\n }\n \n bool insertLast(int value) {\n \n if(dq.size() < max_size)\n {\n dq.push_back(value);\n \n return true;\n }\n \n return false;\n }\n \n bool deleteFront() {\n \n if(dq.size() > 0)\n {\n dq.pop_front();\n \n return true;\n }\n \n return false;\n }\n \n bool deleteLast() {\n \n if(dq.size() > 0)\n {\n dq.pop_back();\n \n return true;\n }\n \n return false; \n }\n \n int getFront() {\n \n if(dq.size() > 0)\n return dq.front();\n \n return -1;\n }\n \n int getRear() {\n \n if(dq.size() > 0)\n return dq.back();\n \n return -1;\n }\n \n bool isEmpty() {\n \n return dq.empty();\n }\n \n bool isFull() {\n \n return dq.size() == max_size;\n }\n};", "solution_c": "class MyCircularDeque {\npublic:\n\n deque dq;\n\n int max_size;\n\n MyCircularDeque(int k) {\n\n max_size = k;\n }\n\n bool insertFront(int value) {\n\n if(dq.size() < max_size)\n {\n dq.push_front(value);\n\n return true;\n }\n\n return false;\n }\n\n bool insertLast(int value) {\n\n if(dq.size() < max_size)\n {\n dq.push_back(value);\n\n return true;\n }\n\n return false;\n }\n\n bool deleteFront() {\n\n if(dq.size() > 0)\n {\n dq.pop_front();\n\n return true;\n }\n\n return false;\n }\n\n bool deleteLast() {\n\n if(dq.size() > 0)\n {\n dq.pop_back();\n\n return true;\n }\n\n return false;\n }\n\n int getFront() {\n\n if(dq.size() > 0)\n return dq.front();\n\n return -1;\n }\n\n int getRear() {\n\n if(dq.size() > 0)\n return dq.back();\n\n return -1;\n }\n\n bool isEmpty() {\n\n return dq.empty();\n }\n\n bool isFull() {\n\n return dq.size() == max_size;\n }\n};" }, { "title": "Sum of All Subset XOR Totals", "algo_input": "The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.\n\n\n\tFor example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.\n\n\nGiven an array nums, return the sum of all XOR totals for every subset of nums. \n\nNote: Subsets with the same elements should be counted multiple times.\n\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.\n\n \nExample 1:\n\nInput: nums = [1,3]\nOutput: 6\nExplanation: The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6\n\n\nExample 2:\n\nInput: nums = [5,1,6]\nOutput: 28\nExplanation: The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28\n\n\nExample 3:\n\nInput: nums = [3,4,5,6,7,8]\nOutput: 480\nExplanation: The sum of all XOR totals for every subset is 480.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 12\n\t1 <= nums[i] <= 20\n\n", "solution_py": "class Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n def sums(term, idx):\n if idx == len(nums):\n return term\n return sums(term, idx + 1) + sums(term ^ nums[idx], idx + 1)\n\n return sums(0, 0)", "solution_js": "var subsetXORSum = function(nums) {\n let output=[];\n backtrack();\n return output.reduce((a,b)=>a+b);\n function backtrack(start = 0, arr=[nums[0]]){\n output.push([...arr].reduce((a,b)=>a^b,0));\n for(let i=start; i& nums)\n {\n int ans=0;\n for(int i=0; i<32; i++)\n {\n int mask=1< int:\n l = list(zip(efficiency,speed))\n l.sort(reverse=True)\n h = []\n res = 0\n mod = 1000000007\n mx_sum = 0\n print(l)\n for i in range(n):\n res = max(res , (mx_sum+l[i][1])*l[i][0])\n if len(h) i)\n ord.sort((a,b) => efficiency[b] - efficiency[a])\n let sppq = new MinPriorityQueue(),\n totalSpeed = 0n, best = 0n\n for (let eng of ord) {\n sppq.enqueue(speed[eng])\n if (sppq.size() <= k) totalSpeed += BigInt(speed[eng])\n else totalSpeed += BigInt(speed[eng] - sppq.dequeue().element)\n let res = totalSpeed * BigInt(efficiency[eng])\n if (res > best) best = res\n }\n return best % 1000000007n\n};", "solution_java": "class Engineer {\n int speed, efficiency;\n Engineer(int speed, int efficiency) {\n this.speed = speed;\n this.efficiency = efficiency;\n }\n}\n\nclass Solution {\n public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {\n List engineers = new ArrayList<>();\n for(int i=0;i b.efficiency - a.efficiency);\n PriorityQueue maxHeap = new PriorityQueue<>((a,b) -> a.speed - b.speed);\n long maxPerformance = 0l, totalSpeed = 0l;\n for(Engineer engineer: engineers) {\n if(maxHeap.size() == k) {\n totalSpeed -= maxHeap.poll().speed;\n }\n totalSpeed += engineer.speed;\n maxHeap.offer(engineer);\n maxPerformance = Math.max(maxPerformance, totalSpeed * (long)engineer.efficiency);\n }\n return (int)(maxPerformance % 1_000_000_007);\n }\n}", "solution_c": "class Solution {\npublic:\n \n int maxPerformance(int n, vector& speed, vector& efficiency, int k) {\n priority_queue, greater> pq;\n long long sum = 0, ans = 0;\n const int m = 1e9 + 7;\n vector> pairs(n, vector (2, 0));\n for(int i = 0; i < n; i++) pairs[i] = {efficiency[i], speed[i]};\n sort(pairs.rbegin(), pairs.rend());\n for(int i = 0; i < n; i++){\n sum += pairs[i][1];\n pq.push(pairs[i][1]);\n ans = max(ans,sum * pairs[i][0]);\n if(pq.size() >= k){\n sum -= pq.top();\n pq.pop();\n }\n }\n return ans%(m);\n }\n}; " }, { "title": "Minimum Number of Taps to Open to Water a Garden", "algo_input": "There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).\n\nThere are n + 1 taps located at points [0, 1, ..., n] in the garden.\n\nGiven an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.\n\nReturn the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n\n \nExample 1:\n\nInput: n = 5, ranges = [3,4,1,1,0,0]\nOutput: 1\nExplanation: The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]\n\n\nExample 2:\n\nInput: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\tranges.length == n + 1\n\t0 <= ranges[i] <= 100\n\n", "solution_py": "class Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n maxRanges = [0]\n for i in range(len(ranges)):\n minIdx = max(i - ranges[i], 0)\n maxIdx = min(i + ranges[i], n)\n idx = bisect_left(maxRanges, minIdx)\n if idx == len(maxRanges) or maxIdx <= maxRanges[idx]: continue\n if idx == len(maxRanges) - 1:\n maxRanges.append(maxIdx)\n else:\n maxRanges[idx + 1] = max(maxRanges[idx + 1], maxIdx)\n if maxRanges[-1] < n:\n return -1\n else:\n return len(maxRanges) - 1", "solution_js": "var minTaps = function(n, ranges) {\n let intervals = [];\n for (let i = 0; i < ranges.length; i++) {\n let l = i - ranges[i];\n let r = i + ranges[i];\n intervals.push([l, r]);\n }\n\n intervals.sort((a, b) => {\n if (a[0] === b[0]) return b[1] - a[1];\n return a[0] - b[0];\n })\n\n // Find the starting idx\n let startIdx;\n for (let i = 0; i < intervals.length; i++) {\n let [s, e] = intervals[i];\n if (s <= 0) {\n if (startIdx === undefined) startIdx = i;\n else if (intervals[startIdx][1] < e) startIdx = i;\n } else break;\n }\n if (startIdx === undefined) return -1;\n\n let q = [startIdx], openedTaps = 1;\n while (q.length) {\n let max;\n while (q.length) {\n let idx = q.pop();\n let [start, end] = intervals[idx];\n if (end >= n) return openedTaps;\n for (let i = idx + 1; i < intervals.length; i++) {\n let [nextStart, nextEnd] = intervals[i];\n // If next interval's start is less than the current interval's end\n if (nextStart <= end) {\n if (!max && nextEnd > end) max = {i, end: nextEnd};\n // If the next interval's end is greater than the current interval's end\n else if (max && nextEnd > max.end) max = {i, end: nextEnd};\n }\n else break;\n }\n }\n if (max) {\n q.push(max.i);\n openedTaps++;\n }\n }\n\n return -1;\n};", "solution_java": "class Solution {\n public int minTaps(int n, int[] ranges) {\n Integer[] idx = IntStream.range(0, ranges.length).boxed().toArray(Integer[]::new);\n Arrays.sort(idx, Comparator.comparingInt(o -> o-ranges[o]));\n int ans = 1, cur = 0, end = 0;\n for (int i = 0;icur){\n cur=end;\n ans++;\n }\n if (j-ranges[j]<=cur){\n end=Math.max(end, j+ranges[j]);\n }\n }\n return end& ranges) {\n vector> v;\n for(int i=0;i= 0 and digits[i] <= digits[i-1]:\n i -= 1\n \n if i == 0: return -1\n \n j = i\n while j+1 < len(digits) and digits[j+1] > digits[i-1]:\n j += 1\n \n digits[i-1], digits[j] = digits[j], digits[i-1]\n digits[i:] = digits[i:][::-1]\n ret = int(''.join(digits))\n \n return ret if ret < 1<<31 else -1", "solution_js": "var nextGreaterElement = function(n) {\n\tconst MAX_VALUE = 2 ** 31 - 1;\n\tconst nums = `${n}`.split('');\n\tlet findPos;\n\n\tfor (let index = nums.length - 2; index >= 0; index--) {\n\t\tif (nums[index] < nums[index + 1]) {\n\t\t\tfindPos = index;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (findPos === undefined) return -1;\n\tfor (let index = nums.length - 1; index >= 0; index--) {\n\t\tif (nums[index] > nums[findPos]) {\n\t\t\t[nums[index], nums[findPos]] = [nums[findPos], nums[index]];\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tconst mantissa = nums.slice(findPos + 1).sort((a, b) => a - b).join('');\n\tconst result = Number(nums.slice(0, findPos + 1).join('') + mantissa);\n\treturn result > MAX_VALUE ? -1 : result;\n};", "solution_java": "class Solution {\n public int nextGreaterElement(int n) {\n char[] arr = (n + \"\").toCharArray();\n \n int i = arr.length - 1;\n while(i > 0){\n if(arr[i-1] >= arr[i]){\n i--;\n }else{\n break;\n }\n }\n if(i == 0){\n return -1;\n }\n \n int idx1 = i-1;\n \n int j = arr.length - 1;\n while(j > idx1){\n if(arr[j] > arr[idx1]){\n break;\n }\n j--;\n }\n \n //Swapping\n swap(arr,idx1,j);\n \n //sorting\n int left = idx1+1;\n int right = arr.length-1;\n while(left < right){\n swap(arr,left,right);\n left++;\n right--;\n }\n \n String result = new String(arr);\n long val = Long.parseLong(result);\n \n return (val > Integer.MAX_VALUE ? -1 : (int)val);\n \n }\n \n void swap(char[]arr,int i,int j){\n char temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}", "solution_c": "class Solution {\npublic:\n int nextGreaterElement(int n) {\n vectorvec;\n int temp = n;\n while(n>0){\n int r = n%10;\n vec.push_back(r);\n n /= 10; \n }\n sort(vec.begin(),vec.end());\n do{\n int num=0;\n long j=0;\n int s = vec.size()-1;\n long i = pow(10,s);\n while(i>0)\n {\n num += i*vec[j++];\n i /= 10;\n }\n if(num>temp)\n return num;\n \n } while(next_permutation(vec.begin(),vec.end()));\n return -1;\n }\n};" }, { "title": "The Time When the Network Becomes Idle", "algo_input": "There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.\n\nAll servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.\n\nThe server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.\n\nAt the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:\n\n\n\tIf it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.\n\tOtherwise, no more resending will occur from this server.\n\n\nThe network becomes idle when there are no messages passing between servers or arriving at servers.\n\nReturn the earliest second starting from which the network becomes idle.\n\n \nExample 1:\n\nInput: edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput: 8\nExplanation:\nAt (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.\n\n\nExample 2:\n\nInput: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput: 3\nExplanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.\n\n\n \nConstraints:\n\n\n\tn == patience.length\n\t2 <= n <= 105\n\tpatience[0] == 0\n\t1 <= patience[i] <= 105 for 1 <= i < n\n\t1 <= edges.length <= min(105, n * (n - 1) / 2)\n\tedges[i].length == 2\n\t0 <= ui, vi < n\n\tui != vi\n\tThere are no duplicate edges.\n\tEach server can directly or indirectly reach another server.\n\n", "solution_py": "class Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n\n #Build Adjency List\n adjList = defaultdict(list)\n\n for source, target in edges:\n adjList[source].append(target)\n adjList[target].append(source)\n\n #BFS to get the shortest route from node to master.\n shortest = {}\n queue = deque([(0,0)])\n seen = set()\n while queue:\n currPos, currDist = queue.popleft()\n\n if currPos in seen:\n continue\n seen.add(currPos)\n shortest[currPos] = currDist\n\n for nei in adjList[currPos]:\n queue.append((nei, currDist+1))\n\n #Calculate answer using shortest paths.\n ans = 0\n for index in range(1,len(patience)):\n resendInterval = patience[index]\n\n #The server will stop sending requests after it's been sent to the master node and back.\n shutOffTime = (shortest[index] * 2)\n\n # shutOffTime-1 == Last second the server can send a re-request.\n lastSecond = shutOffTime-1\n\n #Calculate the last time a packet is actually resent.\n lastResentTime = (lastSecond//resendInterval)*resendInterval\n\n # At the last resent time, the packet still must go through 2 more cycles to the master node and back.\n lastPacketTime = lastResentTime + shutOffTime\n\n ans = max(lastPacketTime, ans)\n\n #Add +1, the current answer is the last time the packet is recieved by the target server (still active).\n #We must return the first second the network is idle, therefore + 1\n return ans + 1", "solution_js": "/**\n * @param {number[][]} edges\n * @param {number[]} patience\n * @return {number}\n */\nvar networkBecomesIdle = function(edges, patience) {\n /*\n Approach:\n Lets call D is the distance from node to master\n And last message sent from node is at T\n Then last message will travel till D+T and network will be idal at D+T+1\n */ \n let edgesMap={},minDistanceFromMasterArr=[],ans=0,visited={};\n for(let i=0;i> adj = new ArrayList<>();\n for(int i = 0 ; i < n ; i++ ) {\n adj.add(new ArrayList<>());\n }\n\n for(int[] edge : edges) {\n adj.get(edge[0]).add(edge[1]);\n adj.get(edge[1]).add(edge[0]);\n }\n\n // getting the distance array using dijkstra algorithm\n int[] dist = dijkstra(adj);\n\n // variable to store the result\n int ans = 0;\n\n // performing the calculations discussed above for each index\n for(int x = 1; x < n ; x++) {\n\n // round trip time\n int time = 2*dist[x];\n\n int p = patience[x];\n\n //total number of messages the station will send until it receives the reply of first message\n int numberOfMessagesSent = (time)/p;\n\n //handling an edge case if round trip time is a multiple of patience example time =24 patience = 4\n //then the reply would be received at 24 therefore station will not send any message at t = 24\n if(time%p == 0) {\n numberOfMessagesSent--;\n }\n\n // time of last message\n int lastMessage = numberOfMessagesSent*p;\n\n // updating the ans to store max of time at which the station becomes idle\n ans = Math.max(ans,lastMessage+ 2*dist[x]+1);\n\n }\n\n return ans;\n }\n\n // simple dijkstra algorithm implementation\n private int[] dijkstra(ArrayList> adj) {\n\n int n = adj.size();\n\n int[] dist = new int[n];\n boolean[] visited = new boolean[n];\n\n Arrays.fill(dist,Integer.MAX_VALUE);\n dist[0] = 0;\n\n PriorityQueue pq = new PriorityQueue<>((o1,o2)->o1[1]-o2[1]);\n\n pq.add(new int[]{0,0});\n\n while(!pq.isEmpty()) {\n int[] node = pq.remove();\n if(!visited[node[0]]) {\n visited[node[0]] = true;\n for(int nbr : adj.get(node[0])) {\n if(dist[nbr] > dist[node[0]]+1) {\n dist[nbr] = dist[node[0]]+1;\n pq.add(new int[]{nbr,dist[nbr]});\n }\n }\n }\n\n }\n\n return dist;\n }\n\n}", "solution_c": "class Solution {\npublic:\n int networkBecomesIdle(vector>& edges, vector& patience) {\n int n = patience.size();\n vector > graph(n);\n vector time(n, -1);\n \n for(auto x: edges) { // create adjacency list\n graph[x[0]].push_back(x[1]);\n graph[x[1]].push_back(x[0]);\n }\n \n queue q;\n q.push(0);\n time[0] = 0;\n while(q.size()) {\n int node = q.front();\n q.pop();\n \n for(auto child: graph[node]) {\n if(time[child] == -1) { // if not visited.\n time[child] = time[node] + 1; // calc time for child node\n q.push(child);\n }\n }\n }\n \n int res = 0;\n for(int i = 1; i int:\n max_rank = 0\n connections = {i: set() for i in range(n)}\n for i, j in roads:\n connections[i].add(j)\n connections[j].add(i)\n for i in range(n - 1):\n for j in range(i + 1, n):\n max_rank = max(max_rank, len(connections[i]) +\n len(connections[j]) - (j in connections[i]))\n return max_rank", "solution_js": "var maximalNetworkRank = function(n, roads) {\n let res = 0\n let map = new Map()\n roads.forEach(([u,v])=>{\n map.set(u, map.get(u) || new Set())\n let set = map.get(u)\n set.add(v)\n \n map.set(v, map.get(v) || new Set())\n set = map.get(v)\n set.add(u)\n })\n \n for(let i=0;i>& roads) {\n vector>graph(n,vector(n,0));\n vectordegree(n,0);\n for(int i=0;i float:\n self.x = x\n \n if n == 0:\n return 1\n \n isInverted = False\n if n < 0:\n isInverted = True\n n = -1 * n\n\n result = self.pow(n)\n \n return result if not isInverted else 1 / result\n \n def pow(self, n):\n if n == 1:\n return self.x\n \n if n % 2 == 0:\n p = self.pow(n / 2)\n return p * p\n else:\n return self.x * self.pow(n-1)", "solution_js": "var myPow = function(x, n) {\n return x**n;\n};", "solution_java": "class Solution {\n public double myPow(double x, int n) {\n if (n == 0) return 1;\n if (n == 1) return x;\n else if (n == -1) return 1 / x;\n double res = myPow(x, n / 2);\n if (n % 2 == 0) return res * res;\n else if (n % 2 == -1) return res * res * (1/x);\n else return res * res * x;\n }\n}", "solution_c": "class Solution {\npublic:\n double myPow(double x, int n) {\n \n if(n==0) return 1; //anything to the power 0 is 1\n \n if(x==1 || n==1) return x; //1 to the power anything = 1 or x to the power 1 = x\n \n double ans = 1;\n \n long long int a = abs(n); //since int range is from -2147483648 to 2147483647, so it can't store absolute value of -2147483648\n \n if(n<0){ //as 2^(-2) = 1/2^2\n if(a%2 == 0) ans = 1/myPow(x*x,a/2);\n else ans = 1/(x * myPow(x,a-1));\n }\n else{\n if(a%2 == 0) ans = myPow(x*x,a/2);\n else ans = x * myPow(x,a-1);\n }\n \n return ans;\n \n }\n};" }, { "title": "Game of Life", "algo_input": "According to Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\"\n\nThe board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):\n\n\n\tAny live cell with fewer than two live neighbors dies as if caused by under-population.\n\tAny live cell with two or three live neighbors lives on to the next generation.\n\tAny live cell with more than three live neighbors dies, as if by over-population.\n\tAny dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n\n\nThe next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.\n\n \nExample 1:\n\nInput: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n\n\nExample 2:\n\nInput: board = [[1,1],[1,0]]\nOutput: [[1,1],[1,1]]\n\n\n \nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 <= m, n <= 25\n\tboard[i][j] is 0 or 1.\n\n\n \nFollow up:\n\n\n\tCould you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.\n\tIn this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?\n\n", "solution_py": "#pattern\nactual update ref \n0 0 0\n1 1 1\n0 1 -1\n1 0 -2\n\nclass Solution:\n\tdef gameOfLife(self, board: List[List[int]]) -> None:\n\t\tr = len(board)\n\t\tc = len(board[0])\n\t\tans = [[0]*c for _ in range(r)]\n\t\tneighs = [[1,0],[-1,0],[0,1],[0,-1],[-1,-1],[-1,1],[1,1],[1,-1]]\n\n\t\tfor i in range(r):\n\t\t\tfor j in range(c):\n\t\t\t\tlivecnt,deadcnt = 0,0\n\t\t\t\tfor di,dj in neighs:\n\t\t\t\t\tif 0<=(i+di) < r and 0<=(j+dj) {\n let radius = [-1, 0, 1], count = 0;\n for(let i = 0; i < 3; i++) {\n for(let j = 0; j < 3; j++) {\n if(!(radius[i] == 0 && radius[j] == 0) && copy[row + radius[i]] && copy[row + radius[i]][col + radius[j]]) {\n let neighbor = copy[row + radius[i]][col + radius[j]];\n if(neighbor == 1) {\n count++;\n }\n }\n }\n }\n return count;\n }\n\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n const count = getNeighbor(i, j);\n if(copy[i][j] == 1) {\n if(count < 2 || count > 3) {\n board[i][j] = 0;\n }\n } else {\n if(count == 3) {\n board[i][j] = 1;\n }\n }\n }\n }\n};", "solution_java": "class Solution {\n public void gameOfLife(int[][] board) {\n int m = board.length, n = board[0].length;\n int[][] next = new int[m][n];\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n next[i][j] = nextState(board, i, j, m, n);\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n board[i][j] = next[i][j];\n }\n }\n }\n\n public int nextState(int[][] board, int i, int j, int m, int n) {\n int ones = 0;\n for (int x = -1; x <=1; x++) {\n for (int y = -1; y <= 1; y++) {\n if (x == 0 && y == 0) {\n continue;\n }\n int a = i + x, b = j + y;\n if (a >= 0 && a < m) {\n if (b >= 0 && b < n) {\n ones += board[a][b];\n }\n }\n }\n }\n if (board[i][j] == 0) {\n return ones == 3 ? 1 : 0;\n } else {\n if (ones == 2 || ones == 3) {\n return 1;\n } else {\n return 0;\n }\n }\n }\n}", "solution_c": "// Idea: Encode the value into 2-bit value, the first bit is the value of next state, and the second bit is the value of current state\nclass Solution {\npublic:\n void gameOfLife(vector>& board) {\n int m = board.size();\n int n = board[0].size();\n for (int i=0; i>= 1;\n }\n }\n \n }\n void encode(vector>& board, int row, int col) {\n int ones = 0;\n int zeros = 0;\n int m = board.size();\n int n = board[0].size();\n int cur = board[row][col];\n if (row >= 1 && col >= 1) {\n ones += (board[row - 1][col - 1] & 1);\n zeros += !(board[row - 1][col - 1] & 1);\n }\n if (row >= 1) {\n ones += (board[row - 1][col] & 1);\n zeros += !(board[row - 1][col] & 1);\n }\n if (row >= 1 && col < n - 1) {\n ones += (board[row - 1][col + 1] & 1);\n zeros += !(board[row - 1][col + 1] & 1);\n }\n if (col < n - 1) {\n ones += (board[row][col + 1] & 1);\n zeros += !(board[row][col + 1] & 1);\n }\n if (row < m - 1 && col < n - 1) {\n ones += (board[row + 1][col + 1] & 1);\n zeros += !(board[row + 1][col + 1] & 1);\n }\n if (row < m - 1) {\n ones += (board[row + 1][col] & 1);\n zeros += !(board[row + 1][col] & 1);\n }\n if (row < m - 1 && col >= 1) {\n ones += (board[row + 1][col - 1] & 1);\n zeros += !(board[row + 1][col - 1] & 1);\n }\n if (col >= 1) {\n ones += (board[row][col - 1] & 1);\n zeros += !(board[row][col - 1] & 1);\n }\n if (ones < 2 && cur == 1) {\n cur += 0 << 1;\n } else if (ones >= 2 && ones <= 3 && cur == 1) {\n cur += 1 << 1;\n } else if (ones > 3 && cur == 1) {\n cur += 0 << 1;\n } else if (ones == 3 && cur == 0) {\n cur += 1 << 1;\n } else {\n cur += cur << 1;\n }\n board[row][col] = cur;\n }\n};" }, { "title": "Get Maximum in Generated Array", "algo_input": "You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:\n\n\n\tnums[0] = 0\n\tnums[1] = 1\n\tnums[2 * i] = nums[i] when 2 <= 2 * i <= n\n\tnums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n\n\n\nReturn the maximum integer in the array nums​​​.\n\n \nExample 1:\n\nInput: n = 7\nOutput: 3\nExplanation: According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 1\nExplanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.\n\n\nExample 3:\n\nInput: n = 3\nOutput: 2\nExplanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.\n\n\n \nConstraints:\n\n\n\t0 <= n <= 100\n\n", "solution_py": "class Solution:\n def getMaximumGenerated(self, n):\n nums = [0]*(n+2)\n nums[1] = 1\n for i in range(2, n+1):\n nums[i] = nums[i//2] + nums[(i//2)+1] * (i%2)\n \n return max(nums[:n+1])", "solution_js": "var getMaximumGenerated = function(n) {\n if (n === 0) return 0;\n if (n === 1) return 1;\n let arr = [0, 1];\n let max = 0;\n for (let i = 0; i < n; i++) {\n if (2 <= 2 * i && 2 * i <= n) {\n arr[2 * i] = arr[i]\n if (arr[i] > max) max = arr[i];\n }\n if (2 <= 2 * i && 2 * i + 1 <= n) {\n arr[2 * i + 1] = arr[i] + arr[i + 1]\n if (arr[i] + arr[i + 1] > max) max = arr[i] + arr[i + 1];\n };\n }\n return max;\n};", "solution_java": "class Solution {\n public int getMaximumGenerated(int n) {\n if(n==0 || n==1) return n;\n\n int nums[]=new int [n+1];\n\n nums[0]=0;\n nums[1]=1;\n int max=Integer.MIN_VALUE;\n\n for(int i=2;i<=n;i++){\n if(i%2==0){\n nums[i]=nums[i/2];\n }\n else{\n nums[i]=nums[i/2]+nums[i/2 + 1];\n }\n max=Math.max(max,nums[i]);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int getMaximumGenerated(int n) {\n // base cases\n if (n < 2) return n;\n // support variables\n int arr[n + 1], m;\n arr[0] = 0, arr[1] = 1;\n // building arr\n for (int i = 2; i <= n; i++) {\n if (i % 2) arr[i] = arr[i / 2] + arr[i / 2 + 1];\n else arr[i] = arr[i / 2];\n // updating m\n m = max(arr[i], m);\n }\n return m;\n }\n};" }, { "title": "Cells with Odd Values in a Matrix", "algo_input": "There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.\n\nFor each location indices[i], do both of the following:\n\n\n\tIncrement all the cells on row ri.\n\tIncrement all the cells on column ci.\n\n\nGiven m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.\n\n \nExample 1:\n\nInput: m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput: 6\nExplanation: Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.\n\n\nExample 2:\n\nInput: m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput: 0\nExplanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.\n\n\n \nConstraints:\n\n\n\t1 <= m, n <= 50\n\t1 <= indices.length <= 100\n\t0 <= ri < m\n\t0 <= ci < n\n\n\n \nFollow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?\n", "solution_py": "class Solution:\n def oddCells(self, row: int, col: int, indices: List[List[int]]) -> int:\n rows, cols = [False] * row, [False] * col\n\n for index in indices:\n rows[index[0]] = not rows[index[0]]\n cols[index[1]] = not cols[index[1]]\n\n count = 0\n for i in rows:\n for j in cols:\n count += i ^ j\n\n return count", "solution_js": "var oddCells = function(m, n, indices) {\n const matrix = Array.from(Array(m), () => Array(n).fill(0));\n\n let res = 0;\n for (const [r, c] of indices) {\n for (let i = 0; i < n; i++) {\n // toggle 0/1 for even/odd\n // another method: matrix[r][i] = 1 - matrix[r][i]\n // or: matrix[r][i] = +!matrix[r][i]\n matrix[r][i] ^= 1;\n if (matrix[r][i]) res++; else res--;\n }\n\n for (let i = 0; i < m; i++) {\n matrix[i][c] ^= 1;\n if (matrix[i][c]) res++; else res--;\n }\n }\n\n return res;\n};", "solution_java": "// --------------------- Solution 1 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[][] matrix = new int[m][n];\n \n for(int i = 0; i < indices.length; i++) {\n int row = indices[i][0];\n int col = indices[i][1];\n \n for(int j = 0; j < n; j++) {\n matrix[row][j]++;\n }\n for(int j = 0; j < m; j++) {\n matrix[j][col]++;\n }\n }\n \n int counter = 0;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if(matrix[i][j] % 2 != 0) {\n counter++;\n }\n }\n }\n \n return counter;\n }\n}\n\n// --------------------- Solution 2 ---------------------\nclass Solution {\n public int oddCells(int m, int n, int[][] indices) {\n int[] row = new int[m];\n int[] col = new int[n];\n \n for(int i = 0; i < indices.length; i++) {\n row[indices[i][0]]++;\n col[indices[i][1]]++;\n }\n \n int counter = 0;\n for(int i : row) {\n for(int j : col) {\n counter += (i + j) % 2 == 0 ? 0 : 1;\n }\n }\n \n return counter;\n }\n}", "solution_c": "static int x = []() {\nstd::ios::sync_with_stdio(false);\ncin.tie(nullptr);\nreturn 0; }();\n\nclass Solution { // tc: O(n+m) & sc: O(n+m)\npublic:\n int oddCells(int n, int m, vector>& indices) {\n vector rows(n,false),cols(m,false);\n for(auto index: indices){\n rows[index[0]] = rows[index[0]] ^ true;\n cols[index[1]] = cols[index[1]] ^ true;\n }\n \n int r(0),c(0);\n for(int i(0);i new Array(len).fill(0));\n\n // according to the meaning of the problem, set the value of dp\n for (let i = 0; i < len; i++) {\n dp[1][i] = sum[i] / (i + 1);\n }\n for (let i = 1; i <= k; i++) {\n dp[i][i - 1] = sum[i - 1];\n }\n for (let i = 2; i <= k; i++) {\n for (let j = i; j < len; j++) {\n for (let m = j - 1; m >= i - 2; m--) {\n dp[i][j] = Math.max(dp[i][j], dp[i - 1][m] + (sum[j] - sum[m]) / (j - m));\n }\n }\n }\n\n // result\n return dp[k][len - 1];\n};", "solution_java": "class Solution {\n Double dp[][][];\n int n;\n int k1;\n public double check(int b, int c,long sum,int n1,int ar[]){\n System.out.println(b+\" \"+c);\n if(dp[b][c][n1]!=null)\n return dp[b][c][n1];\n if(b==n){\n if(sum!=0)\n return (double)sum/(double)n1;\n else\n return 0.0;}\n if(c0)\n dp[b][c][n1]=Math.max((double)sum/(double)n1+check(b,c+1,0,0,ar),check(b+1,c,sum+(long)ar[b],n1+1,ar));\n else\n dp[b][c][n1]=check(b+1,c,sum+(long)ar[b],n1+1,ar);\n\n return dp[b][c][n1];\n }\n public double largestSumOfAverages(int[] nums, int k) {\n n=nums.length;\n k1=k-1;\n dp= new Double[n+1][k][n+1];\n return check(0,0,0l,0,nums);\n }\n}", "solution_c": "class Solution {\npublic:\n double solve(vector&nums, int index, int k, vector>&dp){\n if(index<0)\n return 0;\n if(k<=0)\n return -1e8;\n\n if(dp[index][k]!=-1)\n return dp[index][k];\n\n double s_sum = 0;\n double maxi = INT_MIN;\n int cnt = 1;\n for(int i=index;i>=0;i--){\n s_sum += nums[i];\n maxi = max(maxi, (s_sum/cnt) + solve(nums, i-1, k-1, dp));\n cnt++;\n }\n return dp[index][k] = maxi;\n }\n\n double largestSumOfAverages(vector& nums, int k) {\n int n = nums.size();\n vector>dp(n, vector(k+1, -1));\n return solve(nums, n-1, k, dp);\n }\n};" }, { "title": "Predict the Winner", "algo_input": "You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.\n\nPlayer 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.\n\nReturn true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.\n\n \nExample 1:\n\nInput: nums = [1,5,2]\nOutput: false\nExplanation: Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.\n\n\nExample 2:\n\nInput: nums = [1,5,233,7]\nOutput: true\nExplanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 20\n\t0 <= nums[i] <= 107\n\n", "solution_py": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n dp = [[-1] * len(nums) for _ in nums]\n def get_score(i: int, j: int) -> int:\n if i == j: \n dp[i][j] = 0\n return dp[i][j]\n if i == j - 1:\n dp[i][j] = nums[j] if nums[i] > nums[j] else nums[i]\n return dp[i][j]\n if dp[i][j] != -1:\n return dp[i][j]\n\n y1 = get_score(i + 1, j - 1)\n y2 = get_score(i + 2, j)\n y3 = get_score(i, j - 2)\n res_y1 = y1 + nums[j] if y1 + nums[j] > y2 + nums[i+1] else y2 + nums[i+1]\n res_y2 = y1 + nums[i] if y1 + nums[i] > y3 + nums[j-1] else y3 + nums[j-1]\n\n dp[i][j] = min(res_y1, res_y2)\n return dp[i][j] \n \n y = get_score(0, len(nums) - 1)\n x = sum(nums) - y\n\n return 0 if y > x else 1", "solution_js": "var PredictTheWinner = function(nums) {\n const n = nums.length;\n const dp = [];\n\n for (let i = 0; i < n; i++) {\n dp[i] = new Array(n).fill(0);\n dp[i][i] = nums[i];\n }\n\n for (let len = 2; len <= n; len++) {\n for (let start = 0; start < n - len + 1; start++) {\n const end = start + len - 1;\n dp[start][end] = Math.max(nums[start] - dp[start + 1][end], nums[end] - dp[start][end - 1]);\n }\n }\n\n return dp[0][n - 1] >= 0;\n};", "solution_java": "class Solution {\n public boolean PredictTheWinner(int[] nums) {\n return predictTheWinner(nums, 0, nums.length-1,true,0, 0);\n }\n private boolean predictTheWinner(int[] nums, int start,int end, boolean isP1Turn, long p1Score, long p2Score){\n if(start > end){\n return p1Score >= p2Score;\n }\n\n boolean firstTry;\n boolean secondTry;\n if(isP1Turn){\n firstTry = predictTheWinner(nums, start +1 , end, false, p1Score + nums[start], p2Score);\n secondTry = predictTheWinner(nums, start, end-1, false, p1Score + nums[end], p2Score);\n\n }else{\n firstTry = predictTheWinner(nums, start +1 , end, true, p1Score, p2Score + nums[start]);\n secondTry = predictTheWinner(nums, start, end-1, true, p1Score , p2Score + nums[end]);\n\n }\n return isP1Turn ? (firstTry || secondTry) : (firstTry && secondTry);\n }\n}", "solution_c": "class Solution {\npublic:\n bool PredictTheWinner(vector& nums) {\n vector>> dp(nums.size(),vector>(nums.size(),vector(3,INT_MAX)));\n int t=fun(dp,nums,0,nums.size()-1,1);\n return t>=0;\n }\n int fun(vector>>& dp,vector& v,int i,int j,int t)\n {\n if(i>j)\n return 0;\n \n if(dp[i][j][t+1]!=INT_MAX)\n return dp[i][j][t+1];\n \n if(t>0)\n return dp[i][j][t+1]=max(v[i]*t+fun(dp,v,i+1,j,-1),v[j]*t+fun(dp,v,i,j-1,-1));\n else\n return dp[i][j][t+1]=min(v[i]*t+fun(dp,v,i+1,j,1),v[j]*t+fun(dp,v,i,j-1,1));\n }\n};" }, { "title": "Maximum Element After Decreasing and Rearranging", "algo_input": "You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:\n\n\n\tThe value of the first element in arr must be 1.\n\tThe absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.\n\n\nThere are 2 types of operations that you can perform any number of times:\n\n\n\tDecrease the value of any element of arr to a smaller positive integer.\n\tRearrange the elements of arr to be in any order.\n\n\nReturn the maximum possible value of an element in arr after performing the operations to satisfy the conditions.\n\n \nExample 1:\n\nInput: arr = [2,2,1,2,1]\nOutput: 2\nExplanation: \nWe can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].\nThe largest element in arr is 2.\n\n\nExample 2:\n\nInput: arr = [100,1,1000]\nOutput: 3\nExplanation: \nOne possible way to satisfy the conditions is by doing the following:\n1. Rearrange arr so it becomes [1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNow arr = [1,2,3], which satisfies the conditions.\nThe largest element in arr is 3.\n\n\nExample 3:\n\nInput: arr = [1,2,3,4,5]\nOutput: 5\nExplanation: The array already satisfies the conditions, and the largest element is 5.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t1 <= arr[i] <= 109\n\n", "solution_py": "class Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\t\tcounter = collections.Counter(arr)\n available = sum(n > len(arr) for n in arr)\n i = ans = len(arr)\n while i > 0:\n # This number is not in arr\n if not counter[i]:\n # Use another number to fill in its place. If we cannot, we have to decrease our max\n if available: available -= 1 \n else: ans -= 1\n # Other occurences can be used for future.\n else:\n available += counter[i] - 1\n i -= 1\n return ans", "solution_js": "var maximumElementAfterDecrementingAndRearranging = function(arr) {\n if (!arr.length) return 0\n arr.sort((a, b) => a - b)\n arr[0] = 1\n for (let i = 1; i < arr.length; i++) {\n if (Math.abs(arr[i] - arr[i - 1]) > 1) arr[i] = arr[i - 1] + 1\n }\n return arr.at(-1)\n};", "solution_java": "class Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n arr[0] = 1;\n for(int i = 1;i 1)\n arr[i] = arr[i-1] + 1; \n }\n return arr[arr.length-1];\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector& arr) {\n sort(arr.begin(),arr.end());\n int n=arr.size();\n arr[0]=1;\n for(int i=1;i1)\n {\n arr[i]=arr[i-1]+1;\n }\n }\n return arr[n-1];\n }\n};" }, { "title": "Permutations", "algo_input": "Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.\n\n \nExample 1:\nInput: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\nExample 2:\nInput: nums = [0,1]\nOutput: [[0,1],[1,0]]\nExample 3:\nInput: nums = [1]\nOutput: [[1]]\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 6\n\t-10 <= nums[i] <= 10\n\tAll the integers of nums are unique.\n\n", "solution_py": "class Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n return list(permutations(nums))", "solution_js": "var permute = function(nums) {\n const output = [];\n \n const backtracking = (current, remaining) => {\n if (!remaining.length) return output.push(current);\n\n for (let i = 0; i < remaining.length; i++) {\n const newCurrent = [...current];\n const newRemaining = [...remaining];\n\n newCurrent.push(newRemaining[i]);\n newRemaining.splice(i, 1);\n\n backtracking(newCurrent, newRemaining);\n }\n }\n \n backtracking([], nums);\n\n return output;\n};", "solution_java": "class Solution {\n List> res = new LinkedList<>();\n\n public List> permute(int[] nums) {\n ArrayList list = new ArrayList<>();\n boolean[] visited = new boolean[nums.length];\n\n backTrack(nums, list, visited);\n return res;\n }\n\n private void backTrack(int[] nums, ArrayList list, boolean[] visited){\n if(list.size() == nums.length){\n res.add(new ArrayList(list));\n return;\n }\n for(int i = 0; i < nums.length; i++){\n if(!visited[i]){\n visited[i] = true;\n list.add(nums[i]);\n backTrack(nums, list, visited);\n visited[i] = false;\n list.remove(list.size() - 1);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void per(int ind, int n, vector&nums, vector> &ans)\n {\n if(ind==n)\n {\n ans.push_back(nums);\n return;\n }\n for(int i=ind;i> permute(vector& nums) {\n vector> ans;\n int n=nums.size();\n per(0,n,nums,ans);\n return ans;\n }\n};" }, { "title": "H-Index II", "algo_input": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in an ascending order, return compute the researcher's h-index.\n\nAccording to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.\n\nIf there are several possible values for h, the maximum one is taken as the h-index.\n\nYou must write an algorithm that runs in logarithmic time.\n\n \nExample 1:\n\nInput: citations = [0,1,3,5,6]\nOutput: 3\nExplanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\nExample 2:\n\nInput: citations = [1,2,100]\nOutput: 2\n\n\n \nConstraints:\n\n\n\tn == citations.length\n\t1 <= n <= 105\n\t0 <= citations[i] <= 1000\n\tcitations is sorted in ascending order.\n\n", "solution_py": "import bisect\n\nclass Solution:\n def hIndex(self, citations: List[int]) -> int:\n n = len(citations)\n for h in range(n, -1, -1):\n if h <= n - bisect.bisect_left(citations, h):\n return h", "solution_js": "/**\n * The binary search solution.\n * \n * Time Complexity: O(log(n))\n * Space Complexity: O(1)\n * \n * @param {number[]} citations\n * @return {number}\n */\nvar hIndex = function(citations) {\n\tconst n = citations.length\n\n\tlet l = 0\n\tlet r = n - 1\n\n\twhile (l <= r) {\n\t\tconst m = Math.floor((l + r) / 2)\n\n\t\tif (citations[m] > n - m) {\n\t\t\tr = m - 1\n\t\t\tcontinue\n\t\t}\n\n\t\tif (citations[m] < n - m) {\n\t\t\tl = m + 1\n\t\t\tcontinue\n\t\t}\n\n\t\treturn citations[m]\n\t}\n\n\treturn n - l\n}", "solution_java": "class Solution {\n public int hIndex(int[] citations) {\n int n=citations.length;\n int res=0;\n for(int i=0;i=n-i)\n {\n return n-i;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int hIndex(vector& citations) {\n int start = 0 , end = citations.size()-1;\n int n = citations.size();\n while(start <= end){\n int mid = start + (end - start) / 2;\n int val = citations[mid];\n if(val == (n - mid)) return citations[mid];\n else if(val < n - mid){\n start = mid + 1;\n }\n else{\n end = mid - 1;\n }\n }\n return n - start;\n }\n};" }, { "title": "Clone Graph", "algo_input": "Given a reference of a node in a connected undirected graph.\n\nReturn a deep copy (clone) of the graph.\n\nEach node in the graph contains a value (int) and a list (List[Node]) of its neighbors.\n\nclass Node {\n public int val;\n public List<Node> neighbors;\n}\n\n\n \n\nTest case format:\n\nFor simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.\n\nAn adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.\n\nThe given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.\n\n \nExample 1:\n\nInput: adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput: [[2,4],[1,3],[2,4],[1,3]]\nExplanation: There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n\n\nExample 2:\n\nInput: adjList = [[]]\nOutput: [[]]\nExplanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\n\n\nExample 3:\n\nInput: adjList = []\nOutput: []\nExplanation: This an empty graph, it does not have any nodes.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the graph is in the range [0, 100].\n\t1 <= Node.val <= 100\n\tNode.val is unique for each node.\n\tThere are no repeated edges and no self-loops in the graph.\n\tThe Graph is connected and all nodes can be visited starting from the given node.\n\n", "solution_py": " def cloneGraph(self, node: 'Node') -> 'Node':\n \n if node == None:\n return None\n \n new_node = Node(node.val, [])\n \n visited = set()\n \n q = [[node, new_node]]\n visited.add(node.val)\n \n adj_map = {}\n \n adj_map[node] = new_node\n \n while len(q) != 0:\n \n curr = q.pop(0)\n \n \n for n in curr[0].neighbors:\n \n # if n.val not in visited:\n if n not in adj_map and n is not None:\n new = Node(n.val, [])\n curr[1].neighbors.append(new)\n adj_map[n] = new\n else:\n curr[1].neighbors.append(adj_map[n])\n \n if n.val not in visited:\n q.append([n, adj_map[n]])\n visited.add(n.val) \n \n \n return new_node", "solution_js": "var cloneGraph = function(node) {\n if(!node)\n return node;\n \n let queue = [node];\n \n let map = new Map();\n \n\t//1. Create new Copy of each node and save in Map\n while(queue.length) {\n let nextQueue = [];\n \n for(let i = 0; i < queue.length; i++) {\n let n = queue[i];\n \n let newN = new Node(n.val);\n \n if(!map.has(n)) {\n map.set(n, newN);\n }\n \n let nei = n.neighbors;\n \n for(let j = 0; j < nei.length; j++) {\n if(map.has(nei[j]))\n continue;\n nextQueue.push(nei[j]); \n }\n }\n \n queue = nextQueue;\n }\n \n queue = [node];\n \n let seen = new Set();\n seen.add(node);\n \n\t//2. Run BFS again and populate neighbors in new node created in step 1.\n while(queue.length) {\n let nextQueue = [];\n \n for(let i = 0; i < queue.length; i++) {\n let n = queue[i];\n \n let nei = n.neighbors;\n let newn = map.get(n);\n \n for(let j = 0; j < nei.length; j++) {\n newn.neighbors.push(map.get(nei[j]));\n \n if(!seen.has(nei[j])) {\n nextQueue.push(nei[j]); \n seen.add(nei[j]);\n }\n }\n }\n \n queue = nextQueue;\n }\n \n return map.get(node);\n};", "solution_java": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public void dfs(Node node , Node copy , Node[] visited){\n visited[copy.val] = copy;// store the current node at it's val index which will tell us that this node is now visited\n \n// now traverse for the adjacent nodes of root node\n for(Node n : node.neighbors){\n// check whether that node is visited or not\n// if it is not visited, there must be null\n if(visited[n.val] == null){\n// so now if it not visited, create a new node\n Node newNode = new Node(n.val);\n// add this node as the neighbor of the prev copied node\n copy.neighbors.add(newNode);\n// make dfs call for this unvisited node to discover whether it's adjacent nodes are explored or not\n dfs(n , newNode , visited);\n }else{\n// if that node is already visited, retrieve that node from visited array and add it as the adjacent node of prev copied node\n// THIS IS THE POINT WHY WE USED NODE[] INSTEAD OF BOOLEAN[] ARRAY\n copy.neighbors.add(visited[n.val]);\n }\n }\n \n }\n public Node cloneGraph(Node node) {\n if(node == null) return null; // if the actual node is empty there is nothing to copy, so return null\n Node copy = new Node(node.val); // create a new node , with same value as the root node(given node)\n Node[] visited = new Node[101]; // in this question we will create an array of Node(not boolean) why ? , because i have to add all the adjacent nodes of particular vertex, whether it's visited or not, so in the Node[] initially null is stored, if that node is visited, we will store the respective node at the index, and can retrieve that easily.\n Arrays.fill(visited , null); // initially store null at all places\n dfs(node , copy , visited); // make a dfs call for traversing all the vertices of the root node\n return copy; // in the end return the copy node\n }\n}", "solution_c": " 'IF YOU LIKE IT THEN PLS UpVote😎😎😎'\nclass Solution {\n public:\n Node* dfs(Node* cur,unordered_map& mp)\n {\n vector neighbour;\n Node* clone=new Node(cur->val);\n mp[cur]=clone;\n for(auto it:cur->neighbors)\n {\n if(mp.find(it)!=mp.end()) //already clone and stored in map\n {\n neighbour.push_back(mp[it]); //directly push back the clone node from map to neigh\n }\n else\n neighbour.push_back(dfs(it,mp));\n }\n clone->neighbors=neighbour;\n return clone;\n }\n Node* cloneGraph(Node* node) {\n unordered_map mp;\n if(node==NULL)\n return NULL;\n if(node->neighbors.size()==0) //if only one node present no neighbors\n {\n Node* clone= new Node(node->val);\n return clone; \n }\n return dfs(node,mp);\n }\n};" }, { "title": "Find K Closest Elements", "algo_input": "Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.\n\nAn integer a is closer to x than an integer b if:\n\n\n\t|a - x| < |b - x|, or\n\t|a - x| == |b - x| and a < b\n\n\n \nExample 1:\nInput: arr = [1,2,3,4,5], k = 4, x = 3\nOutput: [1,2,3,4]\nExample 2:\nInput: arr = [1,2,3,4,5], k = 4, x = -1\nOutput: [1,2,3,4]\n\n \nConstraints:\n\n\n\t1 <= k <= arr.length\n\t1 <= arr.length <= 104\n\tarr is sorted in ascending order.\n\t-104 <= arr[i], x <= 104\n\n", "solution_py": "class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n \n def sorted_distance(value, static_input = x):\n return abs(value - static_input)\n \n distances = []\n result = []\n heapq.heapify(distances)\n \n for l,v in enumerate(arr):\n distances.append((l, sorted_distance(value = v)))\n \n for i in heapq.nsmallest(k, distances, key = lambda x: x[1]):\n result.append(arr[i[0]])\n \n result.sort()\n return result\n \n ", "solution_js": "var findClosestElements = function(arr, k, x) {\n\tconst result = [...arr];\n\n\twhile (result.length > k) {\n\t\tconst start = result[0];\n\t\tconst end = result.at(-1);\n\n\t\tx - start <= end - x \n\t\t\t? result.pop() \n\t\t\t: result.shift();\n\t}\n\treturn result;\n};", "solution_java": "class Solution {\npublic List findClosestElements(int[] arr, int k, int x) {\n List result = new ArrayList<>();\n\n int low = 0, high = arr.length -1;\n\n while(high - low >= k){\n if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x))\n low++;\n else\n high--;\n }\n\n for(int i = low; i <= high; i++)\n result.add(arr[i]);\n\n return result;\n}\n}", "solution_c": "class Solution {\npublic:\n static bool cmp(pair&p1,pair&p2)\n {\n if(p1.first==p2.first) //both having equal abs diff\n {\n return p1.second findClosestElements(vector& arr, int k, int x) {\n \n vector>v; //abs diff , ele\n \n for(int i=0;ians;\n for(int i=0;i int:\n \"\"\"\n\n \"\"\"\n\n houses.sort()\n heaters.sort()\n\n max_radius = -inf\n\n for house in houses:\n i = bisect_left(heaters, house)\n\n if i == len(heaters):\n max_radius = max(max_radius, house - heaters[-1])\n elif i == 0:\n max_radius = max(max_radius, heaters[i] - house)\n else:\n curr = heaters[i]\n prev = heaters[i-1]\n max_radius = max(max_radius,min(abs(house - curr), abs(house-prev)))\n\n return max_radius\n\n # O(NLOGN)", "solution_js": "var findRadius = function(houses, heaters) {\n\thouses.sort((a, b) => a - b);\n\theaters.sort((a, b) => a - b);\n\tlet heaterPos = 0;\n\tconst getRadius = (house, pos) => Math.abs(heaters[pos] - house);\n\n\treturn houses.reduce((radius, house) => {\n\t\twhile (\n\t\t\theaterPos < heaters.length &&\n\t\t\tgetRadius(house, heaterPos) >= \n\t\t\tgetRadius(house, heaterPos + 1)\n\t\t) heaterPos += 1;\n\n\t\tconst currentRadius = getRadius(house, heaterPos);\n\t\treturn Math.max(radius, currentRadius);\n\t}, 0);\n};", "solution_java": "class Solution {\n public boolean can(int r, int[] houses, int[] heaters) {\n int prevHouseIdx = -1;\n for(int i = 0; i < heaters.length; i++) {\n int from = heaters[i]-r;\n int to = heaters[i]+r;\n for(int j = prevHouseIdx+1; j < houses.length; j++){\n if(houses[j]<=to && houses[j]>=from){\n prevHouseIdx++;\n }\n else break;\n }\n if(prevHouseIdx >= houses.length-1)return true;\n }\n return prevHouseIdx>= houses.length-1;\n }\n public int findRadius(int[] houses, int[] heaters) {\n Arrays.sort(houses);\n Arrays.sort(heaters);\n int lo = 0, hi = 1000000004;\n int mid, ans = hi;\n while(lo <= hi) {\n mid = (lo+hi)/2;\n if(can(mid, houses, heaters)){\n ans = mid;\n hi = mid - 1;\n } else lo = mid + 1;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n //we will assign each house to its closest heater in position(by taking the minimum\n //of the distance between the two closest heaters to the house) and then store the maximum\n //of these differences(since we want to have the same standard radius)\n int findRadius(vector& houses, vector& heaters) {\n sort(heaters.begin(),heaters.end());\n int radius=0;\n for(int house:houses){\n //finding the smallest heater whose position is not greater than\n //the current house\n int index=lower_bound(heaters.begin(),heaters.end(),house)-heaters.begin();\n if(index==heaters.size()){\n index--;\n }\n //the two closest positions to house will be heaters[index] and\n //heaters[index-1]\n int leftDiff=(index-1>=0)?abs(house-heaters[index-1]):INT_MAX;\n int rightDiff=abs(house-heaters[index]);\n radius=max(radius,min(leftDiff,rightDiff));\n }\n return radius;\n }\n};" }, { "title": "Minimum Length of String After Deleting Similar Ends", "algo_input": "Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:\n\n\n\tPick a non-empty prefix from the string s where all the characters in the prefix are equal.\n\tPick a non-empty suffix from the string s where all the characters in this suffix are equal.\n\tThe prefix and the suffix should not intersect at any index.\n\tThe characters from the prefix and suffix must be the same.\n\tDelete both the prefix and the suffix.\n\n\nReturn the minimum length of s after performing the above operation any number of times (possibly zero times).\n\n \nExample 1:\n\nInput: s = \"ca\"\nOutput: 2\nExplanation: You can't remove any characters, so the string stays as is.\n\n\nExample 2:\n\nInput: s = \"cabaabac\"\nOutput: 0\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".\n\nExample 3:\n\nInput: s = \"aabccabba\"\nOutput: 3\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts only consists of characters 'a', 'b', and 'c'.\n\n", "solution_py": "class Solution:\n def minimumLength(self, s: str) -> int:\n while(len(s)>1 and s[0]==s[-1]):\n s=s.strip(s[0])\n else:\n return len(s)", "solution_js": "var minimumLength = function(s) {\n const n = s.length;\n\n let left = 0;\n let right = n - 1;\n\n while (left < right) {\n if (s.charAt(left) != s.charAt(right)) break;\n\n left++;\n right--;\n\n while (left <= right && s.charAt(left - 1) == s.charAt(left)) left++;\n while (left <= right && s.charAt(right) == s.charAt(right + 1)) right--;\n }\n\n return right - left + 1;\n};", "solution_java": "class Solution {\n public int minimumLength(String s) {\n int length = s.length();\n char[] chars = s.toCharArray();\n for(int left = 0,right = chars.length-1;left < right;){\n if(chars[left] == chars[right]){\n char c = chars[left];\n while(left < right && chars[left] == c ){\n left++;\n length--;\n\n }\n\n while (right >= left && chars[right] == c){\n right--;\n length--;\n\n }\n }else {\n break;\n }\n }\n return length;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumLength(string s) {\n int i=0,j=s.length()-1;\n while(ij)\n {\n return 0;\n }\n while(s[j]==x)\n {\n j--;\n }\n if(j List[int]:\n q,p=divmod(n,2)\n if p:\n return list(range(-q, q+1))\n else:\n return list(range(-q,0))+list(range(1,q+1))", "solution_js": "var sumZero = function(n) {\n var num = Math.floor(n/2); \n var res = [];\n\n for(var i=1;i<=num;i++){\n res.push(i,-i)\n } \n\n if(n%2!==0){\n res.push(0)\n }\n \n return res \n}", "solution_java": "class Solution {\n public int[] sumZero(int n) {\n int[] ans = new int[n];\n int j=0;\n \n for(int i=1;i<=n/2;i++)\n {\n ans[j] = i;\n j++;\n }\n for(int i=1;i<=n/2;i++)\n {\n ans[j] = -i;\n j++;\n }\n if(n%2!=0) ans[j] = 0;\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector sumZero(int n) {\n if(n == 1){\n return {0};\n }else{\n vector res;\n for(int i=n/2*-1;i<=n/2;i++){\n if(i == 0){\n if(n%2 == 0){\n continue;\n }else{\n res.push_back(i);\n continue;\n } \n }\n res.push_back(i);\n }\n return res; \n }\n }\n};" }, { "title": "Minimize Hamming Distance After Swap Operations", "algo_input": "You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.\n\nThe Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed).\n\nReturn the minimum Hamming distance of source and target after performing any amount of swap operations on array source.\n\n \nExample 1:\n\nInput: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput: 1\nExplanation: source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.\n\n\nExample 2:\n\nInput: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput: 2\nExplanation: There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.\n\n\nExample 3:\n\nInput: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tn == source.length == target.length\n\t1 <= n <= 105\n\t1 <= source[i], target[i] <= 105\n\t0 <= allowedSwaps.length <= 105\n\tallowedSwaps[i].length == 2\n\t0 <= ai, bi <= n - 1\n\tai != bi\n\n", "solution_py": "class UnionFind:\n def __init__(self, n):\n self.roots = [i for i in range(n)]\n\n def find(self, v):\n if self.roots[v] != v:\n self.roots[v] = self.find(self.roots[v])\n\n return self.roots[v]\n\n def union(self, u, v):\n self.roots[self.find(u)] = self.find(v)\n\nclass Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n uf = UnionFind(len(source))\n for idx1, idx2 in allowedSwaps:\n uf.union(idx1, idx2)\n\n m = collections.defaultdict(set)\n for i in range(len(source)):\n m[uf.find(i)].add(i)\n\n res = 0\n for indices in m.values():\n freq = {}\n for i in indices:\n freq[source[i]] = freq.get(source[i], 0)+1\n freq[target[i]] = freq.get(target[i], 0)-1\n res += sum(val for val in freq.values() if val > 0)\n\n return res", "solution_js": "var minimumHammingDistance = function(source, target, allowedSwaps) {\n const n = source.length;\n \n const uf = {};\n const sizes = {};\n const members = {};\n \n // initial setup\n for (let i = 0; i < n; i++) {\n const srcNum = source[i];\n \n uf[i] = i;\n sizes[i] = 1;\n members[i] = new Map();\n members[i].set(srcNum, 1);\n }\n \n function find(x) {\n if (uf[x] != x) uf[x] = find(uf[x]);\n return uf[x];\n }\n \n function union(x, y) {\n const rootX = find(x);\n const rootY = find(y);\n \n if (rootX === rootY) return;\n \n if (sizes[rootX] > sizes[rootY]) {\n uf[rootY] = rootX;\n sizes[rootX] += sizes[rootY];\n \n for (const [num, count] of members[rootY]) {\n if (!members[rootX].has(num)) members[rootX].set(num, 0);\n members[rootX].set(num, members[rootX].get(num) + count);\n }\n }\n else {\n uf[rootX] = rootY;\n sizes[rootY] += sizes[rootX];\n\n const num = source[x];\n\n for (const [num, count] of members[rootX]) {\n if (!members[rootY].has(num)) members[rootY].set(num, 0);\n members[rootY].set(num, members[rootY].get(num) + count);\n }\n }\n }\n \n for (const [idx1, idx2] of allowedSwaps) {\n union(idx1, idx2);\n }\n \n let mismatches = 0;\n \n for (let i = 0; i < n; i++) {\n const srcNum = source[i];\n const tarNum = target[i];\n \n const group = find(i);\n \n if (members[group].has(tarNum)) {\n members[group].set(tarNum, members[group].get(tarNum) - 1);\n if (members[group].get(tarNum) === 0) members[group].delete(tarNum);\n } \n else {\n mismatches++;\n }\n }\n \n return mismatches;\n};", "solution_java": "class Solution {\n public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) {\n int minHamming = 0;\n UnionFind uf = new UnionFind(source.length);\n for (int [] swap : allowedSwaps) {\n int firstIndex = swap[0];\n int secondIndex = swap[1];\n // int firstParent = uf.find(firstIndex);\n // int secondParent = uf.find(secondIndex);\n // if (firstParent != secondParent)\n // uf.parent[firstParent] = secondParent;\n\t\t uf.union(firstIndex, secondIndex);\n }\n Map> map = new HashMap<>();\n for (int i=0; i());\n Map store = map.get(root);\n store.put(num, store.getOrDefault(num, 0) + 1);\n }\n for (int i=0; i store = map.get(root);\n if (store.getOrDefault(num, 0) == 0)\n minHamming += 1;\n else\n store.put(num, store.get(num) - 1);\n }\n return minHamming;\n }\n}\n\nclass UnionFind {\n int size;\n int components;\n int [] parent;\n int [] rank;\n UnionFind(int n) {\n if (n <= 0) throw new IllegalArgumentException(\"Size <= 0 is not allowed\");\n size = n;\n components = n;\n parent = new int [n];\n rank = new int [n];\n for (int i=0; i rank[rootP]) {\n parent[rootP] = rootQ;\n }\n else {\n parent[rootQ] = rootP;\n if (rank[rootQ] == rank[rootP])\n rank[rootP] += 1;\n }\n components -= 1;\n }\n \n public int size() {\n return size;\n }\n \n public boolean isConnected(int p, int q) {\n return find(p) == find(q);\n }\n \n public int numberComponents() {\n return components;\n }\n}", "solution_c": "class Solution {\npublic:\n vector parents;\n vector ranks;\n int find(int a) {\n if (a == parents[a])\n return parents[a];\n return parents[a] = find(parents[a]);\n }\n\n void uni(int a, int b) {\n a = find(a);\n b = find(b);\n\n if (ranks[a] >= ranks[b]) {\n parents[b] = a;\n ranks[a]++;\n }\n else {\n parents[a] = b;\n ranks[b]++;\n }\n }\n\n int minimumHammingDistance(vector& source, vector& target, vector>& allowedSwaps) {\n int n = source.size();\n ranks = vector(n, 0);\n\n for (int i = 0; i < n; i++) {\n parents.push_back(i);\n }\n\n for (auto &v : allowedSwaps)\n uni(v[0], v[1]);\n vector> subs(n);\n\n for (int i = 0; i < n; i++) {\n subs[find(i)].insert(source[i]);\n }\n int cnt = 0;\n for (int i = 0; i < n; i++) {\n if (!subs[parents[i]].count(target[i]))\n cnt++;\n else\n subs[parents[i]].erase(subs[parents[i]].find(target[i]));\n }\n return cnt;\n }\n};" }, { "title": "Valid Triangle Number", "algo_input": "Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.\n\n \nExample 1:\n\nInput: nums = [2,2,3,4]\nOutput: 3\nExplanation: Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3\n\n\nExample 2:\n\nInput: nums = [4,2,3,4]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t0 <= nums[i] <= 1000\n\n", "solution_py": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}", "solution_js": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}", "solution_java": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\n public int triangleNumber(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int count =0;\n for(int k = n-1; k>=2; k--)\n {\n int i = 0;\n int j = k-1;\n while(i < j)\n {\n int sum = nums[i] +nums[j];\n if(sum > nums[k])\n {\n count += j-i;\n j--;\n }\n else\n {\n i++;\n }\n }\n }\n return count;\n }\n}" }, { "title": "Design Authentication Manager", "algo_input": "There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.\n\nImplement the AuthenticationManager class:\n\n\n\tAuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.\n\tgenerate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.\n\trenew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.\n\tcountUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.\n\n\nNote that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.\n\n \nExample 1:\n\nInput\n[\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n[[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]\nOutput\n[null, null, null, 1, null, null, null, 0]\n\nExplanation\nAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.\nauthenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\nauthenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\nauthenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\nauthenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.\nauthenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.\n\n\n \nConstraints:\n\n\n\t1 <= timeToLive <= 108\n\t1 <= currentTime <= 108\n\t1 <= tokenId.length <= 5\n\ttokenId consists only of lowercase letters.\n\tAll calls to generate will contain unique values of tokenId.\n\tThe values of currentTime across all the function calls will be strictly increasing.\n\tAt most 2000 calls will be made to all functions combined.\n\n", "solution_py": "class AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive and create dictionary\n\n def generate(self, tokenId, currentTime):\n self.token[tokenId] = currentTime # store tokenId with currentTime\n\n def renew(self, tokenId, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n self.token[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n c = 0\n for i in self.token:\n if self.token[i]>limit: # count unexpired tokens\n c+=1\n return c", "solution_js": "// O(n)\nvar AuthenticationManager = function(timeToLive) {\n this.ttl = timeToLive;\n this.map = {};\n};\nAuthenticationManager.prototype.generate = function(tokenId, currentTime) {\n this.map[tokenId] = currentTime + this.ttl;\n};\nAuthenticationManager.prototype.renew = function(tokenId, currentTime) {\n let curr = this.map[tokenId];\n if (curr > currentTime) {\n this.generate(tokenId, currentTime);\n }\n};\nAuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {\n return Object.keys(this.map).filter(key => this.map[key] > currentTime).length;\n};", "solution_java": "class AuthenticationManager {\n private int ttl;\n private Map map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n this.map = new HashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + this.ttl);\n }\n \n public void renew(String tokenId, int currentTime) {\n Integer expirationTime = this.map.getOrDefault(tokenId, null);\n if (expirationTime == null || expirationTime <= currentTime)\n return;\n \n generate(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (Map.Entry entry: this.map.entrySet())\n if (entry.getValue() > currentTime)\n count++;\n \n return count;\n }\n}", "solution_c": "class AuthenticationManager {\n int ttl;\n unordered_map tokens;\npublic:\n AuthenticationManager(int timeToLive) {\n ttl = timeToLive;\n }\n\n void generate(string tokenId, int currentTime) {\n tokens[tokenId] = currentTime + ttl;\n }\n\n void renew(string tokenId, int currentTime) {\n auto tokenIt = tokens.find(tokenId);\n if (tokenIt != end(tokens) && tokenIt->second > currentTime) {\n tokenIt->second = currentTime + ttl;\n }\n }\n\n int countUnexpiredTokens(int currentTime) {\n int res = 0;\n for (auto token: tokens) {\n if (token.second > currentTime) res++;\n }\n return res;\n }\n};" }, { "title": "Minimum Operations to Make the Array Alternating", "algo_input": "You are given a 0-indexed array nums consisting of n positive integers.\n\nThe array nums is called alternating if:\n\n\n\tnums[i - 2] == nums[i], where 2 <= i <= n - 1.\n\tnums[i - 1] != nums[i], where 1 <= i <= n - 1.\n\n\nIn one operation, you can choose an index i and change nums[i] into any positive integer.\n\nReturn the minimum number of operations required to make the array alternating.\n\n \nExample 1:\n\nInput: nums = [3,1,3,2,4,3]\nOutput: 3\nExplanation:\nOne way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations. \n\n\nExample 2:\n\nInput: nums = [1,2,2,2,2]\nOutput: 2\nExplanation:\nOne way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def minimumOperations(self, nums: List[int]) -> int:\n n = len(nums)\n odd, even = defaultdict(int), defaultdict(int)\n for i in range(n):\n if i % 2 == 0:\n even[nums[i]] += 1\n else:\n odd[nums[i]] += 1\n topEven, secondEven = (None, 0), (None, 0)\n for num in even:\n if even[num] > topEven[1]:\n topEven, secondEven = (num, even[num]), topEven\n elif even[num] > secondEven[1]:\n secondEven = (num, even[num])\n topOdd, secondOdd = (None, 0), (None, 0)\n for num in odd:\n if odd[num] > topOdd[1]:\n topOdd, secondOdd = (num, odd[num]), topOdd\n elif odd[num] > secondOdd[1]:\n secondOdd = (num, odd[num])\n if topOdd[0] != topEven[0]:\n return n - topOdd[1] - topEven[1]\n else:\n return n - max(secondOdd[1] + topEven[1], secondEven[1] + topOdd[1])", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\n\nvar minimumOperations = function(nums) {\n let countOddId = {} \n let countEvenId = {}\n if(nums.length === 1) return 0\n if(nums.length === 2 && nums[0] === nums[1]) {\n return 1\n }\n nums.forEach((n, i) => {\n if(i%2) {\n if(!countOddId[n]) {\n countOddId[n] = 1;\n } else {\n countOddId[n]++\n }\n } else {\n if(!countEvenId[n]) {\n countEvenId[n] = 1;\n } else {\n countEvenId[n]++\n }\n }\n })\n \n const sortedEven = Object.entries(countEvenId).sort((a, b) => {\n return b[1] - a[1]\n })\n\n const sortedOdd = Object.entries(countOddId).sort((a, b) => {\n return b[1] - a[1]\n })\n\n if(sortedEven[0][0] === sortedOdd[0][0]) {\n let maxFirst =0;\n let maxSec =0;\n\n if(sortedEven.length === 1) {\n maxFirst = sortedEven[0][1];\n maxSec = sortedOdd[1]? sortedOdd[1][1] : 0;\n return nums.length - (maxFirst + maxSec) \n } \n \n if(sortedOdd.length === 1) {\n maxFirst = sortedOdd[0][1];\n maxSec = sortedEven[1] ? sortedEven[1][1] : 0;\n return nums.length - (maxFirst + maxSec) \n }\n if(sortedEven[0][1] >= sortedOdd[0][1] && sortedEven[1][1] <= sortedOdd[1][1]) {\n maxFirst = sortedEven[0][1]\n maxSec = sortedOdd[1][1]\n return nums.length - (maxFirst + maxSec) \n } else {\n maxFirst = sortedOdd[0][1]\n maxSec = sortedEven[1][1]\n return nums.length - (maxFirst + maxSec) \n }\n } else {\n return nums.length - (sortedEven[0][1] + sortedOdd[0][1])\n }\n\n};", "solution_java": "class Solution {\n public int minimumOperations(int[] nums) {\n int freq[][] = new int[100005][2];\n int i, j, k, ans=0;\n for(i = 0; i < nums.length; i++) {\n \t\t\tfreq[nums[i]][i&1]++;\n \t\t}\n \t\t\n \t\tfor(i = 1, j=k=0; i <= 100000; i++) {\n\t\t\t// Add the maximum frequency of odd indexes to maximum frequency even indexes \n\t\t //and vice versa, it will give us how many elements we don't need to change. \n \t\tans = Math.max(ans, Math.max(freq[i][0] + k, freq[i][1] + j));\n j = Math.max(j, freq[i][0]);\n k = Math.max(k, freq[i][1]);\n }\n return nums.length - ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumOperations(vector& nums) {\n\n int totalEven = 0, totalOdd = 0;\n\n unordered_map mapEven, mapOdd;\n\n for(int i=0;ifirst;\n int count = it->second;\n\n if(count>=firstEvenCount) {\n secondEvenCount = firstEvenCount;\n secondEven = firstEven;\n firstEvenCount = count;\n firstEven = num;\n }\n\n else if(count >= secondEvenCount) {\n secondEvenCount = count;\n secondEven = num;\n }\n }\n\n int firstOddCount = 0, firstOdd = 0;\n int secondOddCount = 0, secondOdd = 0;\n\n for(auto it=mapOdd.begin();it!=mapOdd.end();it++) {\n int num = it->first;\n int count = it->second;\n\n if(count>=firstOddCount) {\n secondOddCount = firstOddCount;\n secondOdd = firstOdd;\n firstOddCount = count;\n firstOdd = num;\n }\n\n else if(count>=secondOddCount) {\n secondOddCount = count;\n secondOdd = num;\n }\n }\n\n int operationsEven = 0, operationsOdd = 0;\n\n operationsEven = totalEven - firstEvenCount;\n\n if(firstEven!=firstOdd) operationsEven += (totalOdd - firstOddCount);\n else operationsEven += (totalOdd - secondOddCount);\n\n operationsOdd = totalOdd - firstOddCount;\n if(firstOdd!=firstEven) operationsOdd += (totalEven - firstEvenCount);\n else operationsOdd += (totalEven - secondEvenCount);\n\n return min(operationsEven, operationsOdd);\n\n }\n};" }, { "title": "Valid Mountain Array", "algo_input": "Given an array of integers arr, return true if and only if it is a valid mountain array.\n\nRecall that arr is a mountain array if and only if:\n\n\n\tarr.length >= 3\n\tThere exists some i with 0 < i < arr.length - 1 such that:\n\t\n\t\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i] \n\t\tarr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n\t\n\t\n\n\n \nExample 1:\nInput: arr = [2,1]\nOutput: false\nExample 2:\nInput: arr = [3,5,5]\nOutput: false\nExample 3:\nInput: arr = [0,3,2,1]\nOutput: true\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 104\n\t0 <= arr[i] <= 104\n\n", "solution_py": "class Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr) < 3:\n return False\n for i in range(1,len(arr)):\n if arr[i] <= arr[i-1]:\n if i==1:\n return False\n break\n\n for j in range(i,len(arr)):\n if arr[j] >= arr[j-1]:\n return False\n return True", "solution_js": "var validMountainArray = function(arr) {\n let index = 0, length = arr.length;\n //find the peak\n while(index < length && arr[index] < arr[index + 1])index++\n //edge cases\n if(index === 0 || index === length - 1) return false;\n //check if starting from peak to end of arr is descending order\n \n while(index < length && arr[index] > arr[index + 1])index++\n \n return index === length - 1;\n};", "solution_java": "class Solution {\n public boolean validMountainArray(int[] arr) {\n // edge case\n if(arr.length < 3) return false;\n // keep 2 pointers\n int i=0;\n int j=arr.length-1;\n // use i pointer to iterate through steep increase from LHS\n while(ii && arr[j]0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool validMountainArray(vector& arr) {\n int flag = 1;\n if((arr.size()<=2) || (arr[1] <= arr[0])) return false;\n for(int i=1; i arr[i-1]) continue;\n i--;\n flag = 0;\n }\n else{\n if(arr[i] < arr[i-1]) continue;\n return false;\n }\n }\n\n if(flag) return false;\n return true;\n \n }\n};****" }, { "title": "Binary Tree Cameras", "algo_input": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.\n\nReturn the minimum number of cameras needed to monitor all nodes of the tree.\n\n \nExample 1:\n\nInput: root = [0,0,null,0,0]\nOutput: 1\nExplanation: One camera is enough to monitor all nodes if placed as shown.\n\n\nExample 2:\n\nInput: root = [0,0,null,0,null,0,null,null,0]\nOutput: 2\nExplanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\tNode.val == 0\n\n", "solution_py": "import itertools\n# 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 minCameraHelper(self, root: Optional[TreeNode]) -> (int, int):\n # Return 3 things:\n # cam, uncam, uncov\n # cam(era) is best score for valid tree with camera at root\n # uncam(era) is best score for valid tree without camera at root\n # uncov(ered) is best score for invalid tree, where the only invalidity (i.e. the only uncovered node) is the root node\n \n # Note: maxint (float(\"inf\")) is used to signify situations that don't make sense or can't happen.\n # Anywhere there is a float(\"inf\"), you can safely replace that with a 1 as 1 is as bad or worse than worst practical,\n # but I stick with maxint to highlight the nonsensical cases for the reader!\n \n if not root.left and not root.right:\n # base case: leaf\n # Note: \"Uncam\" setting doesn't make much sense (a leaf with no parents can either have a camera or be uncovered,\n # but not covered with no camera)\n return 1, float(\"inf\"), 0\n \n if root.left:\n left_cam, left_uncam, left_uncov = self.minCameraHelper(root.left)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n left_cam, left_uncam, left_uncov = float(\"inf\"), 0, 0\n \n if root.right:\n right_cam, right_uncam, right_uncov = self.minCameraHelper(root.right)\n else:\n # base case: empty child\n # Need to prevent null nodes from providing coverage to parent, so set that cost to inf\n right_cam, right_uncam, right_uncov = float(\"inf\"), 0, 0\n \n # Get the possible combinations for each setting \n cam_poss = itertools.product([left_cam, left_uncam, left_uncov], [right_cam, right_uncam, right_uncov])\n uncam_poss = [(left_cam, right_cam), (left_uncam, right_cam), (left_cam, right_uncam)]\n uncov_poss = [(left_uncam, right_uncam)]\n \n # Compute costs for each setting\n cam = min([x + y for x, y in cam_poss]) + 1\n uncam = min([x + y for x, y in uncam_poss])\n uncov = min([x + y for x, y in uncov_poss])\n \n return cam, uncam, uncov\n \n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n cam, uncam, _ = self.minCameraHelper(root)\n return min(cam, uncam)", "solution_js": "var minCameraCover = function(root) {\n let cam = 0;\n // 0 --> No covered\n // 1 --> covered by camera\n // 2 --> has camera\n function dfs(root) {\n if(root === null) return 1;\n\n const left = dfs(root.left);\n const right = dfs(root.right);\n\n if(left === 0 || right === 0) { // child required a camera to covered\n cam++;\n return 2;\n } else if(left === 2 || right === 2) { // child has camera so i am covered\n return 1;\n } else { // child is covered but don't have camera,So i want camera\n return 0;\n }\n }\n\n const ans = dfs(root);\n\n if(ans === 0) ++cam;\n\n return cam;\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 private int count = 0;\n public int minCameraCover(TreeNode root) {\n if(helper(root) == -1)\n count++;\n return count;\n }\n \n //post order\n //0 - have camera\n //1 - covered\n //-1 - not covered\n public int helper(TreeNode root) {\n if(root == null)\n return 1;\n int left = helper(root.left);\n int right = helper(root.right);\n if(left == -1 || right == -1) {\n count++;\n return 0;\n }\n if(left == 0 || right == 0)\n return 1;\n \n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n map mpr;\n int dp[1009][3];\n int minCameraCover(TreeNode* root)\n {\n int num = 0;\n adres(root, num);\n memset(dp, -1, sizeof(dp));\n\n int t1 = dp_fun(root, 0), t2 = dp_fun(root, 1), t3 = dp_fun(root, 2);\n\n return min({t1, t3});\n\n }\n\n int dp_fun(TreeNode* cur, int st)\n {\n int nd = mpr[cur];\n if(dp[nd][st] == -1)\n {\n if(cur == NULL)\n {\n if(st == 2)\n {\n return 1e8;\n }\n else\n {\n return 0;\n }\n }\n if(st == 2)\n {\n dp[nd][st] = 1 + min({dp_fun(cur->left, 1) + dp_fun(cur->right, 1), dp_fun(cur->left, 1) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 1), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)});\n }\n else if(st == 1)\n {\n dp[nd][st] = min({dp_fun(cur->left, 0) + dp_fun(cur->right, 0), dp_fun(cur->left, 0) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 0), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)});\n }\n else\n {\n dp[nd][st] = min({dp_fun(cur, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 0), dp_fun(cur->left, 0) + dp_fun(cur->right, 2), dp_fun(cur->left, 2) + dp_fun(cur->right, 2)});\n }\n }\n return dp[nd][st];\n }\n\n void adres(TreeNode* cur, int &cnt)\n {\n if(cur == NULL)\n {\n return;\n }\n mpr[cur] = cnt;\n cnt++;\n\n adres(cur->left, cnt);\n adres(cur->right, cnt);\n }\n};" }, { "title": "Check if Word Equals Summation of Two Words", "algo_input": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).\n\nThe numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.\n\n\n\tFor example, if s = \"acb\", we concatenate each letter's letter value, resulting in \"021\". After converting it, we get 21.\n\n\nYou are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.\n\nReturn true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.\n\n \nExample 1:\n\nInput: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput: true\nExplanation:\nThe numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.\n\n\nExample 2:\n\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\nOutput: false\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.\n\n\nExample 3:\n\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\nOutput: true\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.\n\n\n \nConstraints:\n\n\n\t1 <= firstWord.length, secondWord.length, targetWord.length <= 8\n\tfirstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.\n\n", "solution_py": "class Solution:\n def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n x=['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 a=\"\"\n for i in firstWord:\n a=a+str(x.index(i))\n \n b=\"\"\n for i in secondWord:\n b=b+str(x.index(i))\n\n c=\"\"\n for i in targetWord:\n c=c+str(x.index(i))\n if int(a)+int(b)==int(c):\n return True\n return False", "solution_js": "var isSumEqual = function(firstWord, secondWord, targetWord) {\n let obj = {\n 'a' : '0',\n \"b\" : '1',\n \"c\" : '2',\n \"d\" : '3',\n \"e\" : '4',\n 'f' : '5',\n 'g' : '6',\n 'h' : '7',\n 'i' : '8', \n \"j\" : '9'\n }\n let first = \"\", second = \"\", target = \"\"\n for(let char of firstWord){\n first += obj[char]\n }\n for(let char of secondWord){\n second += obj[char]\n }\n for(let char of targetWord){\n target += obj[char]\n }\n return parseInt(first) + parseInt(second) === parseInt(target)\n};", "solution_java": "class Solution {\n public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {\n int sumfirst=0, sumsecond=0, sumtarget=0;\n for(char c : firstWord.toCharArray()){\n sumfirst += c-'a';\n sumfirst *= 10;\n }\n for(char c : secondWord.toCharArray()){\n sumsecond += c-'a';\n sumsecond *= 10;\n }\n for(char c : targetWord.toCharArray()){\n sumtarget += c-'a';\n sumtarget *= 10;\n }\n \n return (sumfirst + sumsecond) == sumtarget;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isSumEqual(string firstWord, string secondWord, string targetWord) {\n int first=0,second=0,target=0;\n for(int i=0;i index);\n }\n find(x) {\n return this.father[x] = this.father[x] === x ? x : this.find(this.father[x]);\n }\n merge(a, b) {\n const fa = this.find(a);\n const fb = this.find(b);\n if (fa === fb) return;\n this.father[fb] = fa;\n }\n equal(a, b) {\n return this.find(a) === this.find(b);\n }\n}\nvar equationsPossible = function(equations) {\n const us = new UnionSet();\n const base = 'a'.charCodeAt();\n // merge, when equal\n for(let i = 0; i < equations.length; i++) {\n const item = equations[i];\n if (item[1] === '!') continue;\n const a = item[0].charCodeAt() - base;\n const b = item[3].charCodeAt() - base;\n us.merge(a, b);\n }\n // check, when different\n for(let i = 0; i < equations.length; i++) {\n const item = equations[i];\n if (item[1] === '=') continue;\n const a = item[0].charCodeAt() - base;\n const b = item[3].charCodeAt() - base;\n if (us.equal(a, b)) return false;\n }\n return true;\n};", "solution_java": "class Solution {\n static int par[];\n\n public static int findPar(int u) {\n return par[u] == u ? u : (par[u] = findPar(par[u]));\n }\n\n public boolean equationsPossible(String[] equations) {\n par = new int[26];\n for (int i = 0; i < 26; i++) {\n par[i] = i;\n }\n\n /*First perform all the merging operation*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '=') {\n if (p1 != p2) {\n if (p1 < p2) {\n par[p2] = p1;\n } else {\n par[p1] = p2;\n }\n }\n } \n }\n\n /*Now traverse on the whole string and search for any != operation and check if there parents are same*/\n for (String s : equations) {\n int c1 = s.charAt(0) - 'a';\n int c2 = s.charAt(3) - 'a';\n char sign = s.charAt(1);\n\n int p1 = findPar(c1);\n int p2 = findPar(c2);\n\n if (sign == '!') {\n if (p1 == p2) {\n return false;\n }\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic: \n bool equationsPossible(vector& equations) {\n \n unordered_map> equalGraph; //O(26*26)\n unordered_map> unEqualGraph; //O(26*26)\n \n //build graph:\n for(auto eq: equations){\n char x = eq[0], y = eq[3];\n if(eq[1] == '='){\n equalGraph[x].insert(y);\n equalGraph[y].insert(x);\n } \n else{\n unEqualGraph[x].insert(y);\n unEqualGraph[y].insert(x);\n }\n }\n \n //for each node in inequality, check if they are reachable from equality:\n for(auto it: unEqualGraph){\n char node = it.first;\n set nbrs = it.second; //all nbrs that should be unequal\n if(nbrs.size() == 0) continue;\n \n unordered_map seen; \n bool temp = dfs(node, seen, equalGraph, nbrs);\n if(temp) return false; //if any nbr found in equality, return false\n }\n \n return true;\n //TC, SC: O(N*N) + O(26*26)\n }\n \n \n bool dfs(char curNode, unordered_map &seen, unordered_map> &equalGraph, set &nbrs){\n \n seen[curNode] = true;\n if(nbrs.find(curNode) != nbrs.end()) return true;\n \n for(auto nextNode: equalGraph[curNode]){\n if(seen.find(nextNode) == seen.end()){\n bool temp = dfs(nextNode, seen, equalGraph, nbrs);\n if(temp) return true;\n }\n }\n \n return false;\n }\n \n};" }, { "title": "Fraction to Recurring Decimal", "algo_input": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\n\nIf the fractional part is repeating, enclose the repeating part in parentheses.\n\nIf multiple answers are possible, return any of them.\n\nIt is guaranteed that the length of the answer string is less than 104 for all the given inputs.\n\n \nExample 1:\n\nInput: numerator = 1, denominator = 2\nOutput: \"0.5\"\n\n\nExample 2:\n\nInput: numerator = 2, denominator = 1\nOutput: \"2\"\n\n\nExample 3:\n\nInput: numerator = 4, denominator = 333\nOutput: \"0.(012)\"\n\n\n \nConstraints:\n\n\n\t-231 <= numerator, denominator <= 231 - 1\n\tdenominator != 0\n\n", "solution_py": "from collections import defaultdict\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n sign = \"\" if numerator*denominator >= 0 else \"-\"\n numerator, denominator = abs(numerator), abs(denominator)\n a = numerator//denominator\n numerator %= denominator\n if not numerator: return sign+str(a)\n fractions = []\n index = defaultdict(int)\n while 10*numerator not in index:\n numerator *= 10\n index[numerator] = len(fractions)\n fractions.append(str(numerator//denominator))\n numerator %= denominator\n i = index[10*numerator]\n return sign+str(a)+\".\"+\"\".join(fractions[:i])+\"(\"+\"\".join(fractions[i:])+\")\" if numerator else sign+str(a)+\".\"+\"\".join(fractions[:i])", "solution_js": "var fractionToDecimal = function(numerator, denominator) {\n if(numerator == 0) return '0'\n let result = ''\n if(numerator*denominator <0){\n result += '-'\n }\n \n let dividend = Math.abs(numerator)\n let divisor = Math.abs(denominator)\n result += Math.floor(dividend/divisor).toString()\n \n let remainder = dividend % divisor\n if(remainder == 0) return result\n \n result += '.'\n \n let map1 = new Map()\n while(remainder != 0){\n if(map1.has(remainder)){\n let i = map1.get(remainder)\n result = result.slice(0, i) + '(' + result.slice(i) + ')'\n break;\n }\n map1.set(remainder, result.length)\n remainder *= 10\n result += Math.floor(remainder/divisor).toString()\n remainder %= divisor\n }\n return result\n};", "solution_java": "class Solution {\n public String fractionToDecimal(int numerator, int denominator) {\n if(numerator == 0){\n return \"0\";\n }\n \n StringBuilder sb = new StringBuilder(\"\");\n if(numerator<0 && denominator>0 || numerator>0 && denominator<0){\n sb.append(\"-\");\n }\n \n long divisor = Math.abs((long)numerator);\n long dividend = Math.abs((long)denominator);\n long remainder = divisor % dividend;\n sb.append(divisor / dividend);\n \n if(remainder == 0){\n return sb.toString();\n }\n sb.append(\".\");\n HashMap map = new HashMap();\n while(remainder!=0){\n if(map.containsKey(remainder)){\n sb.insert(map.get(remainder), \"(\");\n sb.append(\")\");\n break;\n }\n map.put(remainder, sb.length());\n remainder*= 10;\n sb.append(remainder/dividend);\n remainder%= dividend;\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string fractionToDecimal(int numerator, int denominator) {\n unordered_map umap;\n string result = \"\";\n if ((double) numerator / (double) denominator < 0) result.push_back('-');\n long long l_numerator = numerator > 0 ? numerator : -(long long) numerator;\n long long l_denominator = denominator > 0 ? denominator : -(long long) denominator;\n long long quotient = l_numerator / l_denominator;\n long long remainder = l_numerator % l_denominator;\n result.append(to_string(quotient));\n if (remainder == 0) return result;\n result.push_back('.');\n int position = result.size();\n umap[remainder] = position++;\n while (remainder != 0) {\n l_numerator = remainder * 10;\n quotient = l_numerator / l_denominator;\n remainder = l_numerator % l_denominator;\n char digit = '0' + quotient;\n result.push_back(digit);\n if (umap.find(remainder) != umap.end()) {\n result.insert(umap[remainder], 1, '(');\n result.push_back(')');\n return result;\n }\n umap[remainder] = position++;\n }\n return result;\n }\n};" }, { "title": "Factorial Trailing Zeroes", "algo_input": "Given an integer n, return the number of trailing zeroes in n!.\n\nNote that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 0\nExplanation: 3! = 6, no trailing zero.\n\n\nExample 2:\n\nInput: n = 5\nOutput: 1\nExplanation: 5! = 120, one trailing zero.\n\n\nExample 3:\n\nInput: n = 0\nOutput: 0\n\n\n \nConstraints:\n\n\n\t0 <= n <= 104\n\n\n \nFollow up: Could you write a solution that works in logarithmic time complexity?\n", "solution_py": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n res = 0\n for i in range(2, n+1):\n while i > 0 and i%5 == 0:\n i //= 5\n res += 1\n return res", "solution_js": "var trailingZeroes = function(n) {\n let count=0\n while(n>=5){\n count += ~~(n/5)\n n= ~~(n/5)\n }\n return count\n};", "solution_java": "class Solution {\n public int trailingZeroes(int n) {\n int count=0;\n while(n>1) {count+=n/5; n=n/5;}\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int trailingZeroes(int n) {\n int ni=0, mi=0;\n for (int i=1; i<=n; i++){\n int x=i;\n while (x%2==0){\n x= x>>1;\n ni++;\n }\n while (x%5==0){\n x= x/5;\n mi++;\n }\n }\n return min(mi,ni);\n }\n};" }, { "title": "Rotate Function", "algo_input": "You are given an integer array nums of length n.\n\nAssume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:\n\n\n\tF(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].\n\n\nReturn the maximum value of F(0), F(1), ..., F(n-1).\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [4,3,2,6]\nOutput: 26\nExplanation:\nF(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n\n\nExample 2:\n\nInput: nums = [100]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t-100 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def maxRotateFunction(self, nums: List[int]) -> int:\n preSum, cur = 0, 0\n for i in range(len(nums)):\n cur += i * nums[i]\n preSum += nums[i]\n ans = cur\n for i in range(1, len(nums)):\n cur -= len(nums) * nums[len(nums) - i]\n cur += preSum\n ans = max(ans, cur)\n return ans", "solution_js": "var maxRotateFunction = function(nums) { \n let n = nums.length;\n let dp = 0;\n \n let sum = 0; \n for (let i=0; i& A) {\n long sum = 0, fn = 0;\n int len = A.size();\n for(int i=0;i bool:\n left,right,star = deque(), deque(), deque() #indexes of all unmatched left right parens and all '*'\n # O(n) where n=len(s)\n for i,c in enumerate(s):\n if c == '(': # we just append left paren's index\n left.append(i)\n elif c == ')': # we check if we can find a match of left paren\n if left and left[-1] < i:\n left.pop()\n else:\n right.append(i)\n else: #'*' case we just add the postion\n star.append(i)\n if not left and not right: return True\n elif not star: return False #no star to save the string, return False\n l,r = 0 ,len(star)-1\n #O(n) since star will be length less than n\n # Note: left, right,and star are always kept in ascending order! And for any i in left, j in right, i > j, or they would have been matched in the previous for loop.\n while l<=r:\n if left:\n if left[-1]< star[r]: # we keep using right most star to match with right most '('\n left.pop()\n r -= 1\n else: return False # even the right most '*' can not match a '(', we can not fix the string.\n if right:\n if right[0] > star[l]:\n right.popleft()\n l += 1\n else: return False\n if not left and not right: return True #if after some fix, all matched, we return True", "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar checkValidString = function(s) {\n let map = {}\n return check(s,0,0,map);\n};\n\nfunction check(s,index,open,map){\n if(index == s.length){\n return open == 0;\n }\n\n if(open < 0){\n return false;\n }\n let string = index.toString() + \"##\" + open.toString();\n if(string in map){\n return map[string]\n }\n\n if(s[index] == '('){\n let l = check(s,index+1,open+1,map)\n map[string] = l\n return l\n }else if (s[index] == ')'){\n let r = check(s,index+1,open-1,map)\n map[string] = r;\n return r\n }else {\n let lr = check(s,index+1,open+1,map) || check(s,index+1,open-1,map)\n || check(s,index+1,open,map)\n map[string] = lr;\n return lr\n }\n}", "solution_java": "class Solution{\n\tpublic boolean checkValidString(String s){\n\t\tStack stack = new Stack<>();\n\t\tStack star = new Stack<>();\n\t\tfor(int i=0;i> m;\n return dfs(s, 0, 0, m);\n }\n\n // b: balanced number\n bool dfs (string s, int index, int b, unordered_map>& m) {\n if (index == s.length()) {\n if (b == 0 ) return true;\n else return false;\n }\n\n if (m.count(index) && m[index].count(b)) return m[index][b];\n\n if (s[index] == '(') {\n m[index][b] = dfs(s, index+1, b+1, m);\n } else if (s[index] == ')') {\n m[index][b] = (b!= 0 && dfs(s, index+1, b-1, m));\n }else {\n m[index][b] = dfs(s,index+1, b, m) || dfs(s, index+1, b+1, m) ||\n (b != 0 && dfs(s, index+1, b-1, m));\n }\n\n return m[index][b];\n }\n};" }, { "title": "Water Bottles", "algo_input": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.\n\nThe operation of drinking a full water bottle turns it into an empty bottle.\n\nGiven the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.\n\n \nExample 1:\n\nInput: numBottles = 9, numExchange = 3\nOutput: 13\nExplanation: You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.\n\n\nExample 2:\n\nInput: numBottles = 15, numExchange = 4\nOutput: 19\nExplanation: You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.\n\n\n \nConstraints:\n\n\n\t1 <= numBottles <= 100\n\t2 <= numExchange <= 100\n\n", "solution_py": "class Solution:\n def numWaterBottles(self, a: int, b: int) -> int:\n \n def sol(a,b,e,res):\n if a!=0: res += a\n if (a+e) 0) {\n count += numBottles;\n emptyBottles += numBottles;\n numBottles = Math.floor(emptyBottles / numExchange);\n emptyBottles -= numBottles * numExchange;\n }\n \n \n return count;\n};", "solution_java": "class Solution {\n public int numWaterBottles(int numBottles, int numExchange) {\n int drinkedBottles = numBottles;\n int emptyBottles = numBottles;\n\n while(emptyBottles >= numExchange){\n int gainedBottles = emptyBottles / numExchange;\n\n drinkedBottles += gainedBottles;\n\n int unusedEmptyBottles = emptyBottles % numExchange;\n\n emptyBottles = gainedBottles + unusedEmptyBottles;\n }\n return drinkedBottles;\n }\n}", "solution_c": "class Solution {\npublic:\n int numWaterBottles(int numBottles, int numExchange) {\n int ex=0,remain=0,res=numBottles;\n while(numBottles>=numExchange){\n remain=numBottles%numExchange;\n numBottles=numBottles/numExchange;\n res+=numBottles;\n numBottles+=remain;\n cout< str:\n # calculate the last occurence of each characters in s\n last_occurence = {c: i for i, c in enumerate(s)}\n \n stack = []\n # check if element is in stack\n instack = set()\n for i, c in enumerate(s):\n if c not in instack:\n # check if stack already have char larger then current char\n # and if char in stack will occur later again, remove that from stack\n while stack and stack[-1] > c and last_occurence[stack[-1]] > i:\n instack.remove(stack[-1])\n stack.pop()\n \n instack.add(c) \n stack.append(c)\n \n return \"\".join(stack)", "solution_js": "var smallestSubsequence = function(s) {\n let stack = [];\n for(let i = 0; i < s.length; i++){\n if(stack.includes(s[i])) continue;\n while(stack[stack.length-1]>s[i] && s.substring(i).includes(stack[stack.length-1])) stack.pop();\n stack.push(s[i]);\n }\n return stack.join(\"\");\n};", "solution_java": "class Solution {\n public String smallestSubsequence(String s) {\n boolean[] inStack = new boolean [26];\n int[] lastIdx = new int [26];\n Arrays.fill(lastIdx,-1);\n for(int i = 0; i < s.length(); i++){\n lastIdx[s.charAt(i)-'a'] = i;\n }\n Deque dq = new ArrayDeque<>();\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(inStack[ch-'a']){\n continue;\n }\n while(!dq.isEmpty() && dq.peekLast() > ch && lastIdx[dq.peekLast()-'a'] > i){\n inStack[dq.pollLast()-'a'] = false;\n }\n dq.addLast(ch);\n inStack[ch-'a'] = true;\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string smallestSubsequence(string s) {\n \n string st=\"\";\n unordered_map< char ,int> m;\n vector< bool> vis( 26,false);\n for( int i=0;i t;\n \n t.push(s[0]) , m[s[0]]--;\n st+=s[0];\n vis[s[0]-'a']=true;\n \n for( int i=1;i0 && t.top() > s[i]){\n st.pop_back();\n vis[ t.top()-'a']=false;\n t.pop();\n }\n t.push(s[i]);\n vis[s[i]-'a']=true;\n st=st+s[i];\n }\n }\n return st;\n }\n};" }, { "title": "Nth Magical Number", "algo_input": "A positive integer is magical if it is divisible by either a or b.\n\nGiven the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 1, a = 2, b = 3\nOutput: 2\n\n\nExample 2:\n\nInput: n = 4, a = 2, b = 3\nOutput: 6\n\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\t2 <= a, b <= 4 * 104\n\n", "solution_py": "class Solution:\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n import math\n lcm= A*B // math.gcd(A,B)\n l,r=2,10**14\n while l<=r:\n mid=(l+r)//2\n n = mid//A+mid//B-mid//lcm\n if n>=N:\n r=mid-1\n \n else:\n l=mid+1\n return l%(10**9+7)", "solution_js": "/**\n * @param {number} n\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nvar nthMagicalNumber = function(n, a, b) {\n const gcd = (a1,b1)=>{\n if(b1===0) return a1;\n return gcd(b1,a1%b1)\n }\n const modulo = 1000000007;\n let low = 0;\n let high = 10e17;\n let lcmAB = Math.floor((a*b)/gcd(a,b));\n \n while(low=N)\n {\n ans=mid;\n high=mid-1;\n }\n else if(x0)\n {\n long temp=a;\n a=b%a;\n b=temp;\n }\n\n return tmpA*tmpB/b;\n}\n}", "solution_c": "class Solution \n{\npublic:\n \n int lcm(int a, int b) // Finding the LCM of a and b\n {\n if(a==b)\n return a;\n if(a > b)\n {\n int count = 1;\n while(true)\n {\n if((a*count)%b==0)\n return a*count;\n count++;\n }\n }\n int count = 1;\n while(true)\n {\n if((b*count)%a==0)\n return b*count;\n count++;\n }\n return -1; // garbage value--ignore.\n }\n \n int nthMagicalNumber(int n, int a, int b) \n {\n long long int comm = lcm(a,b); //common element\n long long int first = (((comm*2) - comm) / a) - 1; //no. of elements appearing before the comm multiples (a).\n long long int second = (((comm*2) - comm) / b) - 1; //no. of elements appearing before the comm multiples(b).\n \n long long int landmark = (n / (first + second + 1)) * comm; // last common element before nth number.\n long long int offset = n % (first + second + 1); // how many numbers to consider after last common\n \n long long int p = landmark, q = landmark; // initialisations to find the offset from the landmarked element\n long long int ans = landmark;\n for(int i=1;i<=offset;i++) // forwarding offset number of times.\n {\n if(p+a < q+b) //this logic easily takes care of which elements to be considered for the current iteration. \n {\n ans = p+a;\n p = p+a;\n }\n else\n {\n ans = q+b;\n q = q+b;\n }\n }\n \n return (ans%1000000007); //returning the answer.\n }\n};\n\n/*\n a and b\n 1st step would be to find the LCM of the two numbers --> Multiples of LCM would be the common numbers in the sequential pattern.\n The next step would be to find the numbers of a and numbers of b appearing between the common number.\n \n\tDRY : \n\t\n 4 and 6\n 4 -> 4 8 12 16 20 24 28 32 36 40 --> \n 6 -> 6 12 18 24 30 36 42 48 54 60 -->\n \n 4 6 8 12 16 18 20 24 --> n/(f + s) ---> 23/4 = 5 and 3\n 5th -----> (comm * 5 = 60) ------>\n*/" }, { "title": "Search in Rotated Sorted Array II", "algo_input": "There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).\n\nBefore being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].\n\nGiven the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.\n\nYou must decrease the overall operation steps as much as possible.\n\n \nExample 1:\nInput: nums = [2,5,6,0,0,1,2], target = 0\nOutput: true\nExample 2:\nInput: nums = [2,5,6,0,0,1,2], target = 3\nOutput: false\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5000\n\t-104 <= nums[i] <= 104\n\tnums is guaranteed to be rotated at some pivot.\n\t-104 <= target <= 104\n\n\n \nFollow up: This problem is similar to Search in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?\n", "solution_py": "class Solution:\n def search(self, nums: List[int], target: int) -> bool:\n nums.sort()\n low=0\n high=len(nums)-1\n while low<=high:\n mid=(low+high)//2\n if nums[mid]==target:\n return True\n elif nums[mid]>target:\n high=mid-1\n else:\n low=mid+1\n return False", "solution_js": "var search = function(nums, target) {\n let found = nums.findIndex(c=> c==target);\n if(found === -1) return false\n else\n return true\n};", "solution_java": "class Solution {\n public boolean search(int[] nums, int target) {\n if (nums == null || nums.length == 0) return false;\n \n int left = 0, right = nums.length-1;\n int start = 0;\n\n//1. find index of the smallest element\n while(left < right) {\n while (left < right && nums[left] == nums[left + 1])\n ++left;\n while (left < right && nums[right] == nums[right - 1])\n --right;\n int mid = left + (right-left)/2;\n if (nums[mid] > nums[right]) {\n left = mid +1;\n } else right = mid;\n }\n \n//2. figure out in which side our target lies\n start = left;\n left = 0;\n right = nums.length-1;\n if (target >= nums[start] && target <= nums[right])\n left = start;\n else right = start;\n \n//3. Run normal binary search in sorted half.\n while(left <= right) {\n int mid = left + (right - left)/2;\n if (nums[mid] == target) return true;\n \n if (nums[mid] > target) right = mid-1;\n else left = mid + 1;\n }\n \n return false;\n}\n}", "solution_c": "class Solution {\npublic:\n bool search(vector& nums, int target) {\n \n if( nums[0] == target or nums.back() == target ) return true; \n // this line is redundant it reduces only the worst case when all elements are same to O(1)\n \n const int n = nums.size();\n int l = 0 , h = n-1;\n while( l+1 < n and nums[l] == nums[l+1]) l++;\n\n // if all elements are same\n if( l == n-1){\n if( nums[0] == target ) return true;\n else return false;\n }\n \n // while last element is equal to 1st element\n while( h >= 0 and nums[h] == nums[0] ) h--;\n int start = l , end = h;\n \n // find the point of pivot ie from where the rotation starts\n int pivot = -1;\n while( l <= h ){\n int mid = l + (h-l)/2;\n if( nums[mid] >= nums[0] ) l = mid+1;\n else {\n pivot = mid;\n h = mid-1;\n }\n }\n \n \n if( pivot == -1 ) l = start , h = end; // if no pivot exits then search space is from start -e end\n else {\n if( target > nums[end] ) l = start , h = pivot-1; // search space second half\n else l = pivot , h = end; // search space first half\n }\n \n // normal binary search\n while ( l <= h ){\n int mid = l + (h-l)/2;\n if( nums[mid] > target ) h = mid-1;\n else if( nums[mid] < target ) l = mid+1;\n else return true;\n }\n \n return false;\n \n }\n};" }, { "title": "Video Stitching", "algo_input": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.\n\nEach video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi.\n\nWe can cut these clips into segments freely.\n\n\n\tFor example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].\n\n\nReturn the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.\n\n \nExample 1:\n\nInput: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput: 3\nExplanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\n\n\nExample 2:\n\nInput: clips = [[0,1],[1,2]], time = 5\nOutput: -1\nExplanation: We cannot cover [0,5] with only [0,1] and [1,2].\n\n\nExample 3:\n\nInput: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput: 3\nExplanation: We can take clips [0,4], [4,7], and [6,9].\n\n\n \nConstraints:\n\n\n\t1 <= clips.length <= 100\n\t0 <= starti <= endi <= 100\n\t1 <= time <= 100\n\n", "solution_py": "class Solution:\n def videoStitching(self, clips: List[List[int]], T: int) -> int:\n dp = [float('inf')] * (T + 1)\n dp[0] = 0\n for i in range(1, T + 1):\n for start, end in clips:\n if start <= i <= end:\n dp[i] = min(dp[start] + 1, dp[i])\n if dp[T] == float('inf'):\n return -1\n return dp[T]", "solution_js": "/** https://leetcode.com/problems/video-stitching/\n * @param {number[][]} clips\n * @param {number} time\n * @return {number}\n */\nvar videoStitching = function(clips, time) {\n // Memo\n this.memo = new Map();\n \n // Sort the clips for easier iteration\n clips.sort((a, b) => a[0] - b[0]);\n \n // If the output is `Infinity` it means the task is impossible\n let out = dp(clips, time, 0, -1);\n return out === Infinity ? -1 : out;\n};\n\nvar dp = function(clips, time, index, endTime) {\n let key = `${index}_${endTime}`;\n \n // Base, we got all the clip we need\n if (endTime >= time) {\n return 0;\n }\n \n // Reach end of the clip array\n if (index === clips.length) {\n return Infinity;\n }\n \n // Return form memo\n if (this.memo.has(key) === true) {\n return this.memo.get(key);\n }\n \n // There are 2 choices, include clip in current `index` or exclude\n // Include clip in current `index`\n let include = Infinity;\n \n // We can only include clip in current `index` if either:\n // - the `endTime` is -1 and current clip's starting is 0, in which this clip is the first segment\n // - the `endTime` is greater than current clip's starting time, in which this clip has end time greater than our `endTime`\n if ((endTime < 0 && clips[index][0] === 0) ||\n endTime >= clips[index][0]) {\n // Update the next `endTime` with the current clip's end time, `clips[index][1]`\n let nextEndTime = clips[index][1];\n include = 1 + dp(clips, time, index + 1, nextEndTime);\n }\n \n // Exclude clip in current `index`\n let exclude = dp(clips, time, index + 1, endTime);\n \n // Find which one has less clips\n let count = Math.min(include, exclude);\n \n // Set memo\n this.memo.set(key, count);\n \n return count;\n};", "solution_java": "class Solution {\n public int videoStitching(int[][] clips, int time) {\n Arrays.sort(clips , (x , y) -> x[0] == y[0] ? y[1] - x[1] : x[0] - y[0]);\n int n = clips.length;\n int interval[] = new int[2];\n int cuts = 0;\n while(true){\n cuts++;\n int can_reach = 0;\n for(int i = interval[0]; i <= interval[1]; i++){\n int j = 0;\n while(j < n){\n if(clips[j][0] < i){\n j++;\n }\n else if(clips[j][0] == i){\n can_reach = Math.max(can_reach , clips[j][1]);\n j++;\n }\n else{\n break;\n }\n }\n if(can_reach >= time) return cuts;\n }\n interval[0] = interval[1] + 1;\n interval[1] = can_reach;\n if(interval[0] > interval[1]) return -1;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n static bool comp(vector a, vector b){\n if(a[0]b[1];\n return false;\n }\n\n int videoStitching(vector>& clips, int time) {\n sort(clips.begin(), clips.end(), comp);\n vector> res;\n //check if 0 is present or not\n if(clips[0][0] != 0) return -1;\n res.push_back(clips[0]);\n //if 1. First check if the required interval is already covered or not\n //if 2. If the first value of the already inserted element in res is equal, then the next value if obviously smaller interval because of custom sorting so, we should skip it\n //if 3. Cover every value by checking if the interval is required or not (already present?) if required then insert it\n //if 3.1. Check if the interval to be inserted covers the interval at the back for example [0,4], [2,6], now if we were to insert the interval [4, 7], then [2,6] is no more requried, then pop_back.\n for(int i=1; i=time) break;\n if(clips[i][0]==res.back()[0]) continue;\n if(clips[i][1]>res.back()[1]){\n if(res.size()>1 and res[res.size()-2][1]>=clips[i][0]) res.pop_back();\n res.push_back(clips[i]);\n }\n }\n //Check if the compelete range from 0 to time is covered or not\n int prev = res[0][1];\n for(int i=1; iprev) return -1;\n prev = res[i][1];\n }\n //check explicitly for the last value\n if(res.back()[1] bool:\n f = [0] + flowerbed + [0]\n\n i, could_plant = 1, 0\n while could_plant < n and i < len(f) - 1:\n if f[i + 1]:\n # 0 0 1 -> skip 3\n i += 3\n elif f[i]:\n # 0 1 0 -> skip 2\n i += 2\n elif f[i - 1]:\n # 1 0 0 -> skip 1\n i += 1\n else:\n # 0 0 0 -> plant, becomes 0 1 0 -> skip 2\n could_plant += 1\n i += 2\n\n return n <= could_plant", "solution_js": "/**\n * @param {number[]} flowerbed\n * @param {number} n\n * @return {boolean}\n */\nvar canPlaceFlowers = function(flowerbed, n) {\n for(let i=0 ; i& flowerbed, int n) {\n int count = 1;\n int result = 0;\n for(int i=0; i=n; \n }\n};" }, { "title": "Add Minimum Number of Rungs", "algo_input": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.\n\nYou are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.\n\nReturn the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.\n\n \nExample 1:\n\nInput: rungs = [1,3,5,10], dist = 2\nOutput: 2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].\n\n\nExample 2:\n\nInput: rungs = [3,6,8,10], dist = 3\nOutput: 0\nExplanation:\nThis ladder can be climbed without adding additional rungs.\n\n\nExample 3:\n\nInput: rungs = [3,4,6,7], dist = 2\nOutput: 1\nExplanation:\nYou currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].\n\n\n \nConstraints:\n\n\n\t1 <= rungs.length <= 105\n\t1 <= rungs[i] <= 109\n\t1 <= dist <= 109\n\trungs is strictly increasing.\n\n", "solution_py": "class Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n rungs=[0]+rungs\n i,ans=1,0\n while i dist:\n ans+=ceil((rungs[i]-rungs[i-1])/dist)-1\n i+=1\n return ans\n\n\n\n ", "solution_js": "var addRungs = function(rungs, dist) {\n let res = 0;\n let prev = 0;\n for ( let i = 0; i < rungs.length; i++ ){\n res += Math.floor(( rungs[i] - prev - 1 ) / dist );\n prev = rungs[i];\n }\n return res;\n};", "solution_java": "class Solution {\n public int addRungs(int[] rungs, int dist) {\n int ans = 0;\n for (int i=0 ; i dist ) {\n ans += d/dist;\n ans += ( d%dist == 0 ) ? -1 : 0;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int addRungs(vector& rungs, int dist) \n {\n //to keep the track of the number of extra rung to be added\n long long int count = 0;\n \n //our curr pos at the beggining\n long long int currpos = 0;\n\n //to keep the track of the next pos to be climed\n long long int nextposidx = 0;\n\n while(true)\n {\n if(currpos == rungs[rungs.size()-1])\n {\n break;\n }\n\n if((rungs[nextposidx] - currpos) <= dist)\n {\n currpos = rungs[nextposidx];\n nextposidx++;\n }\n else\n {\n //cout<<\"hello\"< bool:\n endheap = []\n startheap = []\n \n for i in range(len(trips)):\n endheap.append((trips[i][2],trips[i][0],trips[i][1]))\n startheap.append((trips[i][1],trips[i][0],trips[i][2]))\n heapify(endheap)\n heapify(startheap)\n cur = 0\n while startheap:\n start,num,end = heappop(startheap)\n while start >= endheap[0][0]:\n newend,newnum,newstart = heappop(endheap)\n cur -= newnum\n cur += num\n print(cur)\n if cur >capacity:\n return False\n return True\n \n \n \n ", "solution_js": "/**\n * @param {number[][]} trips\n * @param {number} capacity\n * @return {boolean}\n */\nvar carPooling = function(trips, capacity) {\n \n // sort trips by destination distance\n trips.sort((a, b) => a[2] - b[2]);\n \n // build result array, using max distance\n const lastTrip = trips[trips.length - 1];\n const maxDistance = lastTrip[lastTrip.length - 1];\n const arr = new Array(maxDistance + 1).fill(0);\n \n // build partial sum array\n for (const [val, start, end] of trips) {\n arr[start] += val;\n arr[end] -= val;\n }\n\n // build combined sum array\n let sum = 0;\n for (let i = 0; i < arr.length; i++) {\n sum += arr[i];\n if (sum > capacity) return false;\n }\n \n return true;\n};", "solution_java": "class Solution {\n public boolean carPooling(int[][] trips, int capacity) {\n Map destinationToPassengers = new TreeMap<>();\n for(int[] trip : trips) {\n int currPassengersAtPickup = destinationToPassengers.getOrDefault(trip[1], 0);\n int currPassengersAtDrop = destinationToPassengers.getOrDefault(trip[2], 0);\n destinationToPassengers.put(trip[1], currPassengersAtPickup + trip[0]);\n destinationToPassengers.put(trip[2], currPassengersAtDrop - trip[0]);\n }\n\n int currPassengers = 0;\n for(int passengers : destinationToPassengers.values()) {\n currPassengers += passengers;\n\n if(currPassengers > capacity) {\n return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\ntypedef pair pd;\npublic:\n bool carPooling(vector>& trips, int capacity) {\n int seat=0;\n priority_queue, greater>pq;\n for(auto it : trips)\n {\n pq.push({it[1], +it[0]});\n pq.push({it[2], -it[0]});\n }\n while(!pq.empty())\n {\n // cout<capacity) return false;\n pq.pop();\n }\n return true;\n }\n};" }, { "title": "Rotate Array", "algo_input": "Given an array, rotate the array to the right by k steps, where k is non-negative.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]\n\n\nExample 2:\n\nInput: nums = [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\nExplanation: \nrotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-231 <= nums[i] <= 231 - 1\n\t0 <= k <= 105\n\n\n \nFollow up:\n\n\n\tTry to come up with as many solutions as you can. There are at least three different ways to solve this problem.\n\tCould you do it in-place with O(1) extra space?\n\n", "solution_py": "class Solution:\n def reverse(self,arr,left,right):\n while left < right:\n arr[left],arr[right] = arr[right], arr[left]\n left, right = left + 1, right - 1\n return arr\n def rotate(self, nums: List[int], k: int) -> None:\n length = len(nums)\n k = k % length\n l, r = 0, length - 1\n nums = self.reverse(nums,l,r)\n l, r = 0, k - 1\n nums = self.reverse(nums,l,r)\n l, r = k, length - 1\n nums = self.reverse(nums,l,r)\n return nums", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nvar rotate = function(nums, k) {\n const len = nums.length;\n k %= len;\n const t = nums.splice(len - k, k);\n nums.unshift(...t);\n};", "solution_java": "class Solution {\n public void rotate(int[] nums, int k) {\n reverse(nums , 0 , nums.length-1);\n reverse(nums , 0 , k-1);\n reverse(nums , k , nums.length -1);\n }\n \n public static void reverse(int[] arr , int start , int end){\n while(start& nums, int k) {\n\n vector temp(nums.size());\n for(int i = 0; i < nums.size() ;i++){\n\n temp[(i+k)%nums.size()] = nums[i];\n\n }\n\n nums = temp;\n }\n};" }, { "title": "License Key Formatting", "algo_input": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.\n\nWe want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.\n\nReturn the reformatted license key.\n\n \nExample 1:\n\nInput: s = \"5F3Z-2e-9-w\", k = 4\nOutput: \"5F3Z-2E9W\"\nExplanation: The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.\n\n\nExample 2:\n\nInput: s = \"2-5g-3-J\", k = 2\nOutput: \"2-5G-3J\"\nExplanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of English letters, digits, and dashes '-'.\n\t1 <= k <= 104\n\n", "solution_py": "class Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n new_str = s.replace(\"-\", \"\")\n res = \"\"\n j = len(new_str)-1\n i = 0\n while j >= 0:\n res += new_str[j].upper()\n i += 1\n if i == k and j != 0:\n res += \"-\"\n i = 0\n j -= 1\n return res[::-1]", "solution_js": "// Please upvote if you like the solution. Thanks\n\nvar licenseKeyFormatting = function(s, k) {\n let str=s.replace(/[^A-Za-z0-9]/g,\"\").toUpperCase()\n let ans=\"\"\n let i=str.length;\n while(i>0){\n ans=\"-\"+str.substring(i-k,i)+ans // we are taking k characters from the end of string and adding it to answer\n i=i-k\n }\n return (ans.substring(1)) // removing the \"-\" which is present in the start of ans\n};", "solution_java": "class Solution {\n public String licenseKeyFormatting(String s, int k) {\n StringBuilder answer = new StringBuilder();\n int length = 0;\n // Iterate Backwards to fullfill first group condition\n for(int i=s.length()-1;i>=0;i--) {\n if(s.charAt(i) == '-') {\n continue;\n }\n if(length > 0 && length % k == 0) {\n answer.append('-');\n }\n answer.append(Character.toUpperCase(s.charAt(i)));\n length++;\n }\n return answer.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string licenseKeyFormatting(string s, int k) {\n stackst;\n string ans=\"\";\n for(int i=0;i0){\n char ch=st.top();\n st.pop();\n if(isalpha(ch)) \n {\n ch=toupper(ch);\n }\n ans+=ch;\n if((i+1)%k==0 && st.size()!=0) ans+='-';\n i++;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};" }, { "title": "Count the Hidden Sequences", "algo_input": "You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].\n\nYou are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.\n\n\n\tFor example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive).\n\n\t\n\t\t[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.\n\t\t[5, 6, 3, 7] is not possible since it contains an element greater than 6.\n\t\t[1, 2, 3, 4] is not possible since the differences are not correct.\n\t\n\t\n\n\nReturn the number of possible hidden sequences there are. If there are no possible sequences, return 0.\n\n \nExample 1:\n\nInput: differences = [1,-3,4], lower = 1, upper = 6\nOutput: 2\nExplanation: The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.\n\n\nExample 2:\n\nInput: differences = [3,-4,5,1,-2], lower = -4, upper = 5\nOutput: 4\nExplanation: The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.\n\n\nExample 3:\n\nInput: differences = [4,-7,2], lower = 3, upper = 6\nOutput: 0\nExplanation: There are no possible hidden sequences. Thus, we return 0.\n\n\n \nConstraints:\n\n\n\tn == differences.length\n\t1 <= n <= 105\n\t-105 <= differences[i] <= 105\n\t-105 <= lower <= upper <= 105\n\n", "solution_py": "class Solution:\n def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n l = [0]\n for i in differences:\n l.append(l[-1]+i)\n return max(0,(upper-lower+1)-(max(l)-min(l)))", "solution_js": "var numberOfArrays = function(differences, lower, upper) {\n let temp = 0;\n let res = 0;\n let n = lower;\n\n for (let i = 0; i < differences.length; i++) {\n temp += differences[i];\n differences[i] = temp;\n }\n\n const min = Math.min(...differences);\n const max = Math.max(...differences);\n\n while (n <= upper) {\n if (n + min >= lower && n + max <= upper) res++;\n n++;\n }\n return res;\n};", "solution_java": "class Solution {\n public int numberOfArrays(int[] differences, int lower, int upper) {\n ArrayList ans = new ArrayList<>();\n ans.add(lower); \n int mn = lower;\n int mx = lower;\n \n for (int i = 0; i < differences.length; i++) {\n int d = differences[i];\n ans.add(d + ans.get(ans.size() - 1));\n mn = Math.min(mn, ans.get(ans.size() - 1));\n mx = Math.max(mx, ans.get(ans.size() - 1));\n }\n\n int add = lower - mn;\n \n for (int i = 0; i < ans.size(); i++) {\n ans.set(i, ans.get(i) + add);\n }\n \n for (int i = 0; i < ans.size(); i++) {\n if (ans.get(i) < lower || upper < ans.get(i)) {\n return 0;\n }\n }\n \n int add2 = upper - mx;\n \n return add2 - add + 1;\n }\n}", "solution_c": "using ll = long long int;\nclass Solution {\n public:\n int numberOfArrays(vector& differences, int lower, int upper) {\n vector ans; \n ans.push_back(lower); \n ll mn = lower;\n ll mx = lower;\n for (const auto& d: differences) {\n ans.push_back(d + ans.back());\n mn = min(mn, ans.back());\n mx = max(mx, ans.back());\n }\n\n ll add = lower - mn;\n \n for (auto& i: ans) i += add;\n for (auto& i: ans) if (i < lower or upper < i) return 0;\n \n ll add2 = upper - mx;\n \n return add2 - add + 1;\n }\n}; " }, { "title": "All Divisions With the Highest Score of a Binary Array", "algo_input": "You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:\n\n\n\tnumsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive).\n\tIf i == 0, numsleft is empty, while numsright has all the elements of nums.\n\tIf i == n, numsleft has all the elements of nums, while numsright is empty.\n\n\nThe division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright.\n\nReturn all distinct indices that have the highest possible division score. You may return the answer in any order.\n\n \nExample 1:\n\nInput: nums = [0,0,1,0]\nOutput: [2,4]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3.\n- 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2.\n- 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.\n\nExample 2:\n\nInput: nums = [0,0,0]\nOutput: [3]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1.\n- 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2.\n- 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.\n\n\nExample 3:\n\nInput: nums = [1,1]\nOutput: [0]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2.\n- 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1.\n- 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\tnums[i] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def maxScoreIndices(self, nums: List[int]) -> List[int]:\n zeroFromLeft = [0] * (len(nums) + 1)\n oneFromRight = [0] * (len(nums) + 1)\n for i in range(len(nums)):\n if nums[i] == 0:\n zeroFromLeft[i + 1] = zeroFromLeft[i] + 1\n else:\n zeroFromLeft[i + 1] = zeroFromLeft[i]\n\n for i in range(len(nums))[::-1]:\n if nums[i] == 1:\n oneFromRight[i] = oneFromRight[i + 1] + 1\n else:\n oneFromRight[i] = oneFromRight[i + 1]\n\n allSum = [0] * (len(nums) + 1)\n currentMax = 0\n res = []\n for i in range(len(nums) + 1):\n allSum[i] = oneFromRight[i] + zeroFromLeft[i]\n if allSum[i] > currentMax:\n res = []\n currentMax = allSum[i]\n if allSum[i] == currentMax:\n res.append(i)\n return res", "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar maxScoreIndices = function(nums) {\n let n=nums.length;\n // initialize 3 arrays for counting with n+1 size\n let zeros = new Array(n+1).fill(0);\n let ones = new Array(n+1).fill(0);\n let total = new Array(n+1).fill(0);\n\n // count no of zeros from left to right\n for(let i=0;i=0;i--){\n if(nums[i]==1)ones[i]=ones[i+1]+1;\n else ones[i]=ones[i+1];\n }\n\n // merge left and right to total and find max element\n let max=0;\n for(let i=0;imax)max=total[i];\n }\n\n // Find occurrence of max elements and return those indexes\n let ans= [];\n for(let i=0;i maxScoreIndices(int[] nums) {\n int N = nums.length;\n List res = new ArrayList<>();\n\n int[] pref = new int[N + 1];\n pref[0] = 0; // at zeroth division we have no elements\n for(int i = 0; i < N; ++i) pref[i+1] = nums[i] + pref[i];\n\n int maxScore = -1;\n int onesToRight, zeroesToLeft, currScore;\n\n for(int i = 0; i < N + 1; ++i) {\n onesToRight = pref[N] - pref[i];\n zeroesToLeft = i - pref[i];\n currScore = zeroesToLeft + onesToRight;\n\n if(currScore > maxScore) {\n res.clear();\n maxScore = currScore;\n }\n if(currScore == maxScore) res.add(i);\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector maxScoreIndices(vector& nums) {\n int n=nums.size();\n if(n==1)\n {\n if(nums[0]==0)\n return {1};\n else\n return {0};\n }\n int one=0,zero=0;\n for(int i=0;i v;\n v.push_back(one);\n int ans=one;\n if(nums[0]==1)\n one--;\n \n for(int i=1;i res;\n for(int i=0;i<=n;i++)\n {\n // cout< Optional[ListNode]:\n heap = []\n heapq.heapify(heap)\n start = end = ListNode(-1)\n for i in lists:\n if i:\n heappush(heap,(i.val,id(i),i))\n while heap:\n val,iD,node = heappop(heap)\n end.next = node\n node = node.next\n end = end.next\n if node:\n heappush(heap,(node.val,id(node),node))\n \n return start.next", "solution_js": "var mergeKLists = function(lists) { \n // Use min heap to keep track of the smallest node in constant time.\n // Enqueue and dequeue will be log(k) where k is the # of lists\n // b/c we only need to keep track of the next node for each list\n // at any given time.\n const minHeap = new MinPriorityQueue({ priority: item => item.val });\n \n for (let head of lists) {\n if (head) minHeap.enqueue(head);\n }\n \n // Create tempHead that we initiate the new list with\n // Final list will start at tempHead.next\n const tempHead = new ListNode();\n let curr = tempHead;\n \n while (!minHeap.isEmpty()) {\n const { val, next } = minHeap.dequeue().element;\n curr.next = new ListNode(val);\n curr = curr.next;\n \n if (next) minHeap.enqueue(next);\n }\n \n return tempHead.next;\n};", "solution_java": "class Solution {\npublic ListNode mergeKLists(ListNode[] lists) {\n if(lists == null || lists.length < 1) return null;\n\n //add the first chunk of linkedlist to res,\n //so later we started from index 1\n ListNode res = lists[0];\n\n //traverse the lists and start merge by calling mergeTwo\n for(int i = 1; i < lists.length; i++){\n res = mergeTwo(res, lists[i]);\n }\n\n return res;\n}\n //leetcode 21 technics\n private ListNode mergeTwo(ListNode l1, ListNode l2){\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n\n if(l1.val < l2.val){\n l1.next = mergeTwo(l1.next, l2);\n return l1;\n } else{\n l2.next = mergeTwo(l2.next, l1);\n return l2;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n struct compare\n {\n bool operator()(ListNode* &a,ListNode* &b)\n {\n return a->val>b->val;\n }\n };\n ListNode* mergeKLists(vector& lists) {\n priority_queue,compare>minh;\n for(int i=0;i0)\n {\n ListNode* p=minh.top();\n minh.pop();\n temp->next=new ListNode(p->val);\n temp=temp->next;\n if(p->next!=NULL) minh.push(p->next);\n }\n return head->next;\n }\n};" }, { "title": "Minimum Replacements to Sort the Array", "algo_input": "You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.\n\n\n\tFor example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].\n\n\nReturn the minimum number of operations to make an array that is sorted in non-decreasing order.\n\n \nExample 1:\n\nInput: nums = [3,9,3]\nOutput: 2\nExplanation: Here are the steps to sort the array in non-decreasing order:\n- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]\n- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]\nThere are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.\n\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: The array is already in non-decreasing order. Therefore, we return 0. \n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def minimumReplacement(self, nums) -> int:\n ans = 0\n n = len(nums)\n curr = nums[-1]\n for i in range(n - 2, -1, -1):\n if nums[i] > curr:\n q = nums[i] // curr\n if nums[i] == curr * q:\n nums[i] = curr\n ans += q - 1\n else:\n nums[i] = nums[i] // (q + 1)\n ans += q\n curr = nums[i]\n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumReplacement = function(nums) {\n const n = nums.length;\n let ans = 0;\n for(let i = n - 2 ; i >= 0 ; i--){\n if(nums[i]>nums[i+1]){\n const temp = Math.ceil(nums[i]/nums[i+1]);\n ans += temp - 1;\n nums[i] = Math.floor(nums[i]/temp);\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public long minimumReplacement(int[] nums) {\n long ret = 0L;\n int n = nums.length;\n int last = nums[n - 1];\n for(int i = n - 2;i >= 0; i--){\n if(nums[i] <= last){\n last = nums[i];\n continue;\n }\n if(nums[i] % last == 0){\n // split into nums[i] / last elements, operations cnt = nums[i] / last - 1;\n ret += nums[i] / last - 1;\n }else{\n // split into k elements operations cnt = k - 1;\n int k = nums[i] / last + 1; // ceil\n ret += k - 1;\n last = nums[i] / k; // left most element max is nums[i] / k\n }\n\n }\n\n return ret;\n }\n\n}", "solution_c": "class Solution {\npublic:\n long long minimumReplacement(vector& nums) {\n long long res=0;\n int n=nums.size();\n int mxm=nums[n-1];\n long long val;\n for(int i=n-2;i>=0;i--)\n {\n // minimum no. of elemetns nums[i] is divided such that every number is less than mxm and minimum is maximized\n val= ceil(nums[i]/(double)mxm); \n \n // no. of steps is val-1\n res+=(val-1);\n \n // the new maximized minimum value \n val=nums[i]/val;\n mxm= val;\n }\n return res;\n }\n};" }, { "title": "Sum of Numbers With Units Digit K", "algo_input": "Given two integers num and k, consider a set of positive integers with the following properties:\n\n\n\tThe units digit of each integer is k.\n\tThe sum of the integers is num.\n\n\nReturn the minimum possible size of such a set, or -1 if no such set exists.\n\nNote:\n\n\n\tThe set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.\n\tThe units digit of a number is the rightmost digit of the number.\n\n\n \nExample 1:\n\nInput: num = 58, k = 9\nOutput: 2\nExplanation:\nOne valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.\n\n\nExample 2:\n\nInput: num = 37, k = 2\nOutput: -1\nExplanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.\n\n\nExample 3:\n\nInput: num = 0, k = 7\nOutput: 0\nExplanation: The sum of an empty set is considered 0.\n\n\n \nConstraints:\n\n\n\t0 <= num <= 3000\n\t0 <= k <= 9\n\n", "solution_py": "class Solution:\n def minimumNumbers(self, num: int, k: int) -> int:\n if num == 0:\n return 0\n \n if k == 0:\n return 1 if num % 10 == 0 else -1\n \n for n in range(1, min(num // k, 10) + 1):\n if (num - n * k) % 10 == 0:\n return n\n \n return -1", "solution_js": "var minimumNumbers = function(num, k) {\n if (num === 0) return 0;\n for (let i = 1; i <= 10; i++) {\n if (k*i % 10 === num % 10 && k*i <= num) return i;\n if (k*i > num) return -1\n } return -1;\n};", "solution_java": "class Solution\n{\n public int minimumNumbers(int num, int k)\n {\n if(num == 0)\n return 0;\n if(k == 0)\n if(num % 10 == 0) //E.g. 20,1590,3000\n return 1;\n else\n return -1;\n for(int i = 1; i <= num/k; i++) // Start with set size 1 and look for set having unit's digit equal to that of num\n if(num % 10 == ((i*k)%10)) // Look for equal unit's digit\n return i;\n\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n \n //same code as that of coin change\n int coinChange(vector& coins, int amount) {\n int Max = amount + 1;\n vector dp(amount + 1, INT_MAX);\n dp[0] = 0;\n for (int i = 0; i <= amount; i++) {\n for (int j = 0; j < coins.size(); j++) {\n if (coins[j] <= i && dp[i-coins[j]] !=INT_MAX) {\n dp[i] = min(dp[i], dp[i - coins[j]] + 1);\n }\n }\n }\n return dp[amount] == INT_MAX ? -1 : dp[amount];\n }\n \n \n \n int minimumNumbers(int num, int k) {\n vectorres;\n for (int i = 0; i <= num; i++){\n if (i % 10 == k)\n res.push_back(i);\n }\n return coinChange(res, num);\n\n \n }\n \n};" }, { "title": "Minimum Operations to Make Array Equal", "algo_input": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).\n\nIn one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.\n\nGiven an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 2\nExplanation: arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\n\n\nExample 2:\n\nInput: n = 6\nOutput: 9\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "class Solution:\n def minOperations(self, n: int) -> int:\n\n return sum([n-x for x in range(n) if x % 2 != 0])", "solution_js": "var minOperations = function(n) {\n let reqNum;\n if(n%2!=0){\n reqNum = Math.floor(n/2)*2+1\n }else{\n reqNum = ((Math.floor(n/2))*2+1 + (Math.floor(n/2) -1)*2+1)/2\n }\n let count = 0;\n for(let i=1; i int:\n while original in nums:\n original *= 2\n return original", "solution_js": "var findFinalValue = function(nums, original) {\n while (nums.includes(original)) {\n original = original * 2\n }\n\n return original\n};", "solution_java": "class Solution\n{\n public int findFinalValue(int[] nums, int original)\n {\n HashSet set = new HashSet<>();\n for(int i : nums)\n if(i >= original)\n set.add(i);\n while(true)\n if(set.contains(original))\n original *= 2;\n else\n break;\n return original;\n }\n}", "solution_c": "class Solution {\npublic:\n int findFinalValue(vector& nums, int original) {\n int n = 1;\n for(int i = 0; i None:\n firstDecreasingElement = -1\n toSwapWith = -1\n lastIndex = len(nums) - 1\n\n # Looking for an element that is less than its follower\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[i - 1]:\n firstDecreasingElement = i - 1\n break\n\n # If there is not any then reverse the array to make initial permutation\n if firstDecreasingElement == -1:\n for i in range(0, lastIndex // 2 + 1):\n nums[i], nums[lastIndex - i] = nums[lastIndex - i], nums[i]\n return\n\n # Looking for an element to swap it with firstDecreasingElement\n for i in range(lastIndex, 0, -1):\n if nums[i] > nums[firstDecreasingElement]:\n toSwapWith = i\n break\n\n # Swap found elements\n nums[firstDecreasingElement], nums[toSwapWith] = nums[toSwapWith], nums[firstDecreasingElement]\n\n # Reverse elements from firstDecreasingElement to the end of the array\n left = firstDecreasingElement + 1\n right = lastIndex\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1", "solution_js": "/**\n * @param {number[]} nums\n * @return {void} Do not return anything, modify nums in-place instead.\n */\nvar nextPermutation = function(nums) {\n const dsc = nums.slice();\n dsc.sort((a, b) => b - a);\n if (dsc.every((n, i) => n === nums[i])) {\n nums.sort((a, b) => a - b);\n } else {\n const len = nums.length;\n let lo = len - 1, hi;\n while (nums[lo] === dsc[dsc.length - 1]) {\n lo--;\n dsc.pop();\n }\n while (lo >= 0) {\n // console.log(lo, nums[lo], nums.slice(lo + 1))\n hi = nums.slice(lo + 1).reverse().findIndex((n) => n > nums[lo]);\n if (hi !== -1) {\n hi = len - 1 - hi;\n break;\n }\n lo--;\n }\n\n const lval = nums[lo];\n // console.log(lo, lval, hi, nums[hi]);\n nums[lo] = nums[hi];\n nums[hi] = lval;\n const sorted = nums.slice(lo + 1);\n // console.log(nums, sorted)\n sorted.sort((a, b) => a - b);\n for (let i = 0; i < sorted.length; i++)\n nums[lo + 1 + i] = sorted[i];\n }\n};", "solution_java": "class Solution {\n public void nextPermutation(int[] nums) {\n // FIND peek+1\n int nextOfPeak = -1;\n for (int i = nums.length - 1; i > 0; i--) {\n if (nums[i] > nums[i - 1]) {\n nextOfPeak = i - 1;\n break;\n }\n }\n\n // Return reverse Array\n if (nextOfPeak == -1) {\n int start = 0;\n int end = nums.length - 1;\n while (start <= end) {\n int temp = nums[start];\n nums[start] = nums[end];\n nums[end] = temp;\n start++;\n end--;\n }\n return;\n }\n // Find element greater than peek\n int reversalPoint = nums.length - 1;\n for (int i = nums.length - 1; i > nextOfPeak; i--) {\n if (nums[i] > nums[nextOfPeak]) {\n reversalPoint = i;\n break;\n }\n }\n\n // swap nextOfPeak && reversalPoint\n int temp = nums[nextOfPeak];\n nums[nextOfPeak] = nums[reversalPoint];\n nums[reversalPoint] = temp;\n\n // Reverse array from nextOfPeak+1\n int start = nextOfPeak + 1;\n int end = nums.length - 1;\n while (start <= end) {\n int temp1 = nums[start];\n nums[start] = nums[end];\n nums[end] = temp1;\n start++;\n end--;\n }\n\n }\n}", "solution_c": "class Solution {\npublic:\n void nextPermutation(vector& nums) {\n if(nums.size()==1)\n return;\n\n int i=nums.size()-2;\n while(i>=0 && nums[i]>=nums[i+1]) i--;\n if(i>=0){\n int j=nums.size()-1;\n while(nums[i] >= nums[j]) j--;\n swap(nums[j], nums[i]);\n }\n sort(nums.begin()+i+1, nums.end());\n }\n};" }, { "title": "Out of Boundary Paths", "algo_input": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.\n\nGiven the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\nOutput: 6\n\n\nExample 2:\n\nInput: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\nOutput: 12\n\n\n \nConstraints:\n\n\n\t1 <= m, n <= 50\n\t0 <= maxMove <= 50\n\t0 <= startRow < m\n\t0 <= startColumn < n\n\n", "solution_py": "class Solution:\n def helper(self, m, n, maxMove, startRow, startColumn, mat,dp) -> int:\n if startRow < 0 or startRow >=m or startColumn < 0 or startColumn >=n:\n return 1\n \n if dp[maxMove][startRow][startColumn]!=-1:\n return dp[maxMove][startRow][startColumn]\n \n if mat[startRow][startColumn]==1:\n return 0\n \n if maxMove <= 0:\n return 0\n \n # mat[startRow][startColumn] = 1\n a = self.helper(m, n, maxMove-1, startRow+1, startColumn,mat,dp)\n b = self.helper(m, n, maxMove-1, startRow-1, startColumn,mat,dp)\n c = self.helper(m, n, maxMove-1, startRow, startColumn+1,mat,dp)\n d = self.helper(m, n, maxMove-1, startRow, startColumn-1,mat,dp)\n dp[maxMove][startRow][startColumn] = a+b+c+d\n return dp[maxMove][startRow][startColumn]\n \n \n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n mat = [[0 for i in range(n)] for j in range(m)]\n dp = [[[-1 for i in range(n+1)] for j in range(m+1)] for k in range(maxMove+1)]\n return self.helper(m, n, maxMove, startRow, startColumn, mat,dp)%(10**9 + 7) \n \n\n ", "solution_js": "vector>> dp;\n\nint dx[4] = {0,0,1,-1};\nint dy[4] = {1,-1,0,0};\n\nint mod = 1e9+7;\n\nint fun(int i,int j,int n,int m,int k){\n \n if(i < 0 || j < 0 || i == n || j == m)return 1;\n else if(k == 0)return 0;\n \n if(dp[i][j][k] != -1)return dp[i][j][k];\n \n int ans = 0;\n for(int c = 0; c < 4; c++){\n int ni = i+dx[c] , nj = j+dy[c];\n ans = (ans + fun(ni,nj,n,m,k-1)) % mod;\n }\n \n return dp[i][j][k] = ans;\n}\n\nint findPaths(int m, int n, int maxMove, int startRow, int startCol) {\n \n dp = vector>>(m, vector>(n, vector(maxMove+1, -1)));\n\t\n return fun(startRow, startCol,m,n,maxMove);\n}", "solution_java": "class Solution {\n int[][][] dp;\n int mod = 1000000007;\n public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n dp = new int[m][n][maxMove + 1];\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n for (int k = 0; k <= maxMove; k++)\n dp[i][j][k] = -1;\n return count(m, n, maxMove, startRow, startColumn) % mod;\n }\n public int count(int m, int n, int move, int r, int c) {\n if (r < 0 || c < 0 || r >= m || c >= n)\n return 1;\n if (move <= 0)\n return 0;\n if (dp[r][c][move] != -1)\n return dp[r][c][move] % mod;\n dp[r][c][move] = ((count(m, n, move - 1, r + 1, c) % mod + count (m, n, move - 1, r - 1, c) % mod) % mod + (count (m, n, move - 1, r, c + 1) % mod + count(m, n, move - 1, r, c - 1) % mod) % mod ) % mod;\n return dp[r][c][move] % mod;\n }\n}", "solution_c": "vector>> dp;\n\nint dx[4] = {0,0,1,-1};\nint dy[4] = {1,-1,0,0};\n\nint mod = 1e9+7;\n\nint fun(int i,int j,int n,int m,int k){\n \n if(i < 0 || j < 0 || i == n || j == m)return 1;\n else if(k == 0)return 0;\n \n if(dp[i][j][k] != -1)return dp[i][j][k];\n \n int ans = 0;\n for(int c = 0; c < 4; c++){\n int ni = i+dx[c] , nj = j+dy[c];\n ans = (ans + fun(ni,nj,n,m,k-1)) % mod;\n }\n \n return dp[i][j][k] = ans;\n}\n\nint findPaths(int m, int n, int maxMove, int startRow, int startCol) {\n \n dp = vector>>(m, vector>(n, vector(maxMove+1, -1)));\n\t\n return fun(startRow, startCol,m,n,maxMove);\n}" }, { "title": "Count of Range Sum", "algo_input": "Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.\n\nRange sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.\n\n \nExample 1:\n\nInput: nums = [-2,5,-1], lower = -2, upper = 2\nOutput: 3\nExplanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n\n\nExample 2:\n\nInput: nums = [0], lower = 0, upper = 0\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-231 <= nums[i] <= 231 - 1\n\t-105 <= lower <= upper <= 105\n\tThe answer is guaranteed to fit in a 32-bit integer.\n\n", "solution_py": "class Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n acc = list(accumulate(nums))\n ans = a = 0\n for n in nums:\n a += n\n ans += sum(1 for x in acc if lower <= x <= upper)\n acc.pop(0)\n lower += n\n upper += n\n return ans", "solution_js": "var countRangeSum = function(nums, lower, upper) {\n let preSum = Array(nums.length + 1).fill(0);\n let count = 0;\n\n // create preSum array, use preSum to check the sum range\n for (let i = 0; i < nums.length; i++) {\n preSum[i + 1] = preSum[i] + nums[i];\n }\n\n const sort = function(preSum) {\n if (preSum.length === 1) return preSum;\n\n let mid = Math.floor(preSum.length / 2);\n let left = sort(preSum.slice(0, mid));\n let right = sort(preSum.slice(mid))\n\n return merge(left, right);\n }\n\n const merge = function(left, right) {\n let start = 0;\n let end = 0;\n\n for (let i = 0; i < left.length; i++) {\n // all elements before start index, after subtracting left[i] are less than lower, which means all elements after start index are bigger or equal than lower\n while (start < right.length && right[start] - left[i] < lower) {\n start++;\n }\n // similarly, all elements before end index are less or euqal then upper\n while (end < right.length && right[end] - left[i] <= upper) {\n end++;\n }\n\n // since the initial values of start and end are the same, and upper >= lower, so end will >= start too, which means the rest of the end minus start element difference will fall between [lower, upper].\n count += end - start;\n }\n\n let sort = [];\n while (left.length && right.length) {\n if (left[0] <= right[0]) {\n sort.push(left.shift());\n } else {\n sort.push(right.shift());\n }\n }\n\n return [...sort, ...left, ...right];\n }\n\n sort(preSum);\n return count;\n};", "solution_java": "class Solution {\n public int countRangeSum(int[] nums, int lower, int upper) {\n int n = nums.length, ans = 0;\n long[] pre = new long[n+1];\n for (int i = 0; i < n; i++){\n pre[i+1] = nums[i] + pre[i];\n }\n Arrays.sort(pre);\n int[] bit = new int[pre.length+2];\n long sum = 0;\n for (int i = 0; i < n; i++){\n update(bit, bs(sum, pre), 1);\n sum += nums[i];\n ans += sum(bit, bs(sum-lower, pre)) - sum(bit, bs(sum-upper-1, pre));\n }\n return ans;\n }\n\n private int bs(long sum, long[] pre){ // return the index of first number bigger than sum\n int lo = 0, hi = pre.length;\n while(lo < hi){\n int mid = (lo+hi) >> 1;\n if (pre[mid]>sum){\n hi=mid;\n }else{\n lo=mid+1;\n }\n }\n return lo;\n }\n\n private void update(int[] bit, int idx, int inc){\n for (++idx; idx < bit.length; idx += idx & -idx){\n bit[idx] += inc;\n }\n }\n\n private int sum(int[] bit, int idx){\n int ans = 0;\n for (++idx; idx > 0; idx -= idx & -idx){\n ans += bit[idx];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n using ll = long long;\n\n int countRangeSum(vector& nums, int lower, int upper) {\n // Build prefix sums\n vector prefixSums(nums.size() + 1, 0);\n for (int i = 0; i < nums.size(); i++) {\n prefixSums[i + 1] = prefixSums[i] + nums[i];\n }\n\n // Run merge sort and count range sum along the way\n tempNums.assign(prefixSums.size(), 0);\n splitAndMerge(prefixSums, 0, prefixSums.size(), lower, upper);\n\n return count;\n }\n\n void splitAndMerge(vector &nums, const int left, const int right, const int lower, const int upper) {\n if (right - left <= 1) return;\n const int mid = left + (right - left) / 2;\n splitAndMerge(nums, left, mid, lower, upper);\n splitAndMerge(nums, mid, right, lower, upper);\n\n countRangeSums(nums, left, mid, right, lower, upper);\n\n merge(nums, left, mid, right);\n }\n\n void countRangeSums(const vector &prefixSums, const int left, const int mid, const int right, const int lower, const int upper) {\n // S(i,j) == prefixSums[j+1] - prefixSums[i] (i <= j)\n // S(i,j) == prefixSums[k] - prefixSums[i] (let k=j+1, i < k)\n //\n // lower <= S(i,j) <= upper\n // => lower <= prefixSums[k] - prefixSums[i] <= upper\n // => lower + prefixSums[i] <= prefixSums[k] <= upper + prefixSums[i]\n for (int i = left; i < mid; i++) {\n const ll newLower = lower + prefixSums[i];\n const ll newUpper = upper + prefixSums[i];\n const auto findStart = prefixSums.begin() + mid;\n const auto findEnd = prefixSums.begin() + right;\n const auto itFoundLower = std::lower_bound(findStart, findEnd, newLower);\n const auto itFoundUpper = std::upper_bound(findStart, findEnd, newUpper);\n count += (itFoundUpper - itFoundLower);\n }\n }\n\n void merge(vector &nums, const int left, const int mid, const int right) {\n std::copy(nums.begin() + left, nums.begin() + right, tempNums.begin() + left);\n int i = left, j = mid;\n for (int k = left; k < right; k++) {\n if (i < mid && j < right) {\n if (tempNums[i] < tempNums[j]) {\n nums[k] = tempNums[i++];\n } else {\n nums[k] = tempNums[j++];\n }\n } else if (i >= mid) {\n nums[k] = tempNums[j++];\n } else { // j >= right\n nums[k] = tempNums[i++];\n }\n }\n }\n\n vector tempNums;\n int count = 0;\n};" }, { "title": "Vertical Order Traversal of a Binary Tree", "algo_input": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree.\n\nFor each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).\n\nThe vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.\n\nReturn the vertical order traversal of the binary tree.\n\n \nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[9],[3,15],[20],[7]]\nExplanation:\nColumn -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.\n\nExample 2:\n\nInput: root = [1,2,3,4,5,6,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nColumn -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.\n\n\nExample 3:\n\nInput: root = [1,2,3,4,6,5,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nThis case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 <= Node.val <= 1000\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 verticalTraversal(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n q = [(0, 0, root)]\n l = []\n while q:\n col, row, node = q.pop()\n l.append((col, row, node.val))\n if node.left:\n q.append((col-1, row+1, node.left))\n if node.right:\n q.append((col+1, row+1, node.right))\n l.sort()\n print(l)\n ans = []\n ans.append([l[0][-1]])\n for i in range(1, len(l)):\n if l[i][0] > l[i-1][0]:\n ans.append([l[i][-1]])\n else:\n ans[-1].append(l[i][-1])\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 {number[][]}\n */\nvar verticalTraversal = function(root) {\n let ans = [];\n let l = 0, ri = 0, mi = 0;\n const preOrder = (r = root, mid = 0, d = 0) => {\n if(!r) return ;\n\n if(mid == 0) {\n if(ans.length < mi + 1) ans.push([]);\n ans[mi].push({v: r.val, d});\n } else if(mid < 0) {\n if(mid < l) {\n l = mid;\n mi++;\n ans.unshift([{v: r.val, d}]);\n } else {\n let idx = mi + mid;\n ans[idx].push({v: r.val, d});\n }\n } else {\n if(mid > ri) {\n ri = mid;\n ans.push([{v: r.val, d}]);\n } else {\n let idx = mi + mid;\n ans[idx].push({v: r.val, d});\n }\n }\n\n preOrder(r.left, mid - 1, d + 1);\n preOrder(r.right, mid + 1, d + 1);\n }\n preOrder();\n const sortByDepthOrVal = (a, b) => {\n if(a.d == b.d) return a.v - b.v;\n return a.d - b.d;\n }\n ans = ans.map(col => col.sort(sortByDepthOrVal).map(a => a.v));\n return ans;\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\n private static class MNode {\n TreeNode Node;\n int hDist;\n int level;\n MNode(TreeNode node, int hd, int l) {\n Node = node;\n hDist = hd;\n level = l;\n }\n }\n\n public List> verticalTraversal(TreeNode root) {\n Map> map = new TreeMap<>();\n Queue q = new LinkedList<>();\n\n q.add(new MNode(root, 0, 0));\n\n while(!q.isEmpty()) {\n\n MNode curr = q.poll();\n if(map.containsKey(curr.hDist))\n map.get(curr.hDist).add(curr);\n\n else {\n PriorityQueue pq = new PriorityQueue<>\n ((a,b) -> (a.level == b.level)? a.Node.val - b.Node.val: a.level - b.level);\n pq.add(curr);\n map.put(curr.hDist, pq);\n }\n\n if(curr.Node.left != null)\n q.add(new MNode(curr.Node.left, curr.hDist -1, curr.level + 1));\n\n if(curr.Node.right != null)\n q.add(new MNode(curr.Node.right, curr.hDist +1, curr.level + 1));\n }\n\n List> ans = new ArrayList<>();\n for(Integer key: map.keySet()) {\n List temp = new ArrayList<>();\n while(!map.get(key).isEmpty()) { temp.add(map.get(key).poll().Node.val); }\n ans.add(new ArrayList<>(temp));\n }\n\n return ans;\n\n }\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\n // hd - horizontal distance\n // vertical order traversal starts from least hd to highest hd\n // on moving left hd decreases by 1, on moving right it increases by 1\n\n // should do level order traversal to get the nodes with same hd in correct order\n\n vector> verticalTraversal(TreeNode* root) {\n map> mp;\n queue> q;\n q.push({root,0});\n while(!q.empty()){\n int sz = q.size();\n map> temp;\n for(int i=0;ival);\n if(pr.first->left != NULL){\n q.push({pr.first->left,pr.second-1});\n }\n if(pr.first->right != NULL){\n q.push({pr.first->right,pr.second+1});\n }\n }\n for(auto pr:temp){\n for(auto val:pr.second){\n mp[pr.first].push_back(val);\n }\n }\n }\n vector> ans;\n for(auto pr:mp){\n vector temp;\n for(auto val:pr.second){\n temp.push_back(val);\n }\n ans.push_back(temp);\n }\n return ans;\n }\n};" }, { "title": "XOR Queries of a Subarray", "algo_input": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].\n\nFor each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).\n\nReturn an array answer where answer[i] is the answer to the ith query.\n\n \nExample 1:\n\nInput: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput: [2,7,14,8] \nExplanation: \nThe binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8\n\n\nExample 2:\n\nInput: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput: [8,0,4,4]\n\n\n \nConstraints:\n\n\n\t1 <= arr.length, queries.length <= 3 * 104\n\t1 <= arr[i] <= 109\n\tqueries[i].length == 2\n\t0 <= lefti <= righti < arr.length\n\n", "solution_py": "class Solution:\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n\n\n \"\"\"\n\n arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\n\n find pref xor of arr\n\n pref = [x,x,x,x]\n\n for each query find the left and right indices\n the xor for range (l, r) would be pref[r] xor pref[l-1]\n \n \"\"\" \n n, m = len(queries), len(arr)\n\n answer = [1]*n\n\n pref = [1]*m\n pref[0] = arr[0]\n if m > 1:\n for i in range(1,m):\n pref[i] = pref[i-1] ^ arr[i]\n\n for (i, (l,r)) in enumerate(queries):\n if l == 0: answer[i] = pref[r] \n else: answer[i] = pref[r] ^ pref[l-1]\n\n return answer", "solution_js": "var xorQueries = function(arr, queries) {\n let n = arr.length;\n \n while ((n & (n - 1)) != 0) {\n n++;\n }\n \n const len = n;\n const tree = new Array(len * 2).fill(0);\n \n build(tree, 1, 0, len - 1);\n \n const res = [];\n \n for (let i = 0; i < queries.length; i++) {\n const [start, end] = queries[i];\n \n const xor = query(tree, 1, 0, len - 1, start, end);\n \n res.push(xor);\n }\n \n \n return res;\n \n \n function build(tree, segmentIdx, segmentStart, segmentEnd) {\n if (segmentStart === segmentEnd) {\n tree[segmentIdx] = arr[segmentStart];\n return;\n }\n \n const mid = (segmentStart + segmentEnd) >> 1;\n build(tree, segmentIdx * 2, segmentStart, mid);\n build(tree, segmentIdx * 2 + 1, mid + 1, segmentEnd);\n \n tree[segmentIdx] = tree[segmentIdx * 2] ^ tree[segmentIdx * 2 + 1];\n\t\treturn;\n } \n \n \n function query(tree, node, nodeStart, nodeEnd, queryStart, queryEnd) {\n if (queryStart <= nodeStart && nodeEnd <= queryEnd) {\n return tree[node];\n } \n if (nodeEnd < queryStart || queryEnd < nodeStart) {\n return 0;\n }\n \n const mid = (nodeStart + nodeEnd) >> 1;\n \n const leftXor = query(tree, node * 2, nodeStart, mid, queryStart, queryEnd);\n const rightXor = query(tree, node * 2 + 1, mid + 1, nodeEnd, queryStart, queryEnd);\n \n return leftXor ^ rightXor;\n }\n};\n``", "solution_java": "class Solution\n{\n public int[] xorQueries(int[] arr, int[][] queries)\n {\n int[] ans = new int[queries.length];\n int[] xor = new int[arr.length];\n xor[0] = arr[0];\n // computing prefix XOR of arr\n for(int i = 1; i < arr.length; i++)\n {\n xor[i] = arr[i] ^ xor[i-1];\n }\n for(int i = 0; i < queries.length; i++)\n {\n // if query starts from something other than 0 (say i), then we XOR all values from arr[0] to arr[i-1]\n if(queries[i][0] != 0)\n {\n ans[i] = xor[queries[i][1]];\n for(int j = 0; j < queries[i][0]; j++)\n {\n ans[i] = arr[j] ^ ans[i];\n }\n }\n // if start of query is 0, then we striaght up use the prefix XOR till ith element\n else\n ans[i] = xor[queries[i][1]];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n \n // we know that (x ^ x) = 0,\n \n // arr = [1,4,8,3,7,8], let we have to calculate xor of subarray[2,4]\n \n // (1 ^ 4 ^ 8 ^ 3 ^ 7) ^ (1 ^ 4) = (8 ^ 3 ^ 7), this is nothing but prefix[right] ^ prefix[left - 1]\n \n // (1 ^ 1 = 0) and (4 ^ 4) = 0\n \n \n vector xorQueries(vector& arr, vector>& queries) {\n \n int n = queries.size();\n \n // find the prefix xor of arr\n \n for(int i = 1; i < arr.size(); i++)\n {\n arr[i] = (arr[i - 1] ^ arr[i]);\n }\n \n // calculate each query\n \n vector res(n);\n \n for(int i = 0; i < n; i++)\n {\n int left = queries[i][0];\n \n int right = queries[i][1];\n \n // find the xorr of the subarray\n \n int xorr = arr[right];\n \n if(left > 0)\n {\n xorr ^= arr[left - 1];\n }\n \n res[i] = xorr;\n }\n \n return res;\n }\n};" }, { "title": "Count Unguarded Cells in the Grid", "algo_input": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.\n\nA guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.\n\nReturn the number of unoccupied cells that are not guarded.\n\n \nExample 1:\n\nInput: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\nOutput: 7\nExplanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.\n\n\nExample 2:\n\nInput: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\nOutput: 4\nExplanation: The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.\n\n\n \nConstraints:\n\n\n\t1 <= m, n <= 105\n\t2 <= m * n <= 105\n\t1 <= guards.length, walls.length <= 5 * 104\n\t2 <= guards.length + walls.length <= m * n\n\tguards[i].length == walls[j].length == 2\n\t0 <= rowi, rowj < m\n\t0 <= coli, colj < n\n\tAll the positions in guards and walls are unique.\n\n", "solution_py": "class Solution:\n def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n dp = [[0] * n for _ in range(m)]\n for x, y in guards+walls:\n dp[x][y] = 1\n \n directions = [(0, 1), (1, 0), (-1, 0), (0, -1)]\n \n for x, y in guards:\n for dx, dy in directions:\n curr_x = x\n curr_y = y\n \n while 0 <= curr_x+dx < m and 0 <= curr_y+dy < n and dp[curr_x+dx][curr_y+dy] != 1:\n curr_x += dx\n curr_y += dy\n dp[curr_x][curr_y] = 2\n \n return sum(1 for i in range(m) for j in range(n) if dp[i][j] == 0) ", "solution_js": "var countUnguarded = function(m, n, guards, walls) {\n let board = new Array(m).fill(0).map(_=>new Array(n).fill(0))\n \n // 0 - Empty\n // 1 - Guard\n // 2 - Wall\n // 3 - Guard view\n \n const DIRECTIONS = [\n [-1, 0],\n [0, 1],\n [1, 0],\n [0, -1]\n ]\n \n for(let [guardRow, guardCol] of guards) board[guardRow][guardCol] = 1\n \n for(let [wallRow, wallCol] of walls) board[wallRow][wallCol] = 2\n \n for(let [guardRow, guardCol] of guards){\n //Loop through row with the same col\n //Go down from current row\n let row = guardRow + 1\n while(row < m){\n //Stop if you encounter a wall or guard\n if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break\n board[row][guardCol] = 3\n row++\n }\n //Go up from current row\n row = guardRow - 1\n while(row >= 0){\n if(board[row][guardCol] == 1 || board[row][guardCol] == 2) break\n board[row][guardCol] = 3\n row--\n }\n \n \n //Loop through col with the same row\n //Go right from current col\n let col = guardCol + 1\n while(col < n){\n if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break\n board[guardRow][col] = 3\n col++\n }\n \n //Go left from current col\n col = guardCol - 1\n while(col >= 0){\n if(board[guardRow][col] == 1 || board[guardRow][col] == 2) break\n board[guardRow][col] = 3\n col--\n }\n }\n \n\t//Count the free cells\n let freeCount = 0\n for(let i = 0; i < m; i++){\n for(let j = 0; j < n; j++){\n if(board[i][j] == 0) freeCount++\n }\n }\n \n return freeCount\n};", "solution_java": "class Solution\n{\n public int countUnguarded(int m, int n, int[][] guards, int[][] walls)\n {\n int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};\n char[][] grid= new char[m][n];\n int count = m*n - guards.length - walls.length;\n for(int[] wall : walls)\n {\n int x = wall[0], y = wall[1];\n grid[x][y] = 'W';\n }\n for(int[] guard : guards)\n {\n int x = guard[0], y = guard[1];\n grid[x][y] = 'G';\n }\n for(int[] point : guards)\n {\n for(int dir[] : dirs)\n {\n int x = point[0] + dir[0];\n int y = point[1] + dir[1];\n while(!(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 'G' || grid[x][y] == 'W'))\n {\n if(grid[x][y] != 'P')\n count--;\n grid[x][y] = 'P';\n x += dir[0];\n y += dir[1];\n }\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n void dfs( vector> &grid,int x,int y,int m,int n,int dir){\n if(x<0 || y<0 || x>=m || y>=n) return;\n if(grid[x][y]==2 || grid[x][y]==1) return;\n grid[x][y]=3;\n if(dir==1){\n dfs(grid,x+1,y,m,n,dir);\n }\n else if(dir==2){\n dfs(grid,x,y+1,m,n,dir);\n }\n else if(dir==3){\n dfs(grid,x-1,y,m,n,dir);\n }\n else{\n dfs(grid,x,y-1,m,n,dir);\n }\n }\n int countUnguarded(int m, int n, vector>& guards, vector>& walls) {\n vector> grid(m,vector(n,0));\n //marking guards\n for(int i=0;i bool:\n eligible = True\n\n for i in range(0, len(s)-2):\n if s[i:i+3] == \"LLL\":\n eligible = False\n absent = 0\n for i in range(len(s)):\n if s[i] == \"A\":\n absent +=1\n\n if absent>=2:\n eligible = False\n\n return(eligible)", "solution_js": "var checkRecord = function(s) {\n let absent = 0;\n let lates = 0;\n for (let i = 0; i < s.length; i++) {\n if(s[i] === 'L') {\n lates++;\n if(lates > 2) return false;\n } else {\n lates = 0;\n if(s[i] === 'A') {\n absent++;\n if(absent > 1) return false; \n }\n }\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean checkRecord(String s) {\n\n int size=s.length();\n if(s.replace(\"A\",\"\").length()<=size-2||s.indexOf(\"LLL\")!=-1)return false;\n\n return true;\n\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkRecord(string s);\n};\n/*********************************************************/\nbool Solution::checkRecord(string s) {\n int i, size = s.size(), maxL=0, countA=0, countL=0;\n for (i = 0; i < size; ++i) {\n if (s[i] == 'L') {\n ++countL;\n } else {\n countL = 0;\n }\n if (s[i] == 'A') {\n ++countA;\n }\n if (maxL < countL) {\n maxL = countL;\n }\n if( countA >= 2 || maxL >= 3) {\n return false;\n }\n }\n return true;\n}\n/*********************************************************/" }, { "title": "Get Equal Substrings Within Budget", "algo_input": "You are given two strings s and t of the same length and an integer maxCost.\n\nYou want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).\n\nReturn the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.\n\n \nExample 1:\n\nInput: s = \"abcd\", t = \"bcdf\", maxCost = 3\nOutput: 3\nExplanation: \"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.\n\n\nExample 2:\n\nInput: s = \"abcd\", t = \"cdef\", maxCost = 3\nOutput: 1\nExplanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.\n\n\nExample 3:\n\nInput: s = \"abcd\", t = \"acde\", maxCost = 0\nOutput: 1\nExplanation: You cannot make any change, so the maximum length is 1.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\tt.length == s.length\n\t0 <= maxCost <= 106\n\ts and t consist of only lowercase English letters.\n\n", "solution_py": "class Solution(object):\n def equalSubstring(self, s, t, maxCost):\n \"\"\"\n :type s: str\n :type t: str\n :type maxCost: int\n :rtype: int\n \"\"\"\n \n \n \n \n best = 0\n \n windowCost = 0\n l = 0\n for r in range(len(s)):\n \n windowCost += abs(ord(s[r]) - ord(t[r]))\n \n while windowCost > maxCost:\n \n windowCost -= abs(ord(s[l]) - ord(t[l]))\n l+=1\n \n best = max(best,r-l+1)\n \n return best\n \n \n ", "solution_js": "var equalSubstring = function(s, t, maxCost) {\n let dp = [], ans = 0;\n\n for (let i = 0, j = 0, k = 0; i < s.length; i++) {\n // overlay\n k += dp[i] = abs(s[i], t[i]);\n \n // non first\n if (k > maxCost) {\n k -= dp[j], j++;\n continue;\n }\n \n // eligible\n ans++;\n }\n\n return ans;\n\n // get abs value\n function abs(a, b) {\n return Math.abs(a.charCodeAt(0) - b.charCodeAt(0));\n }\n};", "solution_java": "class Solution {\n public int equalSubstring(String s, String t, int maxCost) {\n int ans =0;\n int tempcost =0;\n int l =0 ;\n int r= 0 ;\n for(;r!=s.length();r++){\n tempcost += Math.abs(s.charAt(r)-t.charAt(r));\n while(tempcost>maxCost){\n tempcost -= Math.abs(s.charAt(l)-t.charAt(l));\n l++;\n }\n ans =Math.max(ans,r+1-l);\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int equalSubstring(string s, string t, int maxCost) {\n int l = 0, r = 0, currCost = 0, n = s.length(), maxLen = 0;\n\n while(r < n) {\n currCost += abs(s[r] - t[r]);\n r++;\n\n while(currCost > maxCost) {\n currCost -= abs(s[l] - t[l]);\n l++;\n }\n\n maxLen = max(r - l, maxLen);\n }\n\n return maxLen;\n }\n};" }, { "title": "Maximum Repeating Substring", "algo_input": "For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.\n\nGiven strings sequence and word, return the maximum k-repeating value of word in sequence.\n\n \nExample 1:\n\nInput: sequence = \"ababc\", word = \"ab\"\nOutput: 2\nExplanation: \"abab\" is a substring in \"ababc\".\n\n\nExample 2:\n\nInput: sequence = \"ababc\", word = \"ba\"\nOutput: 1\nExplanation: \"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".\n\n\nExample 3:\n\nInput: sequence = \"ababc\", word = \"ac\"\nOutput: 0\nExplanation: \"ac\" is not a substring in \"ababc\". \n\n\n \nConstraints:\n\n\n\t1 <= sequence.length <= 100\n\t1 <= word.length <= 100\n\tsequence and word contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n if word not in sequence:\n return 0\n\n left = 1\n right = len(sequence) // len(word)\n while left <= right:\n mid = (left + right) // 2\n if word * mid in sequence:\n left = mid + 1\n else:\n right = mid - 1\n\n return left - 1", "solution_js": "var maxRepeating = function(sequence, word) {\n\tlet result = 0;\n\n\twhile (sequence.includes(word.repeat(result + 1))) {\n\t\tresult += 1;\n\t};\n\treturn result;\n};", "solution_java": "class Solution {\n public int maxRepeating(String s, String w) {\n if(w.length()>s.length()) return 0;\n int ans=0;\n StringBuilder sb=new StringBuilder(\"\");\n while(sb.length()<=s.length()){\n sb.append(w);\n if(s.contains(sb)) ans++;\n else break;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n\tint maxRepeating(string sequence, string word) {\n\t\tint k = 0;\n\t\tstring temp = word;\n\n\t\twhile(sequence.find(temp) != string::npos){\n\t\t\ttemp += word;\n\t\t\tk++;\n\t\t}\n\n\t\treturn k;\n\t}\n};" }, { "title": "Count Square Sum Triples", "algo_input": "A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.\n\nGiven an integer n, return the number of square triples such that 1 <= a, b, c <= n.\n\n \nExample 1:\n\nInput: n = 5\nOutput: 2\nExplanation: The square triples are (3,4,5) and (4,3,5).\n\n\nExample 2:\n\nInput: n = 10\nOutput: 4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).\n\n\n \nConstraints:\n\n\n\t1 <= n <= 250\n\n", "solution_py": "class Solution:\n def countTriples(self, n: int) -> int:\n c = 0\n for i in range(1, n+1):\n for j in range(i+1, n+1):\n sq = i*i + j*j\n r = int(sq ** 0.5)\n if ( r*r == sq and r <= n ):\n c +=2\n return c", "solution_js": "var countTriples = function(n) {\n let count = 0;\n for (let i=1; i < n; i++) {\n for (let j=1; j < n; j++) {\n let root = Math.sqrt(j*j + i*i)\n if (Number.isInteger(root) && root <= n) {\n count++\n }\n }\n }\n\n return count\n};", "solution_java": "class Solution {\n public int countTriples(int n) {\n int c = 0;\n for(int i=1 ; i<=n ; i++){\n for(int j=i+1 ; j<=n ; j++){\n int sq = ( i * i) + ( j * j);\n int r = (int) Math.sqrt(sq);\n if( r*r == sq && r <= n )\n c += 2;\n }\n }\n return c;\n }\n}", "solution_c": "class Solution {\npublic:\n int countTriples(int n) {\n int res = 0;\n for (int a = 3, sqa; a < n; a++) {\n sqa = a * a;\n for (int b = 3, sqc, c; b < n; b++) {\n sqc = sqa + b * b;\n c = sqrt(sqc);\n if (c > n) break;\n res += c * c == sqc;\n }\n }\n return res;\n }\n};" }, { "title": "Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", "algo_input": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:\n\n\n\thorizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and\n\tverticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.\n\n\nReturn the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.\n\n \nExample 1:\n\nInput: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput: 4 \nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.\n\n\nExample 2:\n\nInput: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput: 6\nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.\n\n\nExample 3:\n\nInput: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput: 9\n\n\n \nConstraints:\n\n\n\t2 <= h, w <= 109\n\t1 <= horizontalCuts.length <= min(h - 1, 105)\n\t1 <= verticalCuts.length <= min(w - 1, 105)\n\t1 <= horizontalCuts[i] < h\n\t1 <= verticalCuts[i] < w\n\tAll the elements in horizontalCuts are distinct.\n\tAll the elements in verticalCuts are distinct.\n\n", "solution_py": "class Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n horizontalCuts.sort()\n verticalCuts.sort()\n \n mxHr = 0\n prev = 0\n for i in horizontalCuts:\n mxHr = max(mxHr, i-prev)\n prev = i\n mxHr = max(mxHr, h-horizontalCuts[-1])\n \n mxVr = 0\n prev = 0\n for i in verticalCuts:\n mxVr = max(mxVr, i-prev)\n prev = i\n mxVr = max(mxVr, w-verticalCuts[-1])\n \n return (mxHr * mxVr) % ((10 ** 9) + 7)", "solution_js": "var maxArea = function(h, w, horizontalCuts, verticalCuts) {\n horizontalCuts.sort((a,b) => a-b)\n verticalCuts.sort((a,b) => a-b)\n let max_hor_dis = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length-1])\n let max_ver_dis = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length-1])\n for(let i=1; i hMax)\n hMax= h-horizontalCuts[horizontalCuts.length-1];\n int vMax=verticalCuts[0];\n for(i=1;i vMax)\n vMax= w-verticalCuts[verticalCuts.length-1];\n return (int)((long)hMax*vMax%1000000007);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxArea(int h, int w, vector& horizontalCuts, vector& verticalCuts) {\n int mod = 1e9 + 7;\n sort(horizontalCuts.begin(), horizontalCuts.end());\n sort(verticalCuts.begin(), verticalCuts.end());\n // cout << 1;\n horizontalCuts.push_back(h);\n verticalCuts.push_back(w);\n // cout << 1;\n int prev = 0;\n int vert = INT_MIN, hori = INT_MIN;\n for(int i = 0; i < verticalCuts.size(); i++)\n {\n if(vert < verticalCuts[i]-prev)\n vert = verticalCuts[i]-prev;\n prev = verticalCuts[i];\n }\n //cout << 1;\n prev = 0;\n for(int i = 0; i < horizontalCuts.size(); i++)\n {\n if(hori < horizontalCuts[i]-prev)\n hori = horizontalCuts[i]-prev;\n prev = horizontalCuts[i];\n }\n return ((long long)vert*hori) % mod;\n }\n};" }, { "title": "Expressive Words", "algo_input": "Sometimes people repeat letters to represent extra feeling. For example:\n\n\n\t\"hello\" -> \"heeellooo\"\n\t\"hi\" -> \"hiiii\"\n\n\nIn these strings like \"heeellooo\", we have groups of adjacent letters that are all the same: \"h\", \"eee\", \"ll\", \"ooo\".\n\nYou are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.\n\n\n\tFor example, starting with \"hello\", we could do an extension on the group \"o\" to get \"hellooo\", but we cannot get \"helloo\" since the group \"oo\" has a size less than three. Also, we could do another extension like \"ll\" -> \"lllll\" to get \"helllllooo\". If s = \"helllllooo\", then the query word \"hello\" would be stretchy because of these two extension operations: query = \"hello\" -> \"hellooo\" -> \"helllllooo\" = s.\n\n\nReturn the number of query strings that are stretchy.\n\n \nExample 1:\n\nInput: s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\nOutput: 1\nExplanation: \nWe can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.\n\n\nExample 2:\n\nInput: s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= s.length, words.length <= 100\n\t1 <= words[i].length <= 100\n\ts and words[i] consist of lowercase letters.\n\n", "solution_py": "class Solution:\n def expressiveWords(self, s: str, words: List[str]) -> int:\n # edge cases\n if len(s) == 0 and len(words) != 0:\n return False\n if len(words) == 0 and len(s) != 0:\n return False\n if len(s) == 0 and len(words) == 0:\n return True\n \n # helper function, compressing string and extract counts\n def compressor(s_word):\n init_string =[s_word[0]]\n array = []\n start = 0\n for i,c in enumerate(s_word):\n if c == init_string[-1]:\n continue\n array.append(i-start)\n start = i\n init_string += c \n array.append(i-start+1) \n return init_string,array\n\n res = len(words)\n s_split, s_array = compressor(s)\n for word in words:\n word_split = ['']\n word_array = []\n word_split,word_array = compressor(word)\n if s_split == word_split:\n for num_s,num_word in zip(s_array,word_array):\n if num_s != num_word and num_s < 3 or num_word > num_s:\n res -= 1\n break\n else:\n res -= 1\n return res", "solution_js": "/**\n * @param {string} s\n * @param {string[]} words\n * @return {number}\n */\nvar expressiveWords = function(s, words) {\n let arr = [];\n let curr = 0\n while(curr < s.length){\n let count = 1\n while(s[curr] === s[curr+1]){\n count++;\n curr++\n }\n arr.push([s[curr] , count]);\n curr++\n }\n let ans = 0\n for(let charArr of words){\n let idx = 0;\n let i = 0;\n let flag = true;\n if(charArr.length > s.length)continue\n\n while( i < charArr.length ){\n let count = 1\n while(charArr[i] === charArr[i+1]){\n i++;\n count++\n }\n if(arr[idx][0] !== charArr[i] || arr[idx][1] < count || (arr[idx][1] <3 && arr[idx][1] !== count) ){\n flag = false;\n break\n }\n idx++;\n i++\n\n }\n if(idx !== arr.length)flag = false\n if(flag)ans++\n }\n return ans\n};", "solution_java": "class Solution {\n private String getFreqString(String s) {\n int len = s.length();\n StringBuilder freqString = new StringBuilder();\n int currFreq = 1;\n char prevChar = s.charAt(0);\n freqString.append(s.charAt(0));\n for(int i = 1; i0) {\n freqString.append(currFreq);\n }\n \n return freqString.toString();\n }\n \n private boolean isGreaterButLessThanThree(char sChar, char wChar) { \n return sChar > wChar && sChar < '3';\n }\n \n private boolean isStretchy(String s, String word) { \n int sLen = s.length();\n int wordLen = word.length();\n \n if(sLen != wordLen) {\n return false;\n }\n \n for(int i = 0; i& sMap) {\n if(s == t) return true; \n if(s.size() < t.size()) return false; // If t is bigger than the original string, return false since we can't take away characters. \n int p1 = 0; // The first pointer will point to a char in our original string. \n int p2 = 0; // The second pointer will point to a char in the word we want to stretch. \n \n // Loop though the target string since we know it was to be either the same length or longer. i.e. \"heeellooo\" is longer than \"hello\". \n while(p1 < s.size()) {\n if(!sMap.count(t[p2])) return false; // If we find a char in the word we want to stretch that's not even in our original string, we return false since we cannot remove chars. \n int want = getRepeatedLen(s,p1); // For every new char we encounter we check how many are in the orignal string. \n int have = getRepeatedLen(t,p2); \n if( have > want) return false; // Remember can't delete chars. \n int needToAdd = want - have; \n if(want != have && needToAdd + have < 3) return false; // If we need to add some chars, we have to also check if the new group size that we create follows our rules of being greater or equal to 3. \n p1 += want; // We don't want to repeat a char again. \n p2 += have; // Same as above but for the other word. \n }\n return true; \n }\n \n int expressiveWords(string s, vector& words) {\n int res = 0; \n unordered_set sMap(s.begin(),s.end()); // Useful to know what characters exits in the first place. \n // Basically loop through every word in the vector and check if it is stretchy. \n for(string& w : words) {\n if(isStretchy(s,w,sMap)) res++; \n }\n return res;\n }\n};" }, { "title": "Maximum Subarray", "algo_input": "Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nA subarray is a contiguous part of an array.\n\n \nExample 1:\n\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\n\n\nExample 2:\n\nInput: nums = [1]\nOutput: 1\n\n\nExample 3:\n\nInput: nums = [5,4,-1,7,8]\nOutput: 23\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\n\n \nFollow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.\n", "solution_py": "class Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n def kadane(i):\n if F[i] != None:\n return F[i]\n F[i] = max(nums[i],kadane(i-1) + nums[i])\n return F[i]\n n = len(nums)\n F = [None for _ in range(n)]\n F[0] = nums[0]\n kadane(n-1)\n return max(F)", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\n var maxSubArray = function(nums) {\n let max = Number.MIN_SAFE_INTEGER;\n let curr = 0;\n for (let i = 0; i < nums.length; i++) {\n if (curr < 0 && nums[i] > curr) {\n curr = 0;\n }\n curr += nums[i];\n max = Math.max(max, curr);\n }\n return max;\n}; ", "solution_java": "class Solution {\n public int maxSubArray(int[] nums) {\n int n = nums.length;\n int currmax = 0;\n int gmax = nums[0];\n for(int i=0;i& nums)\n {\n int m = INT_MIN, sm = 0;\n for (int i = 0; i < nums.size(); ++i)\n {\n sm += nums[i];\n m = max(sm, m);\n if (sm < 0) sm = 0;\n }\n return m;\n }\n};" }, { "title": "Minimum Cost to Make at Least One Valid Path in a Grid", "algo_input": "Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:\n\n\n\t1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])\n\t2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])\n\t3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])\n\t4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])\n\n\nNotice that there could be some signs on the cells of the grid that point outside the grid.\n\nYou will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.\n\nYou can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.\n\nReturn the minimum cost to make the grid have at least one valid path.\n\n \nExample 1:\n\nInput: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\nOutput: 3\nExplanation: You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.\n\n\nExample 2:\n\nInput: grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput: 0\nExplanation: You can follow the path from (0, 0) to (2, 2).\n\n\nExample 3:\n\nInput: grid = [[1,2],[4,3]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 100\n\t1 <= grid[i][j] <= 4\n\n", "solution_py": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n changes = [[float(\"inf\") for _ in range(len(grid[0]))] for _ in range(len(grid))]\n heap = [(0,0,0)]\n dirn = [(0,1),(0,-1),(1,0),(-1,0)]\n while heap:\n dist,r,c = heapq.heappop(heap)\n if r >= len(grid) or r < 0 or c >= len(grid[0]) or c < 0 or changes[r][c] <= dist:\n continue\n if r == len(grid) - 1 and c == len(grid[0]) - 1:\n return dist\n changes[r][c] = dist\n for i in range(1,5):\n if i == grid[r][c]:\n heapq.heappush(heap,(dist,r+dirn[i-1][0],c+dirn[i-1][1]))\n else:\n heapq.heappush(heap,(dist+1,r+dirn[i-1][0],c+dirn[i-1][1]))\n return dist\n ", "solution_js": "const minCost = function (grid) {\n\tconst m = grid.length,\n\t\tn = grid[0].length,\n\t\tcheckPos = (i, j) =>\n\t\t\ti > -1 && j > -1 && i < m && j < n && !visited[i + \",\" + j],\n\t\tdir = { 1: [0, 1], 2: [0, -1], 3: [1, 0], 4: [-1, 0] },\n\t\tdfs = (i, j) => {\n\t\t\tif (!checkPos(i, j)) return false;\n\t\t\tif (i === m - 1 && j === n - 1) return true;\n\t\t\tvisited[i + \",\" + j] = true;\n\t\t\tnext.push([i, j]);\n\t\t\treturn dfs(i + dir[grid[i][j]][0], j + dir[grid[i][j]][1]);\n\t\t},\n\t\tvisited = {};\n\tlet changes = 0, cur = [[0, 0]], next;\n\twhile (cur.length) {\n\t\tnext = [];\n\t\tfor (const [i, j] of cur) if (dfs(i, j)) return changes;\n\t\tchanges++;\n\t\tcur = [];\n\t\tnext.forEach(pos => {\n\t\t\tfor (let d = 1; d < 5; d++) {\n\t\t\t\tconst x = pos[0] + dir[d][0],\n\t\t\t\t\ty = pos[1] + dir[d][1];\n\t\t\t\tif (checkPos(x, y)) cur.push([x, y]);\n\t\t\t}\n\t\t});\n\t}\n};", "solution_java": "class Solution {\n\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n\n private boolean isValid(int i,int j,int n,int m) {\n return i=0 && j>=0;\n }\n\n private boolean isValidDirection(int [][]grid,int []currEle,int nx,int ny) {\n int nextX=currEle[0],nextY = currEle[1];\n int n =grid.length,m = grid[0].length;\n\n switch(grid[currEle[0]][currEle[1]]) {\n case 1: nextY++; break;\n case 2: nextY--; break;\n case 3: nextX++; break;\n case 4: nextX--; break;\n }\n\n return nextX==nx && nextY==ny;\n }\n\n public int minCost(int[][] grid) {\n\n int n = grid.length;\n int m = grid[0].length;\n\n int dist[][] = new int[n][m];\n boolean vis[][] = new boolean[n][m];\n\n LinkedList queue = new LinkedList<>(); // for performing 01 BFS\n\n for(int i=0;i\n\nclass Solution {\npublic:\n\n int dx[4]={0 , 0, 1 , -1};\n int dy[4]={1 , -1 , 0 , 0};\n\n int minCost(vector>& grid) {\n\n int m=grid.size();\n int n=grid[0].size();\n\n priority_queue< vv , vector , greater> pq;\n\n vector> dp(m+3 , vector(n+3 , INT_MAX));\n\n dp[0][0]=0;\n pq.push({0 , 0 , 0});\n\n // there is no need of visited\n\n // distance or u can say cost relaxation\n\n while(!pq.empty())\n {\n\n auto v=pq.top();\n pq.pop();\n\n int cost=v[0];\n int i=v[1];\n int j=v[2];\n\n if(i==m-1 && j==n-1)\n {\n return cost;\n }\n\n for(int k=0;k<4;k++)\n {\n int newi=i+dx[k];\n int newj=j+dy[k];\n\n if(newi>=0 && newj>=0 && newicost)\n {\n dp[newi][newj]=cost;\n pq.push({cost , newi , newj});\n }\n }\n else\n {\n if(dp[newi][newj]>cost+1)\n {\n dp[newi][newj]=cost+1;\n pq.push({cost+1 , newi , newj});\n }\n }\n }\n }\n\n }\n\n if(dp[m-1][n-1]!=INT_MAX)\n {\n return dp[m-1][n-1];\n }\n\n return -1;\n\n }\n};" }, { "title": "Sum Game", "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nYou are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:\n\n\n\tChoose an index i where num[i] == '?'.\n\tReplace num[i] with any digit between '0' and '9'.\n\n\nThe game ends when there are no more '?' characters in num.\n\nFor Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.\n\n\n\tFor example, if the game ended with num = \"243801\", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = \"243803\", then Alice wins because 2+4+3 != 8+0+3.\n\n\nAssuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.\n\n \nExample 1:\n\nInput: num = \"5023\"\nOutput: false\nExplanation: There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.\n\n\nExample 2:\n\nInput: num = \"25??\"\nOutput: true\nExplanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.\n\n\nExample 3:\n\nInput: num = \"?3295???\"\nOutput: false\nExplanation: It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.\n\n\n \nConstraints:\n\n\n\t2 <= num.length <= 105\n\tnum.length is even.\n\tnum consists of only digits and '?'.\n\n", "solution_py": "class Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n q_cnt_1 = s1 = 0\n for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n if num[i] == '?':\n q_cnt_1 += 1\n else:\n s1 += int(num[i])\n q_cnt_2 = s2 = 0\n for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n if num[i] == '?':\n q_cnt_2 += 1\n else:\n s2 += int(num[i])\n s_diff = s1 - s2 # calculate sum difference and question mark difference\n q_diff = q_cnt_2 - q_cnt_1\n return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins", "solution_js": "/**\n * @param {string} num\n * @return {boolean}\n */\nvar sumGame = function(num) {\n \n function getInfo(s) {\n var sum = 0;\n var ques = 0;\n for(let c of s.split(''))\n if (c !== '?') sum += c - 0;\n else ques++;\n return [sum, ques];\n }\n \n function check(sum1, sum2, q1, q2, q) {\n return sum1 + 9* Math.min(q/2, q1) > sum2 + 9 * Math.min(q/2, q2);\n }\n \n \n var q = getInfo(num)[1];\n var [sum1, q1] = getInfo(num.substring(0, Math.floor(num.length/2)));\n var [sum2, q2] = getInfo(num.substring(Math.floor(num.length/2), num.length));\n if (sum1 < sum2) { \n [sum1, sum2] = [sum2, sum1];\n [q1, q2] = [q2, q1];\n }\n \n return check(sum1, sum2, q1, q2, q) || check(sum2, sum1, q2, q1, q);\n};", "solution_java": "class Solution {\n public boolean sumGame(String num) {\n int q = 0, d = 0, n = num.length();\n for (int i = 0; i < n; i++){\n if (num.charAt(i) == '?'){\n q += 2* i < n? 1 : -1;\n }else{\n d += (2 * i < n? 1 : -1) * (num.charAt(i) - '0');\n }\n }\n return (q & 1) > 0 || q * 9 + 2 * d != 0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool sumGame(string num) {\n const int N = num.length();\n \n int lDigitSum = 0;\n int lQCount = 0;\n int rDigitSum = 0;\n int rQCount = 0;\n \n for(int i = 0; i < N; ++i){\n if(isdigit(num[i])){\n if(i < N / 2){\n lDigitSum += (num[i] - '0');\n }else{\n rDigitSum += (num[i] - '0');\n }\n }else{\n if(i < N / 2){\n ++lQCount;\n }else{\n ++rQCount;\n }\n }\n }\n \n // Case 0: Only digits (without '?')\n if((lQCount + rQCount) == 0){\n return (lDigitSum != rDigitSum);\n }\n \n // Case 1: Odd number of '?'\n if((lQCount + rQCount) % 2 == 1){\n return true;\n }\n \n // Case 2: Even number of '?'\n int minQCount = min(lQCount, rQCount);\n lQCount -= minQCount;\n rQCount -= minQCount;\n return (lDigitSum + 9 * lQCount / 2 != rDigitSum + 9 * rQCount / 2);\n }\n};" }, { "title": "Number of Arithmetic Triplets", "algo_input": "You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:\n\n\n\ti < j < k,\n\tnums[j] - nums[i] == diff, and\n\tnums[k] - nums[j] == diff.\n\n\nReturn the number of unique arithmetic triplets.\n\n \nExample 1:\n\nInput: nums = [0,1,4,6,7,10], diff = 3\nOutput: 2\nExplanation:\n(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. \n\n\nExample 2:\n\nInput: nums = [4,5,6,7,8,9], diff = 2\nOutput: 2\nExplanation:\n(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.\n\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 200\n\t0 <= nums[i] <= 200\n\t1 <= diff <= 50\n\tnums is strictly increasing.\n\n", "solution_py": "class Solution:\n def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n \n ans = 0\n n = len(nums)\n for i in range(n):\n if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n ans += 1\n \n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} diff\n * @return {number}\n */\nvar arithmeticTriplets = function(nums, diff) {\n count = 0\n for(let i = 0; i < nums.length - 2; i++){\n for(let j = i + 1; j < nums.length - 1; j++){\n for(let k = j + 1; k < nums.length; k++){\n if(i < j && j < k && nums[j] - nums[i] === diff && nums[k] - nums[j] === diff){\n count++\n }\n }\n }\n }\n return count\n};", "solution_java": "class Solution {\n public int arithmeticTriplets(int[] nums, int diff) {\n int result = 0;\n int[] map = new int[201];\n\n for(int num: nums) {\n map[num] = 1;\n\n if(num - diff >= 0) {\n map[num] += map[num - diff];\n }\n\n if(map[num] >= 3) result += 1;\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int arithmeticTriplets(vector& nums, int diff) {\n int ans=0;\n for(int i=0;i List[str]:\n \n mapping = {\"2\": \"abc\",\n \"3\": \"def\",\n \"4\": \"ghi\",\n \"5\": \"jkl\",\n \"6\": \"mno\",\n \"7\": \"pqrs\",\n \"8\": \"tuv\",\n \"9\": \"wxyz\"}\n \n ans = []\n first = True\n for i in range(len(digits)):\n \n # mult: times we should print each digit\n mult = 1 \n for j in range(i+1, len(digits)):\n mult *= len(mapping[digits[j]])\n \n # cycles: times we should run same filling cycle\n if not first:\n cycles = len(ans) // mult\n else:\n cycles = 1\n if times > 1:\n cycles //= len(mapping[digits[i]])\n \n # cyclically adding each digits to answer\n answer_ind = 0 \n for _ in range(cycles):\n for char in mapping[digits[i]]:\n for __ in range(mult):\n if first:\n ans.append(char)\n else:\n ans[answer_ind] += char\n answer_ind += 1\n if first:\n first = False\n \n return ans", "solution_js": "var letterCombinations = function(digits) {\n if(!digits) return []\n let res = []\n const alpha = {\n 2: \"abc\",\n 3: \"def\",\n 4: \"ghi\",\n 5: \"jkl\",\n 6: \"mno\",\n 7: \"pqrs\",\n 8: \"tuv\",\n 9: \"wxyz\"\n }\n \n const dfs = (i, digits, temp)=>{\n if(i === digits.length){\n res.push(temp.join(''))\n return\n }\n \n let chars = alpha[digits[i]]\n for(let ele of chars){\n temp.push(ele)\n dfs(i+1, digits, temp)\n temp.pop()\n }\n }\n dfs(0, digits, [])\n return res\n};", "solution_java": "class Solution {\n String[] num = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n public List letterCombinations(String digits) {\n List ll = new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n if (digits.length() != 0) {\n combination(digits.toCharArray(), ll, sb, 0);\n }\n return ll;\n }\n public void combination(char[] digits, List ll, StringBuilder sb, int idx) {\n \n if (sb.length() == digits.length) {\n ll.add(sb.toString());\n return;\n }\n \n String grp = num[digits[idx] - 48];\n for (int i = 0; i < grp.length(); i++) {\n sb.append(grp.charAt(i));\n combination(digits, ll, sb, idx + 1);\n sb.deleteCharAt(sb.length() - 1);\n }\n \n }\n}", "solution_c": "class Solution {\npublic:\n\n void solve(string digit,string output,int index,vector&ans,string mapping[])\n { // base condition\n if(index>=digit.length())\n {\n ans.push_back(output);\n return;\n }\n // digit[index] gives character value to change in integer subtract '0'\n int number=digit[index]-'0';\n // get the string at perticular index in mapping\n string value=mapping[number];\n //runs loop in value string and push that value in out put string ans do recursive call for next index\n for(int i=0;i letterCombinations(string digits) {\n\n vectorans;\n //if it is empty input string\n if(digits.length()==0)\n {\n return ans;\n }\n string output=\"\";\n int index=0;\n //map every index with string\n string mapping[10]={\"\",\"\",\"abc\",\"def\",\"ghi\",\"jkl\",\"mno\",\"pqrs\",\"tuv\",\"wxyz\"};\n solve(digits,output,index,ans,mapping);\n return ans;\n }\n};" }, { "title": "Number of Sets of K Non-Overlapping Line Segments", "algo_input": "Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.\n\nReturn the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 4, k = 2\nOutput: 5\nExplanation: The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.\n\n\nExample 2:\n\nInput: n = 3, k = 1\nOutput: 3\nExplanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.\n\n\nExample 3:\n\nInput: n = 30, k = 7\nOutput: 796297179\nExplanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 1000\n\t1 <= k <= n-1\n\n", "solution_py": "class Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n MOD = 10**9 + 7\n @lru_cache(None)\n def dp(i, k, isStart):\n if k == 0: return 1 # Found a way to draw k valid segments\n if i == n: return 0 # Reach end of points\n ans = dp(i+1, k, isStart) # Skip ith point\n if isStart:\n ans += dp(i+1, k, False) # Take ith point as start\n else:\n ans += dp(i, k-1, True) # Take ith point as end\n return ans % MOD\n return dp(0, k, True)", "solution_js": "var numberOfSets = function(n, k) {\n return combinations(n+k-1,2*k)%(1e9+7)\n};\nvar combinations=(n,k)=>{\n var dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>1))\n for (let i = 1; i <=n; i++) \n for (let k = 1; k > &dp, vector> &sumDp)\n {\n if(n < 2)\n return 0;\n \n if(sumDp[n][k] != -1)\n return sumDp[n][k];\n \n sumDp[n][k] = ((sumDyp(n-1, k, dp, sumDp)%MOD) + (dyp(n, k, dp, sumDp)%MOD))%MOD;\n return sumDp[n][k];\n }\n \n int dyp(int n, int k, vector> &dp, vector> &sumDp)\n {\n if(n < 2)\n return 0;\n \n if(dp[n][k] != -1)\n return dp[n][k];\n \n if(k == 1)\n {\n dp[n][k] = ((((n-1)%MOD) * (n%MOD))%MOD)/2;\n return dp[n][k];\n }\n \n \n int ans1 = dyp(n-1, k, dp, sumDp);\n int ans2 = sumDyp(n-1, k-1, dp, sumDp);\n \n int ans = ((ans1%MOD) + (ans2%MOD))%MOD;\n dp[n][k] = ans;\n return ans;\n }\n \n int numberOfSets(int n, int k) \n {\n vector> dp(n+1, vector(k+1, -1));\n vector> sumDp(n+1, vector(k+1, -1));\n return dyp(n, k, dp, sumDp);\n }\n};" }, { "title": "Display Table of Food Orders in a Restaurant", "algo_input": "Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.\n\nReturn the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.\n\n \nExample 1:\n\nInput: orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]\nOutput: [[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]] \nExplanation:\nThe displaying table looks like:\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\n3 ,0 ,2 ,1 ,0\n5 ,0 ,1 ,0 ,1\n10 ,1 ,0 ,0 ,0\nFor the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\nFor the table 5: Carla orders \"Water\" and \"Ceviche\".\nFor the table 10: Corina orders \"Beef Burrito\". \n\n\nExample 2:\n\nInput: orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]\nOutput: [[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]] \nExplanation: \nFor the table 1: Adam and Brianna order \"Canadian Waffles\".\nFor the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".\n\n\nExample 3:\n\nInput: orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]\nOutput: [[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]\n\n\n \nConstraints:\n\n\n\t1 <= orders.length <= 5 * 10^4\n\torders[i].length == 3\n\t1 <= customerNamei.length, foodItemi.length <= 20\n\tcustomerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.\n\ttableNumberi is a valid integer between 1 and 500.\n", "solution_py": "class Solution:\n def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n column = ['Table']\n dish = []\n table_dict = {}\n for order_row in orders : \n if order_row[-1] not in dish :\n dish.append(order_row[-1])\n \n for order_row in orders :\n if order_row[1] not in table_dict.keys() :\n table_dict[order_row[1]] = {}\n for food in dish : \n table_dict[order_row[1]][food] = 0 \n table_dict[order_row[1]][order_row[-1]] += 1\n else : \n table_dict[order_row[1]][order_row[-1]] += 1 \n \n dish.sort()\n column = column + dish \n ans = [column]\n table = []\n childDict = {}\n for key in sorted(table_dict.keys()) : \n table.append(int(key))\n childDict[key] = []\n for value in column : \n if value != 'Table' :\n childDict[key].append(str(table_dict[key][value]))\n table.sort()\n output = [ans[0]]\n for table_num in table : \n childList = [str(table_num)]\n output.append(childList + childDict[str(table_num)])\n return output ", "solution_js": "var displayTable = function(orders) {\n var mapOrders = {};\n var tables = [];\n var dishes = [];\n for(var i=0;i> displayTable(List> orders) {\n List> ans = new ArrayList<>();\n List head = new ArrayList<>();\n head.add(\"Table\");\n Map> map = new TreeMap<>();\n for(List s: orders){\n if(!head.contains(s.get(2))) head.add(s.get(2));\n int tbl = Integer.parseInt(s.get(1));\n map.putIfAbsent(tbl, new TreeMap<>());\n if(map.get(tbl).containsKey(s.get(2))){\n Map m = map.get(tbl);\n m.put(s.get(2), m.getOrDefault(s.get(2), 0)+1);\n }else{\n map.get(tbl).put(s.get(2), 1);\n }\n }\n String[] arr = head.toArray(new String[0]);\n Arrays.sort(arr, 1, head.size());\n head = Arrays.asList(arr);\n ans.add(head);\n\n for(Map.Entry> entry: map.entrySet()){\n List l = new ArrayList<>();\n l.add(entry.getKey() + \"\");\n Map m = entry.getValue();\n for(int i=1; i> displayTable(vector>& orders) {\n\n\n\n vector>ans;\n\n map>m;\n\n sets; //Sets are useful as they dont contain duplicates as well arranges the strings in order.\n\n for(auto row:orders)\n\n {\n\n s.insert(row[2]);\n\n m[stoi(row[1])][row[2]]++;\n\n }\n\n\n\n vectordem;\n\n dem.push_back(\"Table\");\n\n for(auto a:s)\n\n {\n\n dem.push_back(a);\n\n }//For the first row only\n\n\n\n ans.push_back(dem);\n\n for(auto it:m)\n\n {\n\n vectorrow;\n\n row.push_back(to_string(it.first));\n\n auto dummy=it.second;\n\n for(auto st:s)//we use set here as it has food names stored in asc order.\n\n {\n\n row.push_back(to_string(dummy[st]));//we access the number of orders.\n\n }\n\n\n\n ans.push_back(row);\n\n\n\n }\n\n\n\n return ans;\n\n\n\n\n\n }\n\n};" }, { "title": "Brace Expansion II", "algo_input": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.\n\nThe grammar can best be understood through simple examples:\n\n\n\tSingle letters represent a singleton set containing that word.\n\t\n\t\tR(\"a\") = {\"a\"}\n\t\tR(\"w\") = {\"w\"}\n\t\n\t\n\tWhen we take a comma-delimited list of two or more expressions, we take the union of possibilities.\n\t\n\t\tR(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}\n\t\tR(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)\n\t\n\t\n\tWhen we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.\n\t\n\t\tR(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}\n\t\tR(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}\n\t\n\t\n\n\nFormally, the three rules for our grammar:\n\n\n\tFor every lowercase letter x, we have R(x) = {x}.\n\tFor expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...\n\tFor expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, where + denotes concatenation, and × denotes the cartesian product.\n\n\nGiven an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n\n \nExample 1:\n\nInput: expression = \"{a,b}{c,{d,e}}\"\nOutput: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n\n\nExample 2:\n\nInput: expression = \"{{a,z},a{b,c},{ab,z}}\"\nOutput: [\"a\",\"ab\",\"ac\",\"z\"]\nExplanation: Each distinct word is written only once in the final answer.\n\n\n \nConstraints:\n\n\n\t1 <= expression.length <= 60\n\texpression[i] consists of '{', '}', ','or lowercase English letters.\n\tThe given expression represents a set of words based on the grammar given in the description.\n\n", "solution_py": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n s = list(reversed(\"{\" + expression + \"}\"))\n \n def full_word(): \n cur = [] \n while s and s[-1].isalpha(): \n cur.append(s.pop()) \n return \"\".join(cur)\n \n def _expr(): \n res = set() \n if s[-1].isalpha(): \n res.add(full_word()) \n elif s[-1] == \"{\": \n s.pop() # remove open brace\n res.update(_expr()) \n while s and s[-1] == \",\": \n s.pop() # remove comma \n res.update(_expr()) \n s.pop() # remove close brace \n while s and s[-1] not in \"},\": \n res = {e + o for o in _expr() for e in res}\n return res \n \n return sorted(_expr()) ", "solution_js": "var braceExpansionII = function(expression) { // , mutiplier = ['']\n const char = ('{' + expression + '}').split('').values()\n const result = [...rc(char)];\n result.sort((a,b) => a.localeCompare(b));\n return result;\n};\n\nfunction rc (char) {\n const result = new Set(); \n \n let resolved = ['']\n let chars = '';\n let currentChar = char.next().value; \n \n while (currentChar !== '}' && currentChar) {\n if (currentChar === '{') {\n resolved = mix(mix(resolved, [chars]), rc(char));\n chars = '';\n } else if (currentChar === ',') {\n for (const v of mix(resolved, [chars])) {\n result.add(v);\n }\n chars = '';\n resolved = [''];\n } else {\n chars += currentChar;\n }\n currentChar = char.next().value;\n }\n \n for (const v of mix(resolved, [chars])) {\n result.add(v);\n }\n \n return result; // everything\n}\n\nfunction mix (a, b) {\n const result = [];\n for (const ca of a) {\n for (const cb of b) {\n result.push(ca + cb);\n }\n }\n return result;\n}", "solution_java": "class Solution {\n // To Get the value of index traversed in a recursive call.\n int index = 0;\n\n public List braceExpansionII(String expression) {\n List result = util(0, expression);\n Set set = new TreeSet<>();\n set.addAll(result);\n return new ArrayList<>(set);\n }\n\n List util(int startIndex, String expression) {\n // This represents processed List in the current recursion.\n List currentSet = new ArrayList<>();\n boolean isAdditive = false;\n String currentString = \"\";\n // This represents List that is being processed and not yet merged to currentSet.\n List currentList = new ArrayList<>();\n\n for (int i = startIndex; i < expression.length(); ++i) {\n\n if (expression.charAt(i) == ',') {\n isAdditive = true;\n if (currentString != \"\" && currentList.size() == 0) {\n currentSet.add(currentString);\n }\n\n else if (currentList.size() > 0) {\n for (var entry : currentList) {\n currentSet.add(entry);\n }\n }\n\n currentString = \"\";\n currentList = new ArrayList<>();\n } else if (expression.charAt(i) >= 'a' && expression.charAt(i) <= 'z') {\n if (currentList.size() > 0) {\n List tempStringList = new ArrayList<>();\n for (var entry : currentList) {\n tempStringList.add(entry + expression.charAt(i));\n }\n currentList = tempStringList;\n } else {\n currentString = currentString + expression.charAt(i);\n }\n } else if (expression.charAt(i) == '{') {\n List list = util(i + 1, expression);\n // System.out.println(list);\n // Need to merge the returned List. It could be one of the following.\n // 1- ..., {a,b,c}\n // 2- a{a,b,c}\n // 3- {a,b,c}{d,e,f}\n // 3- {a,b,c}d\n if (i > startIndex && expression.charAt(i - 1) == ',') {\n // Case 1\n currentList = list;\n } else {\n if (currentList.size() > 0) {\n List tempList = new ArrayList<>();\n for (var entry1 : currentList) {\n for (var entry2 : list) {\n // CASE 3\n tempList.add(entry1 + currentString + entry2);\n }\n }\n\n // System.out.println(currentList);\n currentList = tempList;\n currentString = \"\";\n }\n\n else if (currentString != \"\") {\n List tempList = new ArrayList<>();\n for (var entry : list) {\n // case 2\n tempList.add(currentString + entry);\n }\n\n currentString = \"\";\n currentList = tempList;\n } else {\n // CASE 1\n currentList = list;\n }\n }\n\n // Increment i to end of next recursion's processing.\n i = index;\n } else if (expression.charAt(i) == '}') {\n if (currentString != \"\") {\n currentSet.add(currentString);\n }\n\n // {a{b,c,d}}\n if (currentList.size() > 0) {\n for (var entry : currentList) {\n\n currentSet.add(entry + currentString);\n }\n currentList = new ArrayList<>();\n }\n\n index = i;\n return new ArrayList<>(currentSet);\n }\n }\n\n if (currentList.size() > 0) {\n\n currentSet.addAll(currentList);\n }\n\n // {...}a\n if (currentString != \"\") {\n\n List tempSet = new ArrayList<>();\n if (currentSet.size() > 0) {\n for (var entry : currentSet) {\n tempSet.add(entry + currentString);\n }\n\n currentSet = tempSet;\n } else {\n currentSet = new ArrayList<>();\n currentSet.add(currentString);\n }\n }\n\n return new ArrayList<>(currentSet);\n }\n}", "solution_c": "class Solution {\npublic:\n vector braceExpansionII(string expression) {\n string ss;\n int n = expression.size();\n for(int i = 0; i < n; i++){\n if(expression[i] == ','){\n ss += '+';\n }\n else{\n ss += expression[i];\n if((isalpha(expression[i]) || expression[i] == '}') && i+1 < n && (isalpha(expression[i+1]) || expression[i+1] == '{')){\n ss += '*';\n }\n }\n }\n \n stackstk1;\n vectorpostfix;\n for(char c:ss){\n if(c == '{'){\n stk1.push(c);\n } else if(c == '}') {\n while(stk1.top() != '{'){\n postfix.push_back(string(1, stk1.top()));\n stk1.pop();\n }\n stk1.pop();\n } else if(c == '+'){\n while(!stk1.empty() && (stk1.top() == '+' || stk1.top() == '*')){\n postfix.push_back(string(1, stk1.top()));\n stk1.pop();\n }\n stk1.push(c);\n } else if(c == '*'){\n while(!stk1.empty() && stk1.top() == '*'){\n postfix.push_back(string(1, stk1.top()));\n stk1.pop();\n }\n stk1.push(c);\n } else {\n postfix.push_back(string(1, c));\n }\n }\n while(!stk1.empty()){\n postfix.push_back(string(1, stk1.top()));\n stk1.pop();\n }\n /*for(string sp:postfix){\n cout << sp << \" \";\n }\n cout << endl;*/\n stack>cont;\n for(string s:postfix){\n if(isalpha(s[0])){\n cont.push({s});\n } else {\n vectorsecond = cont.top();\n cont.pop();\n vectorfirst = cont.top();\n cont.pop();\n \n if(s[0] == '+'){\n for(string sec:second){\n first.push_back(sec);\n }\n cont.push(first);\n } else {\n vectorcartesian;\n for(string fst:first){\n for(string sec:second){\n cartesian.push_back(fst + sec);\n }\n }\n cont.push(cartesian);\n }\n }\n }\n setsstr;\n for(string sc:cont.top()){\n sstr.insert(sc);\n }\n \n vectorret(sstr.begin(), sstr.end());\n return ret;\n }\n};```" }, { "title": "Rotate String", "algo_input": "Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\n\nA shift on s consists of moving the leftmost character of s to the rightmost position.\n\n\n\tFor example, if s = \"abcde\", then it will be \"bcdea\" after one shift.\n\n\n \nExample 1:\nInput: s = \"abcde\", goal = \"cdeab\"\nOutput: true\nExample 2:\nInput: s = \"abcde\", goal = \"abced\"\nOutput: false\n\n \nConstraints:\n\n\n\t1 <= s.length, goal.length <= 100\n\ts and goal consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n for x in range(len(s)):\n s = s[-1] + s[:-1]\n if (goal == s):\n return True\n return False", "solution_js": "var rotateString = function(s, goal) {\n const n = s.length;\n for(let i = 0; i < n; i++) {\n s = s.substring(1) + s[0];\n if(s === goal) return true;\n }\n return false;\n};", "solution_java": "class Solution {\n public boolean rotateString(String s, String goal) {\n int n = s.length(), m = goal.length();\n if (m != n) return false;\n\n for (int offset = 0; offset < n; offset++) {\n if (isMatch(s, goal, offset)) return true;\n }\n return false;\n }\n\n private boolean isMatch(String s, String g, int offset) {\n int n = s.length();\n for (int si = 0; si < n; si++) {\n int gi = (si + offset) % n;\n if (s.charAt(si) != g.charAt(gi)) return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool rotateString(string s, string goal) {\n if(s.size()!=goal.size()){\n return false;\n }\n string temp=s+s;\n if(temp.find(goal)!=-1){\n return true;\n }\n return false;\n }\n};" }, { "title": "Maximum Path Quality of a Graph", "algo_input": "There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime.\n\nA valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).\n\nReturn the maximum quality of a valid path.\n\nNote: There are at most four edges connected to each node.\n\n \nExample 1:\n\nInput: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49\nOutput: 75\nExplanation:\nOne possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.\n\n\nExample 2:\n\nInput: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\nOutput: 25\nExplanation:\nOne possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.\n\n\nExample 3:\n\nInput: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\nOutput: 7\nExplanation:\nOne possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.\n\n\n \nConstraints:\n\n\n\tn == values.length\n\t1 <= n <= 1000\n\t0 <= values[i] <= 108\n\t0 <= edges.length <= 2000\n\tedges[j].length == 3 \n\t0 <= uj < vj <= n - 1\n\t10 <= timej, maxTime <= 100\n\tAll the pairs [uj, vj] are unique.\n\tThere are at most four edges connected to each node.\n\tThe graph may not be connected.\n\n", "solution_py": "class Solution:\n def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n graph = defaultdict(list)\n\t\t# build graph\n for edge in edges:\n graph[edge[0]].append((edge[1], edge[2]))\n graph[edge[1]].append((edge[0], edge[2]))\n \n q = deque()\n q.append((0, 0, values[0], set([0])))\n cache = {}\n maxPoint = 0\n\t\t\n while q:\n currV, currTime, currPoints, currSet = q.popleft()\n if currV in cache:\n\t\t\t\t# if vertex has been visited, and if the previousTime is \n\t\t\t\t# less or equal to current time but current points is lower?\n\t\t\t\t# then this path can't give us better quality so stop proceeding.\n prevTime, prevPoints = cache[currV]\n if prevTime <= currTime and prevPoints > currPoints:\n continue\n cache[currV] = (currTime, currPoints)\n\t\t\t# can't go over the maxTime limit\n if currTime > maxTime:\n continue\n\t\t\t# collect maxPoint only if current vertex is 0\n if currV == 0:\n maxPoint = max(maxPoint, currPoints)\n for neigh, neighTime in graph[currV]:\n newSet = currSet.copy()\n\t\t\t\t# collects quality only if not collected before\n if neigh not in currSet:\n newSet.add(neigh)\n newPoint = currPoints + values[neigh]\n else:\n newPoint = currPoints\n q.append((neigh, currTime + neighTime, newPoint, newSet))\n return maxPoint", "solution_js": "var maximalPathQuality = function(values, edges, maxTime) {\n const adjacencyList = values.map(() => []);\n for (const [node1, node2, time] of edges) {\n adjacencyList[node1].push([node2, time]);\n adjacencyList[node2].push([node1, time]);\n }\n\n const dfs = (node, quality, time, seen) => {\n // if we returned back to the 0 node, then we log it as a valid value\n let best = node === 0 ? quality : 0;\n\n // try to visit all the neighboring nodes within the maxTime\n // given while recording the max\n for (const [neighbor, routeTime] of adjacencyList[node]) {\n const totalTime = time + routeTime;\n if (totalTime > maxTime) continue;\n if (seen.has(neighbor)) {\n best = Math.max(best,\n dfs(neighbor, quality, totalTime, seen));\n } else {\n seen.add(neighbor);\n best = Math.max(best,\n dfs(neighbor, quality + values[neighbor], totalTime, seen));\n seen.delete(neighbor);\n }\n }\n return best;\n }\n return dfs(0, values[0], 0, new Set([0]));\n};", "solution_java": "class Solution {\n public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {\n int n = values.length;\n List[] adj = new List[n];\n for (int i = 0; i < n; ++i) adj[i] = new LinkedList();\n for (int[] e : edges) {\n int i = e[0], j = e[1], t = e[2];\n adj[i].add(new int[]{j, t});\n adj[j].add(new int[]{i, t});\n }\n int[] res = new int[1];\n int[] seen = new int[n];\n seen[0]++;\n dfs(adj, 0, values, maxTime, seen, res, values[0]);\n return res[0];\n }\n private void dfs(List[] adj, int src, int[] values, int maxTime, int[] seen, int[] res, int sum) {\n if (0 == src) {\n res[0] = Math.max(res[0], sum);\n }\n if (0 > maxTime) return;\n for (int[] data : adj[src]) {\n int dst = data[0], t = data[1];\n if (0 > maxTime - t) continue;\n seen[dst]++;\n dfs(adj, dst, values, maxTime - t, seen, res, sum + (1 == seen[dst] ? values[dst] : 0));\n seen[dst]--;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int maximalPathQuality(vector& values, vector>& edges, int maxTime) {\n int n = values.size();\n int res = values[0];\n vector>> graph(n);\n for(int i=0;i visited(n, 0);\n dfs(graph, values, visited, res, 0, 0, 0, maxTime);\n return res;\n }\n \n void dfs(vector>>& graph, vector& values, vector& visited, int& res, int node, int score, int time, int& maxTime)\n {\n if(time > maxTime)\n return;\n \n if(visited[node] == 0)\n score += values[node];\n \n        visited[node]++;\n\t\t\n      \n        if(node == 0)\n res = max(res, score);\n \n for(auto it : graph[node])\n {\n int neigh = it.first;\n int newTime = time + it.second;\n dfs(graph, values, visited, res, neigh, score, newTime, maxTime);\n }\n \n visited[node]--;\n }\n};" }, { "title": "My Calendar III", "algo_input": "A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)\n\nYou are given some events [start, end), after each given event, return an integer k representing the maximum k-booking between all the previous events.\n\nImplement the MyCalendarThree class:\n\n\n\tMyCalendarThree() Initializes the object.\n\tint book(int start, int end) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.\n\n\n \nExample 1:\n\nInput\n[\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, 1, 1, 2, 3, 3, 3]\n\nExplanation\nMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.\nmyCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.\nmyCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3\n\n\n \nConstraints:\n\n\n\t0 <= start < end <= 109\n\tAt most 400 calls will be made to book.\n\n", "solution_py": "import bisect\nclass MyCalendarThree:\n\n def __init__(self):\n self.events = [] \n\n def book(self, start: int, end: int) -> int:\n L, R = 1, 0\n bisect.insort(self.events, (start, L))\n bisect.insort(self.events, (end, R))\n res = 0\n cnt = 0\n for _, state in self.events:\n #if an interval starts, increase the counter\n #othewise, decreas the counter\n cnt += 1 if state == L else -1\n res = max(res, cnt)\n return res", "solution_js": "var MyCalendarThree = function() {\n this.intersections = [];\n this.kEvents = 0;\n \n};\n\n/** \n * @param {number} start \n * @param {number} end\n * @return {number}\n */\nMyCalendarThree.prototype.book = function(start, end) {\n let added = false;\n for(let i = 0; i < this.intersections.length; i++) {\n const a = this.intersections[i];\n if(end <= a.start) {\n this.intersections.splice(i, 0, {start, end, count: 1});\n this.kEvents = Math.max(this.kEvents, 1);\n this.added = true;\n break;\n }\n if(start < a. start) {\n this.intersections.splice(i, 0, {start, end: a.start, count: 1});\n i++;\n start = a.start;\n }\n if(a.start < start && start < a.end ) {\n this.intersections.splice(i, 0, {start: a.start, end: start, count: a.count});\n i++;\n a.start = start;\n }\n if(end < a.end) {\n this.intersections.splice(i + 1, 0, {start: end, end: a.end, count: a.count});\n a.count++;\n a.end = end;\n this.kEvents = Math.max(this.kEvents, a.count);\n this.added = true;\n break;\n }\n if(end === a.end) {\n a.count++;\n a.end = end;\n this.kEvents = Math.max(this.kEvents, a.count); \n this.added = true;\n break;\n } \n if(a.start === start && a.end < end ) {\n a.count++;\n this.kEvents = Math.max(this.kEvents, a.count);\n start = a.end;\n }\n }\n if(!added) {\n this.intersections.push({start, end, count: 1});\n this.kEvents = Math.max(this.kEvents, 1);\n }\n return this.kEvents;\n};", "solution_java": "class MyCalendarThree {\n\n TreeMap map;\n public MyCalendarThree() {\n map = new TreeMap<>();\n }\n\n public int book(int start, int end) {\n if(map.isEmpty()){\n map.put(start, 1);\n map.put(end,-1);\n return 1;\n }\n\n //upvote if you like the solution\n\n map.put(start, map.getOrDefault(start,0)+1);\n map.put(end, map.getOrDefault(end,0)-1);\n\n int res = 0;\n int sum = 0;\n for(Map.Entry e: map.entrySet()){\n sum += e.getValue();\n res = Math.max(res,sum);\n }\n\n return res;\n }\n}", "solution_c": "class MyCalendarThree {\npublic:\n mapmp;\n MyCalendarThree() { \n }\n int book(int start, int end) {\n mp[start]++;\n mp[end]--;\n int sum = 0;\n int ans = 0;\n for(auto it = mp.begin(); it != mp.end(); it++){\n sum += it->second;\n ans = max(ans,sum);\n }\n return ans;\n }\n};" }, { "title": "Minimum Operations to Make a Uni-Value Grid", "algo_input": "You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.\n\nA uni-value grid is a grid where all the elements of it are equal.\n\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n\n \nExample 1:\n\nInput: grid = [[2,4],[6,8]], x = 2\nOutput: 4\nExplanation: We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.\n\n\nExample 2:\n\nInput: grid = [[1,5],[2,3]], x = 1\nOutput: 5\nExplanation: We can make every element equal to 3.\n\n\nExample 3:\n\nInput: grid = [[1,2],[3,4]], x = 2\nOutput: -1\nExplanation: It is impossible to make every element equal.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 105\n\t1 <= m * n <= 105\n\t1 <= x, grid[i][j] <= 104\n\n", "solution_py": "class Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n \n m = len(grid)\n n = len(grid[0])\n\t\t\n\t\t# handle the edge case\n if m==1 and n==1: return 0\n\t\t\n\t\t# transform grid to array, easier to operate\n arr = [] \n for i in range(m):\n arr+=grid[i]\n \n arr.sort()\n \n\t\t# the median is arr[len(arr)//2] when len(arr) is odd\n\t\t# or may be arr[len(arr)//2] and arr[len(arr)//2-1] when len(arr) is even.\n cand1 = arr[len(arr)//2]\n cand2 = arr[len(arr)//2-1]\n \n return min(\n self.get_num_operations_to_target(grid, cand1, x),\n self.get_num_operations_to_target(grid, cand2, x)\n )\n \n \n def get_num_operations_to_target(self, grid, target,x):\n\t\t\"\"\"Get the total number of operations to transform all grid elements to the target value.\"\"\"\n ans = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if abs(grid[i][j]-target)%x!=0:\n return -1\n else:\n ans+=abs(grid[i][j]-target)//x\n\n return ans\n ", "solution_js": "var minOperations = function(grid, x) {\n \n let remainder = -Infinity, flatten = [], res = 0;\n \n for(let i = 0;i a-b);\n let median = flatten[~~(flatten.length/2)] \n\n for(let i = 0;i>& grid, int x) {\n vectornums;\n int m=grid.size(),n=grid[0].size();\n for(int i=0;i=0;i--){\n if(abs(nums[i]-target)%x!=0)\n return -1;\n else\n ans+=abs(nums[i]-target)/x; \n }\n return ans;\n }\n};" }, { "title": "Maximum Difference Between Node and Ancestor", "algo_input": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.\n\nA node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.\n\n \nExample 1:\n\nInput: root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput: 7\nExplanation: We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\n\nExample 2:\n\nInput: root = [1,null,2,null,0,3]\nOutput: 3\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 5000].\n\t0 <= Node.val <= 105\n\n", "solution_py": "class Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n self.max_diff = float('-inf')\n \n def dfs(node,prev_min,prev_max):\n if not node:\n return\n dfs(node.left,min(prev_min,node.val),max(prev_max,node.val))\n dfs(node.right,min(prev_min,node.val),max(prev_max,node.val))\n self.max_diff = max(abs(node.val-prev_min),abs(node.val-prev_max),self.max_diff)\n dfs(root,root.val,root.val)\n return self.max_diff", "solution_js": "var maxAncestorDiff = function(root) {\n let ans = 0;\n const traverse = (r = root, mx = root.val, mn = root.val) => {\n if(!r) return;\n ans = Math.max(ans, Math.abs(mx - r.val), Math.abs(mn - r.val));\n mx = Math.max(mx, r.val);\n mn = Math.min(mn, r.val);\n traverse(r.left, mx, mn);\n traverse(r.right, mx, mn);\n }\n traverse();\n return ans;\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 int maxAncestorDiff(TreeNode root) {\n\n if (root == null) return 0;\n\n return find(root, Integer.MAX_VALUE, Integer.MIN_VALUE);\n }\n\n public int find(TreeNode root, int min, int max) {\n if (root == null) return Math.abs(max-min);\n\n min = Math.min(min, root.val);\n max = Math.max(max, root.val);\n\n return Math.max(find(root.left, min, max), find(root.right, min, max));\n }\n\n}", "solution_c": "class Solution {\nprivate:\n int maxDiff;\n pair helper(TreeNode* root) {\n if (root == NULL) return {INT_MAX, INT_MIN};\n pair L = helper(root -> left), R = helper(root -> right);\n pair minMax = {min(L.first, R.first), max(L.second, R.second)};\n if (minMax.first != INT_MAX) maxDiff = max(maxDiff, max(abs(root -> val - minMax.first), abs(root -> val - minMax.second)));\n return {min(root -> val, minMax.first), max(root -> val, minMax.second)};\n }\npublic:\n int maxAncestorDiff(TreeNode* root) {\n maxDiff = INT_MIN;\n helper(root);\n return maxDiff;\n }\n};" }, { "title": "Minesweeper", "algo_input": "Let's play the minesweeper game (Wikipedia, online game)!\n\nYou are given an m x n char matrix board representing the game board where:\n\n\n\t'M' represents an unrevealed mine,\n\t'E' represents an unrevealed empty square,\n\t'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),\n\tdigit ('1' to '8') represents how many mines are adjacent to this revealed square, and\n\t'X' represents a revealed mine.\n\n\nYou are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').\n\nReturn the board after revealing this position according to the following rules:\n\n\n\tIf a mine 'M' is revealed, then the game is over. You should change it to 'X'.\n\tIf an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.\n\tIf an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.\n\tReturn the board when no more squares will be revealed.\n\n\n \nExample 1:\n\nInput: board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]\nOutput: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n\n\nExample 2:\n\nInput: board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]\nOutput: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n\n\n \nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 <= m, n <= 50\n\tboard[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'.\n\tclick.length == 2\n\t0 <= clickr < m\n\t0 <= clickc < n\n\tboard[clickr][clickc] is either 'M' or 'E'.\n\n", "solution_py": "class Solution:\n def calMines(self,board,x,y):\n directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]\n mines = 0\n for d in directions:\n r, c = x+d[0],y+d[1]\n if self.isValid(board,r,c) and (board[r][c] == 'M' or board[r][c] == 'X'):\n mines+=1\n return mines\n\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n x,y = click[0],click[1]\n options = []\n if board[x][y] == \"M\":\n board[x][y] = \"X\"\n else:\n count = self.calMines(board,x,y)\n if count == 0:\n board[x][y] = \"B\"\n for r in range(x-1,x+2):\n for c in range(y-1,y+2):\n if self.isValid(board,r,c) and board[r][c]!='B':\n self.updateBoard(board,[r,c])\n else:\n board[x][y] = str(count)\n\n return board\n \n \n def isValid(self,board,a,b):\n return 0<=a {\n\t\tfor (let row = -1; row <= 1; row++) {\n\t\t\tfor (let col = -1; col <= 1; col++) {\n\t\t\t\tfun(currentRow + row, currentCol + col);\n\t\t\t}\n\t\t}\n\t};\n\tconst getMinesCount = (currentRow, currentCol) => {\n\t\tlet result = 0;\n\n\t\tfunction check(row, col) {\n\t\t\tconst value = board[row]?.[col];\n\t\t\tif (value == 'M') result += 1;\n\t\t}\n\t\ttraverseAround({ currentRow, currentCol, fun: check });\n\t\treturn result;\n\t};\n\tconst dfs = (row = clickR, col = clickC) => {\n\t\tconst currnet = board[row]?.[col];\n\t\tif (currnet !== 'E') return;\n\t\tconst minesCount = getMinesCount(row, col);\n\t\tboard[row][col] = minesCount === 0 ? 'B' : `${minesCount}`;\n\t\tif (minesCount > 0) return;\n\n\t\ttraverseAround({ currentRow: row, currentCol: col, fun: dfs });\n\t};\n\n\tboard[clickR][clickC] === 'M'\n\t\t? board[clickR][clickC] = 'X'\n\t\t: dfs();\n\treturn board;\n};", "solution_java": "class Solution {\n public char[][] updateBoard(char[][] board, int[] click) {\n int r = click[0];\n int c = click[1];\n if(board[r][c] == 'M')\n {\n board[r][c] = 'X';\n return board;\n }\n dfs(board, r, c);\n return board;\n }\n\n private void dfs(char[][]board, int r, int c)\n {\n if(r < 0 || r >= board.length || c >= board[0].length || c < 0 || board[r][c] == 'B')//Stop case\n return;\n int num = countMine(board, r, c);//count how many adjacent mines\n if(num != 0)\n {\n board[r][c] = (char)('0' + num);\n return;\n }\n else\n {\n board[r][c] = 'B';\n dfs(board, r + 1, c);//recursively search all neighbors\n dfs(board, r - 1, c);\n dfs(board, r, c + 1);\n dfs(board, r, c - 1);\n dfs(board, r - 1, c - 1);\n dfs(board, r + 1, c - 1);\n dfs(board, r - 1, c + 1);\n dfs(board, r + 1, c + 1);\n }\n }\n\n private int countMine(char[][]board, int r, int c)\n {\n int count = 0;\n for(int i = r - 1; i <= r + 1; ++i)\n {\n for(int j = c - 1; j <= c + 1; ++j)\n {\n if(i >= 0 && i < board.length && j >= 0 && j < board[0].length)\n {\n if(board[i][j] == 'M')\n count++;\n }\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int m, n ;\n vector> updateBoard(vector>& board, vector& click) {\n if(board[click[0]][click[1]] == 'M'){\n board[click[0]][click[1]] = 'X' ;\n return board ;\n }\n else{\n m = board.size(), n = board[0].size() ;\n dfs(click[0], click[1], board) ;\n }\n return board ;\n }\n\n const int dx[8] = {1, 0, -1, 0, 1, 1, -1, -1};\n const int dy[8] = {0, -1, 0, 1, 1, -1, -1, 1};\n void dfs(int cr, int cc, vector> &board){\n int count = 0 ;\n for(int i = 0 ; i < 8 ; i++){\n int nr = cr + dx[i], nc = cc + dy[i] ;\n if(nr<0 || nr>=m || nc<0 || nc >=n || board[nr][nc]!='M') continue;\n count++ ;\n }\n\n if(count!=0){\n board[cr][cc] = '0'+count ;\n return ;\n }else{\n board[cr][cc] = 'B' ;\n for(int i = 0 ; i < 8 ; i++){\n int nr = cr + dx[i], nc = cc + dy[i] ;\n if(nr<0 || nr>=m || nc<0 || nc >=n || board[nr][nc]!='E') continue;\n dfs(nr, nc, board) ;\n }\n }\n }\n};" }, { "title": "Merge BSTs to Create Single BST", "algo_input": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:\n\n\n\tSelect two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].\n\tReplace the leaf node in trees[i] with trees[j].\n\tRemove trees[j] from trees.\n\n\nReturn the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.\n\nA BST (binary search tree) is a binary tree where each node satisfies the following property:\n\n\n\tEvery node in the node's left subtree has a value strictly less than the node's value.\n\tEvery node in the node's right subtree has a value strictly greater than the node's value.\n\n\nA leaf is a node that has no children.\n\n \nExample 1:\n\nInput: trees = [[2,1],[3,2,5],[5,4]]\nOutput: [3,2,5,1,null,4]\nExplanation:\nIn the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].\n\nIn the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].\n\nThe resulting tree, shown above, is a valid BST, so return its root.\n\nExample 2:\n\nInput: trees = [[5,3,8],[3,2,6]]\nOutput: []\nExplanation:\nPick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].\n\nThe resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.\n\n\nExample 3:\n\nInput: trees = [[5,4],[3]]\nOutput: []\nExplanation: It is impossible to perform any operations.\n\n\n \nConstraints:\n\n\n\tn == trees.length\n\t1 <= n <= 5 * 104\n\tThe number of nodes in each tree is in the range [1, 3].\n\tEach node in the input may have children but no grandchildren.\n\tNo two roots of trees have the same value.\n\tAll the trees in the input are valid BSTs.\n\t1 <= TreeNode.val <= 5 * 104.\n\n", "solution_py": "class Solution:\n def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n n = len(trees)\n if n == 1: return trees[0]\n\n value_to_root = {} # Map each integer root value to its node\n appeared_as_middle_child = set() # All values appearing in trees but not in a curr or leaf\n self.saw_conflict = False # If this is ever true, break out of function and return None\n leaf_value_to_parent_node = {}\n\n def is_leaf_node(curr: TreeNode) -> bool:\n return curr.left is None and curr.right is None\n\n def get_size(curr: TreeNode) -> int: # DFS to count Binary Tree Size\n if curr is None: return 0\n return 1 + get_size(curr.left) + get_size(curr.right)\n\n def is_valid_bst(curr: TreeNode, lo=-math.inf, hi=math.inf) -> bool: # Standard BST validation code\n if curr is None: return True\n return all((lo < curr.val < hi,\n is_valid_bst(curr.left, lo, curr.val),\n is_valid_bst(curr.right, curr.val, hi)))\n\n def process_child(child_node: TreeNode, parent: TreeNode) -> None:\n if child_node is None:\n return None\n elif child_node.val in leaf_value_to_parent_node or child_node.val in appeared_as_middle_child:\n self.saw_conflict = True # Already saw this child node's value in a non-root node\n elif is_leaf_node(child_node):\n leaf_value_to_parent_node[child_node.val] = parent\n elif child_node.val in value_to_root:\n self.saw_conflict = True\n else:\n appeared_as_middle_child.add(child_node.val)\n process_child(child_node.left, child_node)\n process_child(child_node.right, child_node)\n\n def process_root(curr_root: TreeNode) -> None:\n value_to_root[curr_root.val] = curr_root\n\n if curr_root.val in appeared_as_middle_child:\n self.saw_conflict = True\n else:\n process_child(curr_root.left, curr_root)\n process_child(curr_root.right, curr_root)\n\n for root_here in trees:\n process_root(root_here)\n if self.saw_conflict: return None\n\n final_expected_size = len(leaf_value_to_parent_node) + len(appeared_as_middle_child) + 1\n\n final_root = None # The root of our final BST will be stored here\n while value_to_root:\n root_val, root_node_to_move = value_to_root.popitem()\n\n if root_val not in leaf_value_to_parent_node: # Possibly found main root\n if final_root is None:\n final_root = root_node_to_move\n else:\n return None # Found two main roots\n else:\n new_parent = leaf_value_to_parent_node.pop(root_val)\n if new_parent.left is not None and new_parent.left.val == root_val:\n new_parent.left = root_node_to_move\n continue\n elif new_parent.right is not None and new_parent.right.val == root_val:\n new_parent.right = root_node_to_move\n else:\n return None # Didn't find a place to put this node\n\n # Didn't find any candidates for main root, or have a cycle, or didn't use all trees\n if final_root is None or not is_valid_bst(final_root) or get_size(final_root) != final_expected_size:\n return None\n\n return final_root", "solution_js": "var canMerge = function(trees) {\n let Node={},indeg={}\n // traverse the mini trees and put back pointers to their parents, also figure out the indegree of each node\n let dfs=(node,leftparent=null,rightparent=null)=>{\n if(!node)return\n indeg[node.val]=indeg[node.val]||Number(leftparent!==null||rightparent!==null)\n node.lp=leftparent,node.rp=rightparent\n dfs(node.left,node,null),dfs(node.right,null,node)\n }\n for(let root of trees)\n Node[root.val]=root,\n dfs(root)\n //there are a lot of potential roots=> no bueno\n if(Object.values(indeg).reduce((a,b)=>a+b)!=Object.keys(indeg).length-1)\n return null\n //find THE root\n let bigRoot,timesMerged=0\n for(let root of trees)\n if(indeg[root.val]===0)\n bigRoot=root\n // traverse the tree while replacing each leaf that can be replaced\n let rec=(node=bigRoot)=>{\n if(!node)\n return\n if(!node.left&&!node.right){\n let toadd=Node[node.val]\n Node[node.val]=undefined //invalidating the trees you already used\n if(toadd===undefined)\n return\n //make the change\n if(node.lp===null&&node.rp===null)\n return\n else if(node.lp!==null)\n node.lp.left=toadd\n else\n node.rp.right=toadd\n timesMerged++\n rec(toadd)\n }\n else\n rec(node.left),rec(node.right)\n }\n rec()\n var isValidBST = function(node,l=-Infinity,r=Infinity) { //l and r are the limits node.val should be within\n if(!node)\n return true\n if(node.valr)\n return false\n return isValidBST(node.left,l,node.val-1)&&isValidBST(node.right,node.val+1,r)\n };\n //check if every item was used and if the result bst is valid \n return !isValidBST(bigRoot)||timesMerged!==trees.length-1?null:bigRoot\n};", "solution_java": "class Solution {\n public TreeNode canMerge(List trees) {\n //Map root value to tree\n HashMap map = new HashMap<>();\n for(TreeNode t : trees){\n map.put(t.val, t);\n }\n\n // Merge trees\n for(TreeNode t : trees){\n if(map.containsKey(t.val)){\n merger(t, map);\n }\n }\n\n //After merging we should have only one tree left else return null\n if(map.size() != 1) return null;\n else {\n //Return the one tree left after merging\n for(int c : map.keySet()) {\n //Check if final tree is valid else return null\n if(isValidBST(map.get(c))){\n return map.get(c);\n } else return null;\n }\n }\n\n return null;\n\n }\n\n void merger(TreeNode t, HashMap map){\n map.remove(t.val); // Remove current tree to prevent cyclical merging For. 2->3(Right) and 3->2(Left)\n //Merge on left\n if(t.left != null && map.containsKey(t.left.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.left.val), map);\n t.left = map.get(t.left.val);\n map.remove(t.left.val);\n }\n\n // Merge on right\n if(t.right!=null && map.containsKey(t.right.val) ){\n // Before merging child node, merge the grandchild nodes\n merger(map.get(t.right.val), map);\n t.right = map.get(t.right.val);\n map.remove(t.right.val);\n }\n // Add tree back to map once right and left merge is complete\n map.put(t.val, t);\n }\n\n // Validate BST\n public boolean isValidBST(TreeNode root) {\n return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);\n }\n\n public boolean helper(TreeNode root, long min, long max){\n if(root == null) return true;\n if(root.val <= min || root.val >= max) return false;\n return helper(root.left, min, root.val) && helper(root.right, root.val, max);\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 TreeNode* canMerge(vector& trees) {\n //store the leaves of every node\n\n unordered_map mp;\n \n //store the current min and current max nodes in the current tree\n unordered_map> mini;\n for(int i=0;i ans={trees[i]->val,trees[i]->val};\n if(trees[i]->left)\n {\n \n mp[trees[i]->left->val]={trees[i]};\n ans.first=trees[i]->left->val;\n }\n if(trees[i]->right)\n {\n mp[trees[i]->right->val]=trees[i];\n ans.second=trees[i]->right->val;\n }\n mini[trees[i]]=ans;\n }\n \n //store the number of merging operations we will be doing\n int count=0;\n int rootCount=0;\n TreeNode* root=NULL;\n //now for every node get the root\n for(int i=0;ival)!=mp.end())\n {\n count++;\n //merge them\n TreeNode* parent=mp[trees[i]->val];\n if(trees[i]->val < parent->val)\n {\n //left child \n \n //if the maximum of the current sub tree is greater than the parent value \n //then return NULL\n if(parent->val <= mini[trees[i]].second)\n return NULL;\n //change the minimum value of the parent tree to the current min value of the tree\n mini[parent].first=mini[trees[i]].first;\n //merge the trees\n parent->left=trees[i];\n }\n else if(trees[i]->val > parent->val)\n {\n //right child\n \n //if the minimum of the current tree is lesser than the parent value\n //we cannot merge \n //so return NULL\n if(parent->val >= mini[trees[i]].first)\n return NULL;\n \n //change the parent tree maximum to the current tree maximum\n mini[parent].second=mini[trees[i]].second;\n //merge the trees\n parent->right=trees[i];\n }\n //erase the current tree value\n mp.erase(trees[i]->val);\n }\n else{\n //it has no other tree to merge \n //it is the root node we should return \n if(rootCount==1)\n return NULL;\n else \n {\n rootCount++;\n root=trees[i];\n }\n }\n }\n //if we are not able to merge all trees return NULL\n if(count!=trees.size()-1)\n return NULL;\n return root;\n \n }\n};" }, { "title": "Watering Plants", "algo_input": "You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.\n\nEach plant needs a specific amount of water. You will water the plants in the following way:\n\n\n\tWater the plants in order from left to right.\n\tAfter watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.\n\tYou cannot refill the watering can early.\n\n\nYou are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.\n\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.\n\n \nExample 1:\n\nInput: plants = [2,2,3,3], capacity = 5\nOutput: 14\nExplanation: Start at the river with a full watering can:\n- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.\n- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.\n- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).\n- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.\n- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).\n- Walk to plant 3 (4 steps) and water it.\nSteps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.\n\n\nExample 2:\n\nInput: plants = [1,1,1,4,2,3], capacity = 4\nOutput: 30\nExplanation: Start at the river with a full watering can:\n- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).\n- Water plant 3 (4 steps). Return to river (4 steps).\n- Water plant 4 (5 steps). Return to river (5 steps).\n- Water plant 5 (6 steps).\nSteps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.\n\n\nExample 3:\n\nInput: plants = [7,7,7,7,7,7,7], capacity = 8\nOutput: 49\nExplanation: You have to refill before watering each plant.\nSteps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.\n\n\n \nConstraints:\n\n\n\tn == plants.length\n\t1 <= n <= 1000\n\t1 <= plants[i] <= 106\n\tmax(plants[i]) <= capacity <= 109\n\n", "solution_py": "class Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n result = 0\n curCap = capacity\n\n for i in range(len(plants)):\n if curCap >= plants[i]:\n curCap -= plants[i]\n result += 1\n\n else:\n result += i * 2 + 1\n curCap = capacity - plants[i]\n\n return result", "solution_js": "var wateringPlants = function(plants, capacity) {\n var cap = capacity;\n var steps = 0;\n for(let i = 0; i < plants.length;i++){\n if(cap >= plants[i]){\n steps = steps + 1;\n }else{\n cap = capacity;\n steps = steps + (2 *i + 1);\n }\n cap = cap - plants[i];\n }\n return steps;\n};", "solution_java": "class Solution {\n public int wateringPlants(int[] plants, int capacity) {\n int count=0,c=capacity;\n for(int i=0;i=plants[i]){\n c-=plants[i];\n count++;\n }\n else {\n c=capacity;\n count=count+i+(i+1);\n c-=plants[i];\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n\tint wateringPlants(vector& plants, int capacity) {\n\t\tint result = 0;\n\t\tint curCap = capacity;\n\n\t\tfor (int i=0; i < plants.size(); i++){\n\t\t\tif (curCap >= plants[i]){\n\t\t\t\tcurCap -= plants[i];\n\t\t\t\tresult++; \n\t\t\t}\n\t\t\telse{\n\t\t\t\tresult += i * 2 + 1;\n\t\t\t\tcurCap = capacity - plants[i];\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n};" }, { "title": "Partition Array According to Given Pivot", "algo_input": "You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:\n\n\n\tEvery element less than pivot appears before every element greater than pivot.\n\tEvery element equal to pivot appears in between the elements less than and greater than pivot.\n\tThe relative order of the elements less than pivot and the elements greater than pivot is maintained.\n\t\n\t\tMore formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.\n\t\n\t\n\n\nReturn nums after the rearrangement.\n\n \nExample 1:\n\nInput: nums = [9,12,5,10,14,3,10], pivot = 10\nOutput: [9,5,3,10,10,12,14]\nExplanation: \nThe elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.\n\n\nExample 2:\n\nInput: nums = [-3,4,3,2], pivot = 2\nOutput: [-3,2,4,3]\nExplanation: \nThe element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-106 <= nums[i] <= 106\n\tpivot equals to an element of nums.\n\n", "solution_py": "class Solution:\n def pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n left=[]\n mid=[]\n right=[]\n for i in nums:\n if(ipivot)result.push(num)\n }\n return result\n};", "solution_java": "// Time complexity = 2n = O(n)\n// Space complexity = O(1), or O(n) if the result array is including in the complexity analysis.\n\nclass Solution {\n public int[] pivotArray(int[] nums, int pivot) {\n int[] result = new int[nums.length];\n int left = 0, right = nums.length - 1;\n\n for(int i = 0; i < nums.length; i++) {\n if(nums[i] < pivot) {\n result[left++] = nums[i];\n }\n if(nums[nums.length - 1 - i] > pivot) {\n result[right--] = nums[nums.length - 1 - i];\n }\n }\n\n while(left <= right) {\n result[left++] = pivot;\n result[right--] = pivot;\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector pivotArray(vector& nums, int pivot) {\n int i = 0;\n vector res;\n int cnt = count(nums.begin(), nums.end(), pivot);\n while(--cnt >= 0) {\n res.push_back(pivot);\n }\n for(int k = 0; k < nums.size(); k++) {\n if(nums[k] < pivot) {\n res.insert(res.begin() + i, nums[k]);\n i++;\n } else if(nums[k] > pivot) {\n res.push_back(nums[k]);\n } else\n continue;\n }\n return res;\n }\n};" }, { "title": "Check if Numbers Are Ascending in a Sentence", "algo_input": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.\n\n\n\tFor example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words.\n\n\nGiven a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).\n\nReturn true if so, or false otherwise.\n\n \nExample 1:\n\nInput: s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\nOutput: true\nExplanation: The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.\n\n\nExample 2:\n\nInput: s = \"hello world 5 x 5\"\nOutput: false\nExplanation: The numbers in s are: 5, 5. They are not strictly increasing.\n\n\nExample 3:\n\nInput: s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\nOutput: false\nExplanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 200\n\ts consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.\n\tThe number of tokens in s is between 2 and 100, inclusive.\n\tThe tokens in s are separated by a single space.\n\tThere are at least two numbers in s.\n\tEach number in s is a positive number less than 100, with no leading zeros.\n\ts contains no leading or trailing spaces.\n\n", "solution_py": "class Solution:\n def areNumbersAscending(self, s):\n nums = re.findall(r'\\d+', s)\n return nums == sorted(set(nums), key=int)", "solution_js": "var areNumbersAscending = function(s) {\n const numbers = [];\n const arr = s.split(\" \");\n for(let i of arr) {\n if(isFinite(i)) {\n if(numbers.length > 0 && numbers[numbers.length - 1] >= i) {\n return false;\n }\n numbers.push(+i);\n }\n }\n return true\n};", "solution_java": "// Space Complexity: O(1)\n// Time Complexity: O(n)\nclass Solution {\n public boolean areNumbersAscending(String s) {\n int prev = 0;\n\n for(String token: s.split(\" \")) {\n try {\n int number = Integer.parseInt(token);\n if(number <= prev)\n return false;\n prev = number;\n }\n catch(Exception e) {}\n }\n\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool areNumbersAscending(string s) {\n s.push_back(' '); // for last number calculation\n int prev = -1;\n string num;\n \n for(int i = 0 ; i < s.size() ; ++i)\n {\n char ch = s[i];\n if(isdigit(ch))\n num += ch;\n else if(ch == ' ' and isdigit(s[i - 1]))\n {\n if(stoi(num) <= prev) // number is not strictly increasing\n return false;\n prev = stoi(num);\n num = \"\";\n }\n }\n return true;\n }\n};" }, { "title": "Decode XORed Array", "algo_input": "There is a hidden integer array arr that consists of n non-negative integers.\n\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].\n\nYou are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].\n\nReturn the original array arr. It can be proved that the answer exists and is unique.\n\n \nExample 1:\n\nInput: encoded = [1,2,3], first = 1\nOutput: [1,0,2,1]\nExplanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]\n\n\nExample 2:\n\nInput: encoded = [6,2,7,3], first = 4\nOutput: [4,2,0,7,4]\n\n\n \nConstraints:\n\n\n\t2 <= n <= 104\n\tencoded.length == n - 1\n\t0 <= encoded[i] <= 105\n\t0 <= first <= 105\n\n", "solution_py": "class Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]", "solution_js": "var decode = function(encoded, first) {\n return [first].concat(encoded).map((x,i,a)=>{return i===0? x : a[i] ^= a[i-1]});\n};", "solution_java": "class Solution {\n public int[] decode(int[] encoded, int first) {\n int[] ans = new int[encoded.length + 1];\n ans[0] = first;\n for (int i = 0; i < encoded.length; i++) {\n ans[i + 1] = ans[i] ^ encoded[i];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector decode(vector& encoded, int first) {\n vector ans{first};\n for(int x: encoded)\n ans.push_back(first^=x);\n return ans;\n }\n};" }, { "title": "Minimum Changes To Make Alternating Binary String", "algo_input": "You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.\n\nThe string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not.\n\nReturn the minimum number of operations needed to make s alternating.\n\n \nExample 1:\n\nInput: s = \"0100\"\nOutput: 1\nExplanation: If you change the last character to '1', s will be \"0101\", which is alternating.\n\n\nExample 2:\n\nInput: s = \"10\"\nOutput: 0\nExplanation: s is already alternating.\n\n\nExample 3:\n\nInput: s = \"1111\"\nOutput: 2\nExplanation: You need two operations to reach \"0101\" or \"1010\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\n def minOperations(self, s: str) -> int:\n count = 0\n count1 = 0\n for i in range(len(s)):\n if i % 2 == 0:\n if s[i] == '1':\n count += 1\n if s[i] == '0':\n count1 += 1\n else:\n if s[i] == '0':\n count += 1\n if s[i] == '1':\n count1 += 1\n return min(count, count1)", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minOperations = function(s) {\n let counter1=0;\n let counter2=0;\n for(let i=0;i all chars at even places should be 1 and that at odd places should be 0\n if((i % 2 == 0 && s.charAt(i) == '0') || (i % 2 != 0 && s.charAt(i) == '1'))\n count1++;\n\n // string starts with 0 => all chars at even places should be 0 and that at odd places should be 1\n else if((i % 2 == 0 && s.charAt(i) == '1') || (i % 2 != 0 && s.charAt(i) == '0'))\n count0++;\n }\n\n // return minimum of the two\n return Math.min(count0, count1);\n }\n}", "solution_c": "class Solution {\npublic:\n int minOperations(string s) {\n int n=s.size(), ans=0;\n for(int i=0;i List[List[int]]:\n\n i=0\n c=1\n prev=\"\"\n l=len(s)\n ans=[]\n while i=3):\n ans.append([i+1-c,i])\n else:\n if c>=3:\n ans.append([i-c,i-1])\n c=1\n prev=s[i]\n i+=1\n return ans", "solution_js": "// 77 ms, faster than 97.56%\n// 45 MB, less than 87.81%\nvar largeGroupPositions = function(s) {\n\tlet re = /(.)\\1{2,}/g;\n\tlet ans = [];\n\twhile ((rslt = re.exec(s)) !== null) {\n\t\tans.push([rslt.index, rslt.index + rslt[0].length-1]);\n\t}\n\treturn ans;\n};", "solution_java": "class Solution {\n public List> largeGroupPositions(String s) {\n List> res = new ArrayList<>();\n List tmp = new ArrayList<>();\n int count = 1;\n \n for (int i = 0; i < s.length() - 1; i++) {\n // Increment the count until the next element is the same as the previous element. Ex: \"aaa\"\n if (s.charAt(i) == s.charAt(i + 1)) {\n count++;\n } \n // Add the first and last indices of the substring to the list when the next element is different from the previous element. Ex: \"aaab\"\n else if (s.charAt(i) != s.charAt(i + 1) && count >= 3) {\n // gives the starting index of substring\n tmp.add(i - count + 1);\n // gives the last index of substring \n tmp.add(i);\n res.add(tmp);\n count = 1;\n tmp = new ArrayList<>();\n } \n else {\n count = 1;\n }\n }\n\n // Check for a large group at the end of the string. Ex: \"abbb\".\n if (count >= 3) {\n tmp.add(s.length() - count);\n tmp.add(s.length() - 1);\n res.add(tmp);\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> largeGroupPositions(string s) {\n vector> res;\n \n int st = 0;\n int en = 1;\n \n while(en < s.size())\n {\n if(s[en] != s[st])\n {\n if(en-st >= 3)\n {\n res.push_back({st, en-1});\n \n }\n st = en;\n en = st+1;\n }\n else\n {\n en++;\n }\n }\n \n if(en-st >= 3)\n {\n res.push_back({st, en-1});\n }\n \n return res;\n }\n};" }, { "title": "Three Divisors", "algo_input": "Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\n\nAn integer m is a divisor of n if there exists an integer k such that n = k * m.\n\n \nExample 1:\n\nInput: n = 2\nOutput: false\nExplantion: 2 has only two divisors: 1 and 2.\n\n\nExample 2:\n\nInput: n = 4\nOutput: true\nExplantion: 4 has three divisors: 1, 2, and 4.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "import math\nclass Solution:\n def isThree(self, n: int) -> bool:\n primes = {3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1, 67:1, 71:1, 73:1, 79:1, 83:1, 89:1, 97:1}\n if n == 4:\n return True\n else:\n a = math.sqrt(n)\n\n if primes.get(a,0):\n return True\n else:\n return False", "solution_js": "var isThree = function(n) {\n var set = new Set();\n for(var i = 1; i<=Math.sqrt(n) && set.size <= 3; i++)\n {\n if(n % i === 0)\n {\n set.add(i);\n set.add(n / i);\n }\n }\n return set.size===3; \n};", "solution_java": "class Solution {\n public boolean isThree(int n) {\n if(n<4 ) return false;\n int res = (int)Math.sqrt(n);\n for(int i=2;i*i float:\n n = len(positions)\n if n == 1: return 0\n def gradient(x,y):\n ans = [0,0]\n for i in range(n):\n denom = math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n ans[0] += (x-positions[i][0])/denom if denom else 0\n ans[1] += (y-positions[i][1])/denom if denom else 0\n return ans\n def fn(x, y):\n res = 0\n for i in range(n):\n res += math.sqrt(pow(x-positions[i][0],2)+pow(y-positions[i][1],2))\n return res\n x = sum(x for x,_ in positions)/n\n y = sum(y for _,y in positions)/n\n lr = 1\n while lr > 1e-7:\n dx, dy = gradient(x,y)\n x -= lr*dx\n y -= lr*dy\n lr *= 0.997\n if not dx and not dy:\n lr /= 2\n return fn(x,y)", "solution_js": "/**\n * @param {number[][]} positions\n * @return {number}\n */\nvar getMinDistSum = function(positions) {\n /**\n identify the vertical range and horizontal range\n \n start from the center of positions\n calc the distance\n test the 4 direction with a certain step\n if any distance is closer, choose it as the new candidate\n if all 4 are further, reduce the step\n **/\n \n \n let xSum = 0;\n let ySum = 0;\n for (const [x, y] of positions) {\n xSum += x;\n ySum += y;\n }\n \n let n = positions.length;\n let x = xSum / n;\n let y = ySum / n;\n \n let step = 0.5;\n const dirs = [[0, 1], [0, -1], [-1, 0], [1, 0]];\n while (step >= 10 ** -5) {\n \n const dist = calcDist(x, y);\n let found = false;\n for (const [xDiff, yDiff] of dirs) {\n const newX = x + xDiff * step;\n const newY = y + yDiff * step;\n const newDist = calcDist(newX, newY);\n \n // console.log(x, y, newDist, dist);\n if (newDist < dist) {\n x = newX;\n y = newY;\n found = true;\n break;\n }\n }\n \n if (!found) {\n step /= 2;\n }\n }\n \n return calcDist(x, y);\n \n \n function calcDist(x, y) {\n let dist = 0;\n for (const [posX, posY] of positions) {\n dist += Math.sqrt((x - posX) ** 2 + (y - posY) ** 2);\n }\n return dist;\n }\n};", "solution_java": "class Solution {\n private static final double MIN_STEP = 0.0000001;\n private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n public double getMinDistSum(int[][] positions) {\n double cx = 0, cy = 0;\n int n = positions.length;\n for (int[] pos: positions) {\n cx += pos[0];\n cy += pos[1];\n }\n cx /= n; cy /= n;\n Node center = new Node(cx, cy, totalDistance(positions, cx, cy));\n\n double step = 50.0;\n while (step > MIN_STEP) {\n Node min = center;\n for (int[] direction: DIRECTIONS) {\n double dx = center.x + direction[0] * step, dy = center.y + direction[1] * step;\n double totalDist = totalDistance(positions, dx, dy);\n if (totalDist < center.dist) min = new Node(dx, dy, totalDist);\n }\n if (center == min) step /= 2;\n center = min;\n }\n\n return center.dist;\n }\n\n private double sq(double p) {\n return p * p;\n }\n\n private double dist(int[] pos, double x, double y) {\n return Math.sqrt(sq(x - pos[0]) + sq(y - pos[1]));\n }\n\n private double totalDistance(int[][] positions, double x, double y) {\n double dist = 0;\n for (int[] pos: positions) dist += dist(pos, x, y);\n return dist;\n }\n\n private static class Node {\n double x, y, dist;\n Node (double x, double y, double dist) {\n this.x = x;\n this.y = y;\n this.dist = dist;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n const double MIN_STEP = 0.000001; // With 0.00001 not AC\n\n const int dx[4] = {0, 0, 1,-1};\n const int dy[4] = {1, -1, 0, 0};\n\n double totalDist(vector>& positions, double cx, double cy) {\n double dist = 0;\n for (auto p : positions) {\n dist += hypot(p[0] - cx, p[1] - cy);\n }\n return dist;\n }\n\n double getMinDistSum(vector>& positions) {\n int n = (int)positions.size();\n double cx = 0, cy = 0;\n for (auto p : positions) { cx += p[0], cy += p[1]; }\n cx /= n, cy /= n;\n\n pair minDistCenter = {cx, cy};\n double minDist = totalDist(positions, cx, cy);\n //printf(\"cx = %.4lf, cy = %.4lf, minDist = %.4lf\\n\", minDistCenter.first, minDistCenter.second, minDist);\n\n double step = 50.0; // Because max value of x, y could be 100. So half of that\n while (step > MIN_STEP) {\n pair tempCenter = minDistCenter;\n double tempDist = minDist;\n\n for (int k = 0; k < 4; k++) {\n double xx = minDistCenter.first + dx[k] * step;\n double yy = minDistCenter.second + dy[k] * step;\n double d = totalDist(positions, xx, yy);\n //printf(\"d = %.4lf\\n\", d);\n if (d < minDist) {\n tempCenter = {xx, yy};\n tempDist = d;\n }\n }\n if (minDistCenter == tempCenter) step /= 2;\n minDistCenter = tempCenter;\n minDist = tempDist;\n }\n //printf(\"minDist = %.4lf\\n\", minDist);\n return minDist;\n }\n};" }, { "title": "Combination Sum IV", "algo_input": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.\n\nThe test cases are generated so that the answer can fit in a 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [1,2,3], target = 4\nOutput: 7\nExplanation:\nThe possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.\n\n\nExample 2:\n\nInput: nums = [9], target = 3\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 200\n\t1 <= nums[i] <= 1000\n\tAll the elements of nums are unique.\n\t1 <= target <= 1000\n\n\n \nFollow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?\n", "solution_py": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n dp = [0] * (target+1)\n dp[0] = 1\n for i in range(1, target+1):\n for num in nums: \n num_before = i - num\n if num_before >= 0:\n dp[i] += dp[num_before]\n return dp[target]", "solution_js": "var combinationSum4 = function(nums, target) {\n const dp = Array(target + 1).fill(0);\n \n nums.sort((a,b) => a - b);\n \n for(let k=1; k <= target; k++) {\n for(let n of nums) {\n if(k < n) break;\n dp[k] += (k == n) ? 1 : dp[k-n];\n }\n }\n \n return dp[target];\n};", "solution_java": "class Solution {\n public int combinationSum4(int[] nums, int target) {\n Integer[] memo = new Integer[target + 1];\n return recurse(nums, target, memo);\n }\n \n public int recurse(int[] nums, int remain, Integer[] memo){\n \n if(remain < 0) return 0;\n if(memo[remain] != null) return memo[remain];\n if(remain == 0) return 1;\n \n int ans = 0;\n for(int i = 0; i < nums.length; i++){\n ans += recurse(nums, remain - nums[i], memo);\n }\n \n memo[remain] = ans;\n return memo[remain];\n }\n}", "solution_c": "class Solution {\npublic:\n int combinationSum4(vector& nums, int target) {\n vector dp(target+1, 0);\n dp[0] = 1;\n for (int i = 1; i <= target; i++) {\n for (auto x : nums) {\n if (x <= i) {\n dp[i] += dp[i - x];\n }\n }\n }\n return dp[target];\n }\n};" }, { "title": "Self Crossing", "algo_input": "You are given an array of integers distance.\n\nYou start at point (0,0) on an X-Y plane and you move distance[0] meters to the north, then distance[1] meters to the west, distance[2] meters to the south, distance[3] meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.\n\nReturn true if your path crosses itself, and false if it does not.\n\n \nExample 1:\n\nInput: distance = [2,1,1,2]\nOutput: true\n\n\nExample 2:\n\nInput: distance = [1,2,3,4]\nOutput: false\n\n\nExample 3:\n\nInput: distance = [1,1,1,1]\nOutput: true\n\n\n \nConstraints:\n\n\n\t1 <= distance.length <= 105\n\t1 <= distance[i] <= 105\n\n", "solution_py": "class Solution:\n def isSelfCrossing(self, x):\n n = len(x)\n if n < 4: return False\n for i in range(3, n):\n if x[i] >= x[i-2] and x[i-1] <= x[i-3]: return True\n if i >= 4 and x[i-1]==x[i-3] and x[i]+x[i-4]>=x[i-2]: return True\n if i >= 5 and 0<=x[i-2]-x[i-4]<=x[i] and 0<=x[i-3]-x[i-1]<=x[i-5]: return True\n return False\n ", "solution_js": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b) return true; // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true; // cross [i - 4]\n\nif (x[i] < a) arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}", "solution_java": "class Solution {\n\npublic boolean isSelfCrossing(int[] x) {\nboolean arm = false;\nboolean leg = false;\nfor (int i = 2; i < x.length; ++i) {\nint a = f(x, i - 2) - f(x, i - 4);\nint b = f(x, i - 2);\n\nif (arm && x[i] >= b) return true; // cross [i - 2]\nif (leg && x[i] >= a && a > 0) return true; // cross [i - 4]\n\nif (x[i] < a) arm = true;\nelse if (x[i] <= b) leg = true;\n}\nreturn false;\n}\nprivate int f(int[] x, int index) {\nreturn (index < 0) ? 0 : x[index];\n}\n}", "solution_c": "class Solution {\npublic:\n bool isSelfCrossing(vector& distance) {\n if (distance.size() <= 3) return false; //only can have intersection with more than 4 lines\n\n distance.insert(distance.begin(), 0); //for the edge case: line i intersect with line i-4 at (0, 0)\n for (int i = 3; i < distance.size(); i++) {\n //check line i-3\n if (distance[i - 2] <= distance[i] && distance[i - 1] <= distance[i - 3]) return true;\n\n //check line i-5\n if (i >= 5) {\n if (distance[i - 1] <= distance[i - 3] && distance[i - 1] >= distance[i - 3] - distance[i - 5] \n && distance[i - 2] >= distance[i - 4] && distance[i - 2] <= distance[i - 4] + distance[i])\n return true;\n }\n }\n return false;\n }\n};" }, { "title": "Kth Ancestor of a Tree Node", "algo_input": "You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.\n\nThe kth ancestor of a tree node is the kth node in the path from that node to the root node.\n\nImplement the TreeAncestor class:\n\n\n\tTreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.\n\tint getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.\n\n\n \nExample 1:\n\nInput\n[\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]\nOutput\n[null, 1, 0, -1]\n\nExplanation\nTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n\n \nConstraints:\n\n\n\t1 <= k <= n <= 5 * 104\n\tparent.length == n\n\tparent[0] == -1\n\t0 <= parent[i] < n for all 0 < i < n\n\t0 <= node < n\n\tThere will be at most 5 * 104 queries.\n\n", "solution_py": "from math import ceil, log2\nfrom typing import List\n\nNO_PARENT = -1\n\nclass TreeAncestor:\n def __init__(self, n: int, parent: List[int]):\n self.parent = [[NO_PARENT] * n for _ in range(ceil(log2(n + 1)))]\n self.__initialize(parent)\n\n def __initialize(self, parent: List[int]):\n self.parent[0], prev = parent, parent\n\n for jump_pow in range(1, len(self.parent)):\n cur = self.parent[jump_pow]\n\n for i, p in enumerate(prev):\n if p != NO_PARENT:\n cur[i] = prev[p]\n\n prev = cur\n\n def getKthAncestor(self, node: int, k: int) -> int:\n jump_pow = self.jump_pow\n\n while k > 0 and node != NO_PARENT:\n jumps = 1 << jump_pow\n\n if k >= jumps:\n node = self.parent[jump_pow][node]\n k -= jumps\n else:\n jump_pow -= 1\n\n return node\n\n @property\n def jump_pow(self) -> int:\n return len(self.parent) - 1", "solution_js": "/**\n * @param {number} n\n * @param {number[]} parent\n */\nvar TreeAncestor = function(n, parent) {\n this.n = n;\n this.parent = parent;\n};\n\n/** \n * @param {number} node \n * @param {number} k\n * @return {number}\n */\n\n/*\nQs:\n1. Is the given tree a binary tree or n-ary tree?\n2. Can k be greater than possible (the total number of ancestors of given node)?\n\nEvery node has a parent except the root.\n1. Check if given node has a parent. If not, return -1.\n2. Set given node as the current ancestor and start a while loop which continues while k is greater than 0.\nAt each iteration, we set `ancestor` to the parent of current `ancestor` and decrement k. If k is still greater\nthan 0 but ancestor is -1, that means k is greater than possible. Hence, we return -1. Else, while loop will\nend when we are at the correct k-th ancestor. We return ancestor.\n*/\nTreeAncestor.prototype.getKthAncestor = function(node, k) {\n // check if given node has a parent\n if (this.parent[node] === -1) return -1;\n let ancestor = node;\n while (k > 0) {\n if (ancestor === -1) return -1; // k is greater than total number of ancestors of given node\n ancestor = this.parent[ancestor];\n k--;\n }\n return ancestor;\n // T.C: O(k)\n};", "solution_java": "class TreeAncestor {\n int n;\n int[] parent;\n List[] nodeInPath;\n int[] nodeIdxInPath;\n\n public TreeAncestor(int n, int[] parent) {\n this.n = n;\n this.parent = parent;\n nodeInPath = new ArrayList[n];\n nodeIdxInPath = new int[n];\n fill();\n }\n\n private void fill() {\n boolean[] inner = new boolean[n];\n for (int i = 1; i < n; i++) {\n inner[parent[i]] = true;\n }\n\n for (int i = 1; i < n; i++) {\n if (inner[i] || nodeInPath[i] != null) {\n continue;\n }\n List path = new ArrayList<>();\n int k = i;\n while (k != -1) {\n path.add(k);\n k = parent[k];\n }\n int m = path.size();\n for (int j = 0; j < m; j++) {\n int node = path.get(j);\n if (nodeInPath[node] != null) break;\n nodeInPath[node] = path;\n nodeIdxInPath[node] = j;\n }\n }\n }\n\n public int getKthAncestor(int node, int k) {\n List path = nodeInPath[node];\n int idx = nodeIdxInPath[node] + k;\n return idx >= path.size() ? -1 : path.get(idx);\n }\n}", "solution_c": "class TreeAncestor {\npublic:\n //go up by only powers of two\n vector> lift ;\n TreeAncestor(int n, vector& parent) {\n lift.resize(n,vector(21,-1)) ;\n //every node's first ancestor is parent itself\n for(int i = 0 ; i < n ; ++i ) lift[i][0] = parent[i] ;\n\n for(int i = 0 ; i < n ; ++i ){\n for(int j = 1 ; j <= 20 ; ++j ){\n if(lift[i][j-1] == -1) continue ;\n lift[i][j] = lift[lift[i][j-1]][j-1] ;\n }\n }\n }\n\n int getKthAncestor(int node, int k) {\n\n for(int i = 0 ; i <= 20 ; ++i ){\n if(k & (1 << i)){\n node = lift[node][i] ;\n if(node == -1) break;\n }\n }\n return node ;\n }\n};" }, { "title": "Magic Squares In Grid", "algo_input": "A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.\n\nGiven a row x col grid of integers, how many 3 x 3 \"magic square\" subgrids are there?  (Each subgrid is contiguous).\n\n \nExample 1:\n\nInput: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput: 1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\n\nwhile this one is not:\n\nIn total, there is only one magic square inside the given grid.\n\n\nExample 2:\n\nInput: grid = [[8]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\trow == grid.length\n\tcol == grid[i].length\n\t1 <= row, col <= 10\n\t0 <= grid[i][j] <= 15\n\n", "solution_py": "class Solution:\n\n digits = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n @classmethod\n def magic_3_3(cls, square: List[List[int]]) -> bool:\n if set(sum(square, [])) != Solution.digits:\n return False\n sum_row0 = sum(square[0])\n for r in range(1, 3):\n if sum(square[r]) != sum_row0:\n return False\n if any(sum(col) != sum_row0 for col in zip(*square)):\n return False\n sum_main_diagonal = sum_second_diagonal = 0\n for i in range(3):\n sum_main_diagonal += square[i][i]\n sum_second_diagonal += square[i][2 - i]\n return sum_main_diagonal == sum_second_diagonal == sum_row0\n\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n count = 0\n rows, cols = len(grid), len(grid[0])\n for r in range(rows - 2):\n for c in range(cols - 2):\n if Solution.magic_3_3([grid[row_idx][c: c + 3]\n for row_idx in range(r, r + 3)]):\n count += 1\n return count", "solution_js": "var numMagicSquaresInside = function(grid) {\n let res = 0;\n for(let i = 0; i < grid.length - 2; i++){\n for(let j = 0; j < grid[0].length - 2; j++){\n //only check 4\n if(grid[i][j]+grid[i][j+1]+grid[i][j+2]==15\n && grid[i][j]+grid[i+1][j]+grid[i+2][j]==15\n && grid[i][j]+grid[i+1][j+1]+grid[i+2][j+2]==15\n && grid[i+2][j]+grid[i+2][j+1]+grid[i+2][j+2]==15){\n let set = new Set();\n for(let a = i; a<=i+2; a++){\n for(let b = j; b<=j+2; b++){\n if(grid[a][b]>=1&&grid[a][b]<=9) set.add(grid[a][b]);\n }}\n if(set.size===9) res++;\n }}}\n return res;\n};", "solution_java": "class Solution {\n\tpublic int numMagicSquaresInside(int[][] grid) {\n\t\tint n=grid.length,m=grid[0].length,count=0;\n\t\tfor(int i=0;i9 ||count[grid[x+i][y+j]]!=0)\n\t\t\t\t\treturn false;\n\t\t\t\tcount[grid[x+i][y+j]]=1;\n\n\t\t\t}\n\t\t\tif(sum1!=sum || sum!=sum2 || sum1!=sum2)\n\t\t\t\treturn false;\n\t\t}\n\t\tsum1=grid[x][y]+grid[x+1][y+1]+grid[x+2][y+2];\n\t\tsum2=grid[x][y+2]+grid[x+1][y+1]+grid[x+2][y];\n\t\tif(sum1!=sum2 || sum1!=sum)\n\t\t\treturn false;\n\t\treturn true;\n\t}", "solution_c": "class Solution {\npublic:\n int numMagicSquaresInside(vector>& grid) {\n int result = 0;\n for(int i = 0; i < grid.size(); i++){\n for(int j = 0; j < grid[i].size() ; j++){\n if(isMagicSquare(grid, i, j)){\n result++;\n }\n }\n }\n return result;\n }\n bool isMagicSquare(vector>& grid, int i, int j){\n if(i + 2 < grid.size() && j+2 < grid[i].size()){\n int col1 = grid[i][j] + grid[i+1][j] + grid[i+2][j];\n int col2 = grid[i][j+1] + grid[i+1][j+1] + grid[i+2][j+1];\n int col3 = grid[i][j+2] + grid[i+1][j+2] + grid[i+2][j+2];\n int row1 = grid[i][j] + grid[i][j+1] + grid[i][j+2];\n int row2 = grid[i+1][j] + grid[i+1][j+1] + grid[i+1][j+2];\n int row3 = grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2];\n int diag1 = grid[i][j] + grid[i+1][j+1] + grid[i+2][j+2];\n int diag2 = grid[i+2][j] + grid[i+1][j+1] + grid[i][j+2];\n if(\n (col1 == col2) &&\n (col1 == col3) &&\n (col1 == row1) &&\n (col1 == row2) &&\n (col1 == row3) &&\n (col1 == diag1) &&\n (col1 == diag2)) {\n set s({1,2,3,4,5,6,7,8,9});\n for(int r = 0 ; r < 3 ; r++){\n for(int c = 0; c < 3 ; c++){\n s.erase(grid[i + r][j + c]);\n }\n }\n return s.empty();\n }\n }\n return false;\n }\n};" }, { "title": "Maximum Nesting Depth of the Parentheses", "algo_input": "A string is a valid parentheses string (denoted VPS) if it meets one of the following:\n\n\n\tIt is an empty string \"\", or a single character not equal to \"(\" or \")\",\n\tIt can be written as AB (A concatenated with B), where A and B are VPS's, or\n\tIt can be written as (A), where A is a VPS.\n\n\nWe can similarly define the nesting depth depth(S) of any VPS S as follows:\n\n\n\tdepth(\"\") = 0\n\tdepth(C) = 0, where C is a string with a single character not equal to \"(\" or \")\".\n\tdepth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.\n\tdepth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\n\n\nFor example, \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n\nGiven a VPS represented as string s, return the nesting depth of s.\n\n \nExample 1:\n\nInput: s = \"(1+(2*3)+((8)/4))+1\"\nOutput: 3\nExplanation: Digit 8 is inside of 3 nested parentheses in the string.\n\n\nExample 2:\n\nInput: s = \"(1)+((2))+(((3)))\"\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.\n\tIt is guaranteed that parentheses expression s is a VPS.\n\n", "solution_py": "class Solution:\n def maxDepth(self, s: str) -> int:\n ans = cur = 0\n for c in s:\n if c == '(':\n cur += 1\n ans = max(ans, cur)\n elif c == ')':\n cur -= 1\n return ans ", "solution_js": "var maxDepth = function(s) {\n let maxCount = 0, count = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '(') {\n maxCount = Math.max(maxCount, ++count);\n } else if (s[i] === ')') {\n count--;\n }\n }\n return maxCount;\n};", "solution_java": "class Solution {\n public int maxDepth(String s) {\n int count = 0; //count current dept of \"()\"\n int max = 0; //count max dept of \"()\"\n\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == '(') {\n count++;\n } else if (s.charAt(i) == ')') {\n count--;\n }\n max = Math.max(count, max);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxDepth(string s) {\n int maxi=0,curr=0;\n for(int i=0;i List[int]:\n\n class UnionFind:\n def __init__(self):\n self.parents = {}\n self.ranks = {}\n\n def insert(self, x):\n if x not in self.parents:\n self.parents[x] = x\n self.ranks[x] = 0\n\n def find_parent(self, x):\n if self.parents[x] != x:\n self.parents[x] = self.find_parent(self.parents[x])\n return self.parents[x]\n\n def union(self, x, y):\n self.insert(x)\n self.insert(y)\n x, y = self.find_parent(x), self.find_parent(y)\n if x == y:\n return\n if self.ranks[x] > self.ranks[y]:\n self.parents[y] = x\n else:\n self.parents[x] = y\n if self.ranks[x] == self.ranks[y]:\n self.ranks[y] += 1\n\n time2meets = defaultdict(list)\n for x, y, t in meetings:\n time2meets[t].append((x, y))\n time2meets = sorted(time2meets.items())\n\n curr_know = set([0, firstPerson])\n\n for time, meets in time2meets:\n uf = UnionFind()\n for x, y in meets:\n uf.union(x, y)\n\n groups = defaultdict(set)\n for idx in uf.parents:\n groups[uf.find_parent(idx)].add(idx)\n\n for group in groups.values():\n if group & curr_know:\n curr_know.update(group)\n\n return list(curr_know)", "solution_js": "var findAllPeople = function(n, meetings, firstPerson) {\n const timeToMeeting = mapSortedTimeToMeetings(meetings);\n\n const peopleThatCurrentlyHaveSecret = new Set([0, firstPerson]);\n for (const peopleInMeetings of timeToMeeting.values()) {\n const personToMeetingsWithPeople =\n mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings);\n let peopleInMeetingsWithSecret =\n findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret);\n\n // BFS algorithm\n while (peopleInMeetingsWithSecret.size > 0) {\n const nextPeopleInMeetingsWithSecret = new Set();\n for (const attendee of peopleInMeetingsWithSecret) {\n for (const personInMeetingWithAttendee of personToMeetingsWithPeople[attendee]) {\n\n // only add new people that have the secret otherwise there will be an\n // infinite loop\n if (!peopleThatCurrentlyHaveSecret.has(personInMeetingWithAttendee)) {\n nextPeopleInMeetingsWithSecret.add(personInMeetingWithAttendee);\n peopleThatCurrentlyHaveSecret.add(personInMeetingWithAttendee);\n }\n }\n }\n peopleInMeetingsWithSecret = nextPeopleInMeetingsWithSecret;\n }\n }\n return [...peopleThatCurrentlyHaveSecret];\n};\n\n// groups all the meetings by time\n// keys (time) is sorted in ascending order\nfunction mapSortedTimeToMeetings(meetings) {\n meetings.sort((a, b) => a[2] - b[2]);\n\n const timeToMeeting = new Map();\n for (const [person1, person2, time] of meetings) {\n if (!timeToMeeting.has(time)) {\n timeToMeeting.set(time, []);\n }\n timeToMeeting.get(time).push([person1, person2]);\n }\n return timeToMeeting;\n}\n\n// creates an adjacency list of people and people they are having meetings with\nfunction mapPeopleToPeopleTheyAreHavingMeetingsWith(peopleInMeetings) {\n const personToMeetingsWithPeople = {};\n for (const [person1, person2] of peopleInMeetings) {\n if (!personToMeetingsWithPeople[person1]) {\n personToMeetingsWithPeople[person1] = [];\n }\n if (!personToMeetingsWithPeople[person2]) {\n personToMeetingsWithPeople[person2] = [];\n }\n personToMeetingsWithPeople[person1].push(person2);\n personToMeetingsWithPeople[person2].push(person1);\n }\n return personToMeetingsWithPeople;\n}\n\n// finds all the people that are in meetings that have the secret\n// set data structue is used so that people are not duplicated\nfunction findPeopleThatHaveTheSecret(peopleInMeetings, peopleThatCurrentlyHaveSecret) {\n const peopleInMeetingsWithSecret = new Set();\n for (const peopleInMeeting of peopleInMeetings) {\n for (const person of peopleInMeeting) {\n if (peopleThatCurrentlyHaveSecret.has(person)) {\n peopleInMeetingsWithSecret.add(person);\n }\n }\n }\n return peopleInMeetingsWithSecret;\n}", "solution_java": "class Solution {\n public List findAllPeople(int n, int[][] meetings, int firstPerson) {\n\t\n\t\t// create map\n Map> timeToIndexes = new TreeMap<>();\n int m = meetings.length;\n for (int i = 0; i < m; i++) {\n timeToIndexes.putIfAbsent(meetings[i][2], new ArrayList<>());\n timeToIndexes.get(meetings[i][2]).add(i);\n }\n\t\t\n UF uf = new UF(n);\n\t\t// base\n uf.union(0, firstPerson);\n\t\t\n\t\t// for every time we have a pool of people that talk to each other\n\t\t// if someone knows a secret proir to this meeting - all pool will too\n\t\t// if not - reset unions from this pool\n for (int time : timeToIndexes.keySet()) {\n Set pool = new HashSet<>();\n\t\t\t\n for (int ind : timeToIndexes.get(time)) {\n int[] currentMeeting = meetings[ind];\n uf.union(currentMeeting[0], currentMeeting[1]);\n pool.add(currentMeeting[0]);\n pool.add(currentMeeting[1]);\n }\n\t\t\t\n\t\t\t// meeting that took place now should't affect future\n\t\t\t// meetings if people don't know the secret\n for (int i : pool) if (!uf.connected(0, i)) uf.reset(i);\n }\n\t\t\n\t\t// if the person is conneted to 0 - they know a secret\n List ans = new ArrayList<>();\n for (int i = 0; i < n; i++) if (uf.connected(i,0)) ans.add(i);\n return ans;\n }\n \n\t// regular union find\n private static class UF {\n int[] parent, rank;\n\t\t\n public UF(int n) {\n parent = new int[n];\n rank = new int[n];\n for (int i = 0; i < n; i++) parent[i] = i;\n }\n \n public void union(int p, int q) {\n int rootP = find(p);\n int rootQ = find(q);\n\n if (rootP == rootQ)\n return;\n\n if (rank[rootP] < rank[rootQ]) {\n parent[rootP] = rootQ;\n } else {\n parent[rootQ] = rootP;\n rank[rootP]++;\n }\n }\n \n public int find(int p) {\n while (parent[p] != p) {\n p = parent[parent[p]];\n }\n return p;\n }\n \n public boolean connected(int p, int q) {\n return find(p) == find(q);\n }\n \n public void reset(int p) {\n parent[p] = p;\n rank[p] = 0;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n vector findAllPeople(int n, vector>& meetings, int firstPerson) {\n vector res;\n set ust;\n ust.insert(0);\n ust.insert(firstPerson);\n map>> mp;\n for (auto &m : meetings) {\n mp[m[2]].push_back({m[0],m[1]});\n }\n for (auto &m : mp) {\n for (auto &v : m.second) { //front to back\n if (ust.count(v.first)) {\n ust.insert(v.second);\n }\n if (ust.count(v.second)) {\n ust.insert(v.first);\n }\n }\n for (auto it = m.second.rbegin(); it != m.second.rend(); ++it) { //back to front\n if (ust.count((*it).first)) {\n ust.insert((*it).second);\n }\n if (ust.count((*it).second)) {\n ust.insert((*it).first);\n }\n }\n }\n for (auto it = ust.begin(); it != ust.end(); ++it)\n res.push_back(*it);\n return res;\n }\n};" }, { "title": "Longest Common Subsequence", "algo_input": "Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.\n\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n\n\n\tFor example, \"ace\" is a subsequence of \"abcde\".\n\n\nA common subsequence of two strings is a subsequence that is common to both strings.\n\n \nExample 1:\n\nInput: text1 = \"abcde\", text2 = \"ace\" \nOutput: 3 \nExplanation: The longest common subsequence is \"ace\" and its length is 3.\n\n\nExample 2:\n\nInput: text1 = \"abc\", text2 = \"abc\"\nOutput: 3\nExplanation: The longest common subsequence is \"abc\" and its length is 3.\n\n\nExample 3:\n\nInput: text1 = \"abc\", text2 = \"def\"\nOutput: 0\nExplanation: There is no such common subsequence, so the result is 0.\n\n\n \nConstraints:\n\n\n\t1 <= text1.length, text2.length <= 1000\n\ttext1 and text2 consist of only lowercase English characters.\n\n", "solution_py": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n def lcs(ind1,ind2):\n prev=[0 for i in range(ind2+1)]\n curr=[0 for i in range(ind2+1)]\n \n for i in range(1,ind1+1):\n for j in range(1,ind2+1):\n if text1[i-1]==text2[j-1]:\n curr[j]=1+prev[j-1]\n \n else:\n curr[j]=max(prev[j],curr[j-1])\n prev=list(curr) # remember to use a new list for prev\n\n return prev[-1]\n \n \n ans=lcs(len(text1),len(text2))\n return ans", "solution_js": "/**\n * @param {string} text1\n * @param {string} text2\n * @return {number}\n */\nlet memo\nconst dp=(a,b,i,j)=>{\n if(i===0||j===0)return 0;\n if(memo[i][j]!=-1)return memo[i][j];\n if(a[i-1]===b[j-1]){\n return memo[i][j]= 1+ dp(a,b,i-1,j-1);\n }else{\n return memo[i][j]=Math.max(dp(a,b,i-1,j),dp(a,b,i,j-1));\n }\n\n}\nconst bottomUp=(a,b)=>{\n\n for(let i=1;i<=a.length;i++){\n for(let j=1;j<=b.length;j++){\n if(a[i-1]===b[j-1]){\n memo[i][j]=1+memo[i-1][j-1]\n }else{\n memo[i][j]=Math.max(memo[i-1][j],memo[i][j-1]);\n }\n\n }\n }\n\nreturn memo[a.length][b.length]\n\n}\n\nvar longestCommonSubsequence = function(text1, text2) {\n memo=[];\n for(let i=0;i<=text1.length;i++){\n memo[i]=[];\n for(let j=0;j<=text2.length;j++){\n if(i===0||j===0)memo[i][j]=0;\n else memo[i][j]=-1;\n }\n }\n return bottomUp(text1,text2,text1.length,text2.length);\n // return dp(text1,text2,text1.length,text2.length);\n};", "solution_java": "class Solution {\n public int longestCommonSubsequence(String text1, String text2) {\n int m = text1.length();\n int n = text2.length();\n int[][] dp = new int[m + 1][n + 1];\n\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (text1.charAt(i - 1) == text2.charAt(j - 1)) {\n dp[i][j] = 1 + dp[i - 1][j - 1];\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n\n return dp[m][n];\n }\n}", "solution_c": "class Solution {\npublic:\n int longestCommonSubsequence(string text1, string text2) {\n int dp[1001][1001] = {0};\n for(int i = 1; i <= text1.size(); i++)\n for(int j = 1; j <= text2.size(); j++)\n if(text1[i-1] == text2[j-1]) dp[i][j] = 1 + dp[i-1][j-1];\n else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n return dp[text1.size()][text2.size()];\n }\n};" }, { "title": "Decode the Slanted Ciphertext", "algo_input": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.\n\noriginalText is placed first in a top-left to bottom-right manner.\n\nThe blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText.\n\nencodedText is then formed by appending all characters of the matrix in a row-wise fashion.\n\nThe characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.\n\nFor example, if originalText = \"cipher\" and rows = 3, then we encode it in the following manner:\n\nThe blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\".\n\nGiven the encoded string encodedText and number of rows rows, return the original string originalText.\n\nNote: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.\n\n \nExample 1:\n\nInput: encodedText = \"ch ie pr\", rows = 3\nOutput: \"cipher\"\nExplanation: This is the same example described in the problem description.\n\n\nExample 2:\n\nInput: encodedText = \"iveo eed l te olc\", rows = 4\nOutput: \"i love leetcode\"\nExplanation: The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.\n\n\nExample 3:\n\nInput: encodedText = \"coding\", rows = 1\nOutput: \"coding\"\nExplanation: Since there is only 1 row, both originalText and encodedText are the same.\n\n\n \nConstraints:\n\n\n\t0 <= encodedText.length <= 106\n\tencodedText consists of lowercase English letters and ' ' only.\n\tencodedText is a valid encoding of some originalText that does not have trailing spaces.\n\t1 <= rows <= 1000\n\tThe testcases are generated such that there is only one possible originalText.\n\n", "solution_py": "class Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n n = len(encodedText)\n cols = n // rows\n step = cols + 1\n res = \"\"\n \n for i in range(cols):\n for j in range(i, n, step):\n res += encodedText[j]\n \n return res.rstrip()", "solution_js": "var decodeCiphertext = function(encodedText, rows) {\n const numColumns = encodedText.length / rows;\n const stringBuilder = [];\n let nextCol = 1;\n let row = 0;\n let col = 0;\n let index = 0\n while (index < encodedText.length) {\n stringBuilder.push(encodedText[index]);\n if (row === rows - 1 || col === numColumns - 1) {\n row = 0;\n col = nextCol;\n nextCol++;\n } else {\n row++;\n col++;\n }\n index = calcIndex(row, col, numColumns);\n }\n while (stringBuilder[stringBuilder.length - 1] === ' ') {\n stringBuilder.pop();\n }\n return stringBuilder.join('');\n};\n\nfunction calcIndex(row, col, numColumns) {\n return row * numColumns + col;\n}", "solution_java": "class Solution {\n public String decodeCiphertext(String str, int rows) {\n\n //first find column size!!\n \tint cols=str.length()/rows;\n \tStringBuilder res=new StringBuilder(),new_res=new StringBuilder();;\n \tfor(int i=0;i=0;i--) {\n \n if(fg==0&&res.charAt(i)==' ')\n continue;\n fg=1;\n new_res.append(res.charAt(i));\n }\n return new_res.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string decodeCiphertext(string encodedText, int rows) {\n int n = encodedText.size();\n\n // Determining the number of columns\n int cols = n / rows;\n vector> mat(rows, vector(cols, ' '));\n int i = 0, j = 0;\n int k = 0;\n\n string ans = \"\";\n\n // Filling the matrix using encodedText\n // Row wise\n for(int i = 0; i < rows; i++) {\n for(int j = 0; j < cols; j++) {\n mat[i][j] = encodedText[k++];\n }\n }\n\n // Only the upper triangular part of the matrix will\n // contain characters of the originalText\n // so, this loop traverses that area\n for(int k = 0; k < n - (rows * (rows - 1)) / 2; k++) {\n // i, j are the two pointers for tracking rows and columns\n ans.push_back(mat[i++][j++]);\n\n // If any boundary is hit, then column pointer is subtracted\n // by row_pointer - 1\n // and row pointer is reset to 0\n if(i == rows || j == cols) {\n j -= (i - 1);\n i = 0;\n }\n }\n\n // Removing all trailing spaces\n while(ans.back() == ' ')\n ans.pop_back();\n\n return ans;\n }\n};" }, { "title": "Reorganize String", "algo_input": "Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.\n\nReturn any possible rearrangement of s or return \"\" if not possible.\n\n \nExample 1:\nInput: s = \"aab\"\nOutput: \"aba\"\nExample 2:\nInput: s = \"aaab\"\nOutput: \"\"\n\n \nConstraints:\n\n\n\t1 <= s.length <= 500\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n\tdef reorganizeString(self, s: str) -> str:\n\t\tc = Counter(s) # for counting the distinct element \n\t\tpq = []\n\t\tfor k,v in c.items(): heapq.heappush(pq,(-v,k)) #multipy by -1 to make max heap \n\t\tans = ''\n\t\twhile pq :\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif ans and ans[-1] == ch: \n\t\t\t\tif not pq: return '' // if heap is empty we cant make the ans return empty string\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\t\treturn ans", "solution_js": "var reorganizeString = function(s) {\n const charMap = {};\n const res = [];\n\n // Store the count of each char\n for (let char of s) {\n charMap[char] = (charMap[char] || 0) + 1;\n }\n\n // Sort in descending order by count\n const sortedMap = Object.entries(charMap).sort((a, b) => b[1] - a[1]);\n\n // Check if we can distribute the first char by every other position.\n // We only need to check the first char b/c the chars are ordered by count\n // so if the first char succeeds, all following chars will succeed\n if (sortedMap[0][1] > Math.floor((s.length + 1) / 2)) return '';\n\n let position = 0;\n for (let entry of sortedMap) {\n const char = entry[0]\n const count = entry[1];\n for (let j = 0; j < count; j++) {\n // Distribute the current char every other position. The same char\n // will never be placed next to each other even on the 2nd loop\n // for placing chars in odd positions\n res[position] = char;\n position +=2;\n\n // This will only happen once since total number of chars\n // will be exactly equal to the length of s\n if (position >= s.length) position = 1;\n }\n }\n\n return res.join('');\n};", "solution_java": "class Solution {\n public String reorganizeString(String s) {\n StringBuilder ans=new StringBuilder(\"\");\n char[] charArray=new char[s.length()];\n Map hashMap=new HashMap<>();\n Queue queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence);\n\n charArray=s.toCharArray();\n\n for(int i=0;inew CharOccurence(e.getKey(),e.getValue()))\n .collect(Collectors.toList()));\n while(!queue.isEmpty())\n {\n Queue tmpQueue=new LinkedList<>();\n int sizeQueue=queue.size();\n int stringLength=ans.length();\n int startSub=(stringLength-1<0)?0:stringLength-1;\n int endSub=stringLength;\n String lastLetter=ans.substring(startSub,endSub);\n boolean letterAdded=false;\n for(int i=0;i0)\n tmpQueue.add(letter);\n letterAdded=true;\n break;\n }\n else\n {\n tmpQueue.add(letter);\n }\n }\n if(!letterAdded)\n return \"\";\n queue.addAll(tmpQueue);\n }\n return ans.toString();\n\n }\n class CharOccurence{\n public Character letter;\n public int occurence;\n public CharOccurence(Character letter, int occurence)\n {\n this.letter=letter;\n this.occurence=occurence;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n string reorganizeString(string s) {\n \n // Step1: insert elements to the map so that we will get the frequency\n unordered_map mp;\n for(auto i: s){\n mp[i]++;\n }\n \n //Step2: Create a max heap to store all the elements according to there frequency\n priority_queue> pq;\n \n for(auto it: mp){\n pq.push({it.second, it.first});\n }\n \n //Step3: Now take two elements from the heap and do this till the map becomes size 1\n // why one : cause we are taking two top elements like pq.top is a then will pop and again pq.top is b and will add to answer\n string ans = \"\";\n while(mp.size() > 1){\n //get the top two elements from heap\n char ch1 = pq.top().second;\n ans+=ch1;\n pq.pop();\n char ch2 = pq.top().second;\n ans+=ch2;\n pq.pop();\n \n //now reduce the size in the mp\n // now we have added two char in the ans so reduce the cound in map\n mp[ch1]--;\n mp[ch2]--;\n \n //Now check if it's size is still greater than 0 then push\n // if size is greater in map than 0 then we again need to push into the map so that we can make the ans string\n if(mp[ch1] > 0){\n pq.push({mp[ch1],ch1});\n }\n else{\n //if the size is 0 then decrese the map means erase the map\n mp.erase(ch1);\n }\n if(mp[ch2] > 0){\n pq.push({mp[ch2],ch2});\n }\n else{\n mp.erase(ch2);\n }\n }\n \n //Step4 : Now check wheather any element is present into it\n // Now we have zero size of the map so check top element size is greater than 1 or not if greater the we cannot split it since it''s only that char if not add to ans\n if(mp.size() == 1){\n if(mp[pq.top().second] > 1){\n return \"\";\n }\n ans += pq.top().second;\n }\n //returrn ans\n return ans;\n }\n};" }, { "title": "Remove Colored Pieces if Both Neighbors are the Same Color", "algo_input": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.\n\nAlice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.\n\n\n\tAlice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.\n\tBob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.\n\tAlice and Bob cannot remove pieces from the edge of the line.\n\tIf a player cannot make a move on their turn, that player loses and the other player wins.\n\n\nAssuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.\n\n \nExample 1:\n\nInput: colors = \"AAABABB\"\nOutput: true\nExplanation:\nAAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.\n\n\nExample 2:\n\nInput: colors = \"AA\"\nOutput: false\nExplanation:\nAlice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.\n\n\nExample 3:\n\nInput: colors = \"ABBBBBBBAAA\"\nOutput: false\nExplanation:\nABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.\n\n\n \nConstraints:\n\n\n\t1 <= colors.length <= 105\n\tcolors consists of only the letters 'A' and 'B'\n\n", "solution_py": "class Solution:\n def winnerOfGame(self, s: str) -> bool:\n \n a = b = 0\n \n for i in range(1,len(s)-1):\n if s[i-1] == s[i] == s[i+1]:\n if s[i] == 'A':\n a += 1\n else:\n b += 1\n \n return a>b", "solution_js": "var winnerOfGame = function(colors) {\n const n = colors.length;\n const stack = [];\n \n let alice = 0;\n let bob = 0;\n \n for (let i = 0; i < n; ++i) {\n const char = colors[i];\n \n if (stack.length > 1 && stack[stack.length - 1] === char && stack[stack.length - 2] === char) {\n stack.pop();\n \n if (char === \"A\") ++alice;\n else ++bob;\n }\n stack.push(char);\n }\n \n return alice > bob ? true : false; \n};", "solution_java": "class Solution {\n public boolean winnerOfGame(String colors) {\n int cntA=0,cntB=0;\n for(int i=1;icntB;\n }\n}", "solution_c": "class Solution {\npublic:\n bool winnerOfGame(string colors) {\n if (colors.size() < 3) return false;\n int a = 0, b = 0;\n for (int i = 0; i < colors.size()-2; i++) {\n if (colors.substr(i, 3) == \"AAA\") a++;\n else if (colors.substr(i, 3) == \"BBB\") b++;\n }\n return a > b;\n }\n};" }, { "title": "Remove Linked List Elements", "algo_input": "Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.\n\n \nExample 1:\n\nInput: head = [1,2,6,3,4,5,6], val = 6\nOutput: [1,2,3,4,5]\n\n\nExample 2:\n\nInput: head = [], val = 1\nOutput: []\n\n\nExample 3:\n\nInput: head = [7,7,7,7], val = 7\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 104].\n\t1 <= Node.val <= 50\n\t0 <= val <= 50\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:\n prev=head\n cur=head\n while cur is not None:\n if cur.val==val:\n if cur==head:\n head=head.next\n prev=head\n else:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} val\n * @return {ListNode}\n */\nvar removeElements = function(head, val) {\n \n if(!head)return null\n \n //if the val is on the beginning delete it \n while( head && head.val===val)head=head.next\n\n \n let current=head;\n let next=head.next;\n //travers the liste and delete any node has this val \n while(next){ \n if(next.val===val){\n current.next=next.next\n }\n else current=next\n \n next=next.next\n \n }\n \n return head\n};", "solution_java": "class Solution {\n public ListNode removeElements(ListNode head, int val) {\n if (head == null) {\n return head;\n }\n ListNode result = head;\n while (head.next != null) {\n if (head.next.val == val) {\n head.next = head.next.next;\n } else {\n head = head.next;\n }\n }\n if (result.val == val) {\n result = result.next;\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* removeElements(ListNode* head, int val) {\n ListNode *prv,*cur,*temp;\n while(head && head->val==val){\n cur=head;\n head=head->next;\n delete(cur);\n }\n if(head==NULL) return head;\n prv=head;\n cur=head->next;\n while(cur){\n if(cur->val==val){\n temp=cur;\n prv->next=cur->next;\n cur=cur->next;\n delete(temp);\n }\n else{\n prv=cur;\n cur=cur->next;\n }\n }\n return head;\n\n }\n};" }, { "title": "Prison Cells After N Days", "algo_input": "There are 8 prison cells in a row and each cell is either occupied or vacant.\n\nEach day, whether the cell is occupied or vacant changes according to the following rules:\n\n\n\tIf a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.\n\tOtherwise, it becomes vacant.\n\n\nNote that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.\n\nYou are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.\n\nReturn the state of the prison after n days (i.e., n such changes described above).\n\n \nExample 1:\n\nInput: cells = [0,1,0,1,1,0,0,1], n = 7\nOutput: [0,0,1,1,0,0,0,0]\nExplanation: The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]\n\n\nExample 2:\n\nInput: cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput: [0,0,1,1,1,1,1,0]\n\n\n \nConstraints:\n\n\n\tcells.length == 8\n\tcells[i] is either 0 or 1.\n\t1 <= n <= 109\n\n", "solution_py": "class Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n patternMatch=defaultdict(int) # pattern match\n totalPrisons=8 # totalPrisons\n cells= [ str(c) for c in (cells)] # into char type\n for d in range(1,n+1):\n tempCell=[]\n tempCell.append('0') # left corner case\n for c in range(1,totalPrisons-1):\n if (cells[c-1]=='1' and cells[c+1]=='1') or (cells[c-1]=='0' and cells[c+1]=='0'):\n tempCell.append('1') # insert 1 if first condition met\n else:\n tempCell.append('0') # otherwise 0\n tempCell.append('0') # right corner case\n cells=tempCell # update cells\n pattern= ''.join(tempCell) # insert pattern in hashtable\n if pattern in patternMatch: # if there is a match\n day=patternMatch[pattern]\n remainder= (n%(d-1))-1 # take modulo\n match= list(patternMatch.keys())[remainder] # find key\n return [ int(m) for m in match] # return\n patternMatch[pattern]=d # assign day\n return [ int(c) for c in (cells)] # return", "solution_js": "/**\n * @param {number[]} cells\n * @param {number} n\n * @return {number[]}\n */\n\nvar prisonAfterNDays = function(cells, n) {\n const set = new Set()\n let cycleDuration = 0\n \n while(n--) {\n const nextCells = getNextCells(cells)\n\n // 1. Get cycle length\n if(!set.has(String(nextCells))){\n set.add(String(nextCells))\n cycleDuration++\n cells = nextCells\n \n } else {\n // 2. Use cycle length to iterate once more to get to correct order\n let remainderToMove = n%cycleDuration\n while(remainderToMove >= 0) {\n remainderToMove--\n cells = getNextCells(cells)\n }\n break\n } \n \n }\n \n return cells\n};\n\nfunction getNextCells(cells) {\n let temp = [...cells]\n for(let i = 0; i < 8; i++) {\n if(i>0 && i < 7 && cells[i-1] === cells[i+1]) {\n temp[i] = 1\n } else {\n temp[i] = 0\n }\n }\n\n return temp\n}\n\n// 0\n// 1\n// 2\n// n\n\n// 1 000 000 % n ", "solution_java": "class Solution {\n public int[] prisonAfterNDays(int[] cells, int n) {\n // # Since we have 6 cells moving cells (two wil remain unchaged at anytime) \n // # the cycle will restart after 14 iteration\n // # 1- The number of days if smaller than 14 -> you brute force O(13)\n // # 2- The number is bigger than 14\n // # - You do a first round of 14 iteration\n // # - Than you do a second round of n%14 iteration\n // # ===> O(27)\n \n n = n % 14 == 0 ? 14 : n%14;\n int temp[] = new int[cells.length];\n \n while(n-- > 0)\n {\n for(int i=1; i prisonAfterNDays(vector& cells, int n) {\n //since there are only a 2**6 number of states and n can go to 10**9\n //this means that there is bound to be repetition of states\n int state=0;\n //making the initial state bitmask\n for(int i=0;iseen;\n while(n--){\n int next=0;\n //transitioning to the next state\n for(int pos=6;pos>0;pos--){\n int right=pos+1,left=pos-1;\n if(((state>>right)&1)==((state>>left)&1)){\n next|=(1<ans(cells.size(),0);\n for(int i=0;i<8;i++){\n if((state>>i)&1){\n ans[7-i]=1;\n }\n }\n return ans;\n }\n};" }, { "title": "Pizza With 3n Slices", "algo_input": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\n\n\n\tYou will pick any pizza slice.\n\tYour friend Alice will pick the next slice in the anti-clockwise direction of your pick.\n\tYour friend Bob will pick the next slice in the clockwise direction of your pick.\n\tRepeat until there are no more slices of pizzas.\n\n\nGiven an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.\n\n \nExample 1:\n\nInput: slices = [1,2,3,4,5,6]\nOutput: 10\nExplanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n\n\nExample 2:\n\nInput: slices = [8,9,8,6,1,1]\nOutput: 16\nExplanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n\n\n \nConstraints:\n\n\n\t3 * n == slices.length\n\t1 <= slices.length <= 500\n\t1 <= slices[i] <= 1000\n\n", "solution_py": " class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n ** #This solve function mainly on work on the idea of A Previous dp problem House Robber II \n\t\t#If we take the first slice then we cant take the second slice and vice versa**\n\t\tdef solve(slices,start,end,n,dp):\n if start>end or n==0:\n return 0\n if dp[start][n] !=-1:\n return dp[start][n]\n include = slices[start] + solve(slices,start+2,end,n-1,dp)\n \n exclude = 0 + solve(slices,start+1,end,n,dp)\n \n dp[start][n]= max(include,exclude)\n return dp[start][n]\n dp1=[[-1 for i in range(k+1)]for _ in range(k+1)]\n dp2=[[-1 for i in range(k+1)]for _ in range(k+1)]\n \n option1=solve(slices,0,k-2,k//3,dp1)#Taking the the first slice , now we cant take the last slice and next slice\n option2=solve(slices,1,k-1,k//3,dp2)#Taking the the second slice , now we cant take the second last slice and next slice\n \n return max(option1,option2)", "solution_js": "var maxSizeSlices = function(slices) {\n const numSlices = slices.length / 3;\n const len = slices.length - 1;\n \n const dp = new Array(len).fill(null).map(() => new Array(numSlices + 1).fill(0));\n const getMaxTotalSlices = (pieces) => {\n\t // the max for 1 piece using only the first slice is itself\n dp[0][1] = pieces[0];\n\t\t// the max for 1 piece using the first 2 slices is the max of the first and second slice\n dp[1][1] = Math.max(pieces[0], pieces[1]);\n\t\t// start the max as the max of taking 1 slice from the first 2 slices\n let max = dp[1][1];\n\t\t\n\t\t// calculate the max value for taking x number of pieces using up to that piece\n for (let i = 2; i < pieces.length; i++) {\n for (let numPieces = 1; numPieces <= numSlices; numPieces++) {\n dp[i][numPieces] = Math.max(dp[i - 1][numPieces], // the max for not taking this piece\n\t\t\t\t dp[i - 2][numPieces - 1] + pieces[i]); // the max for taking this piece\n if (max < dp[i][numPieces]) max = dp[i][numPieces]; // update the max if it is greater\n }\n }\n return max;\n }\n \n return Math.max(getMaxTotalSlices(slices.slice(0, slices.length - 1)), // get max without the last slice\n getMaxTotalSlices(slices.slice(1))); // get max without the first slice\n};", "solution_java": "class Solution {\n public int maxSizeSlices(int[] slices) {\n int n = slices.length;\n return Math.max(helper(slices, n/3, 0, n - 2), helper(slices, n/3, 1, n - 1));\n }\n \n private int helper(int[] slices, int rounds, int start, int end) {\n int n = end - start + 1, max = 0;\n int[][][] dp = new int[n][rounds+1][2];\n dp[0][1][1] = slices[start];\n for (int i = start + 1; i <= end; i++) {\n int x = i - start;\n for (int j = 1; j <= rounds; j++) {\n dp[x][j][0] = Math.max(dp[x-1][j][0], dp[x-1][j][1]);\n dp[x][j][1] = dp[x-1][j-1][0] + slices[i];\n if (j == rounds) {\n max = Math.max(max, Math.max(dp[x][j][0], dp[x][j][1]));\n }\n }\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n \n int dp[501][501];\n \n int solve(vector&v , int i ,int count ){\n \n if( i >= v.size() || count > v.size()/3 ) return 0 ;\n \n if(dp[i][count] != -1 ) return dp[i][count]; \n \n int pick = v[i] + solve(v,i+2,count+1) ;\n int notPick = solve(v,i+1,count) ;\n \n return dp[i][count] = max(pick,notPick) ;\n \n }\n \n \n int maxSizeSlices(vector& slices) { \n \n vectorv1 ;\n vectorv2 ;\n \n for(int i = 0 ; i < slices.size() ;i++){\n \n if( i != slices.size()-1 ) v1.push_back(slices[i]) ;\n if( i != 0 ) v2.push_back(slices[i]);\n \n }\n memset(dp,-1,sizeof(dp)) ; \n int ans1 = solve(v1,0,0);\n memset(dp,-1,sizeof(dp)) ; \n int ans2 = solve(v2,0,0);\n \n return max(ans1,ans2) ;\n \n }\n};" }, { "title": "Max Area of Island", "algo_input": "You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.\n\nThe area of an island is the number of cells with a value 1 in the island.\n\nReturn the maximum area of an island in grid. If there is no island, return 0.\n\n \nExample 1:\n\nInput: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\nOutput: 6\nExplanation: The answer is not 11, because the island must be connected 4-directionally.\n\n\nExample 2:\n\nInput: grid = [[0,0,0,0,0,0,0,0]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 50\n\tgrid[i][j] is either 0 or 1.\n\n", "solution_py": "from queue import Queue\nfrom typing import List\n\n\nclass Solution:\n def __init__(self):\n self.directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]\n\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n [rows, cols] = [len(grid), len(grid[0])]\n\n ans = 0\n visited: List[List[bool]] = [[False for _ in range(cols)] for _ in range(rows)]\n \n for i in range(rows):\n for j in range(cols):\n if not visited[i][j] and grid[i][j]:\n res = self.dfs(grid, visited, i, j)\n ans = res if res > ans else ans \n\n return ans\n\n def dfs(self, grid: List[List[int]], visited: List[List[bool]], startRow: int, startCol: int) -> int:\n [rows, cols] = [len(grid), len(grid[0])]\n \n fields = 1\n q = Queue()\n\n q.put([startRow, startCol])\n visited[startRow][startCol] = True\n\n while not q.empty():\n [row, col] = q.get()\n for d in self.directions:\n newRow = row + d[0]\n newCol = col + d[1]\n if newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols and not visited[newRow][newCol] and grid[newRow][newCol]:\n visited[newRow][newCol] = True\n fields += 1\n q.put([newRow, newCol])\n \n return fields", "solution_js": "var maxAreaOfIsland = function(grid) {\n let result = 0;\n const M = grid.length;\n const N = grid[0].length;\n const isOutGrid = (m, n) => m < 0 || m >= M || n < 0 || n >= N;\n const island = (m, n) => grid[m][n] === 1;\n const dfs = (m, n) => {\n if (isOutGrid(m, n) || !island(m, n)) return 0;\n\n grid[m][n] = 'X';\n const top = dfs(m - 1, n);\n const bottom = dfs(m + 1, n);\n const left = dfs(m, n - 1);\n const right = dfs(m, n + 1);\n return 1 + top + bottom + left + right;\n };\n\n for (let m = 0; m < M; m++) {\n for (let n = 0; n < N; n++) {\n if (!island(m, n)) continue;\n const area = dfs(m, n);\n\n result = Math.max(area, result);\n }\n }\n return result;\n};", "solution_java": "class Solution {\n public int maxAreaOfIsland(int[][] grid) {\n\n final int rows=grid.length;\n final int cols=grid[0].length;\n final int[][] dirrections=new int[][]{{1,0},{0,1},{-1,0},{0,-1}};\n Map> adj=new HashMap<>();\n boolean[][] visited=new boolean[rows][cols];\n Queue queue=new LinkedList<>();\n int res=0;\n\n for(int i=0;i list=new ArrayList<>();\n for(int[] dirrection:dirrections)\n {\n int newRow=dirrection[0]+i;\n int newCol=dirrection[1]+j;\n\n boolean isInBoard=newRow>=rows||newRow<0||newCol>=cols||newCol<0;\n if(!isInBoard)\n {\n list.add(new int[]{newRow,newCol,grid[newRow][newCol]});\n }\n }\n\n adj.put(getNodeStringFormat(i,j,grid[i][j]),list);\n }\n }\n\n for(int i=0;i>& grid,int i,int j,int& m,int& n){\n if(i==m || j==n || i<0 || j<0 || grid[i][j]==0)\n return 0;\n grid[i][j]=0;\n return 1+cal(grid,i,j+1,m,n)+cal(grid,i+1,j,m,n)+cal(grid,i,j-1,m,n)+cal(grid,i-1,j,m,n);\n }\n int maxAreaOfIsland(vector>& grid) {\n int m=grid.size(),n=grid[0].size(),maxArea=0;\n for(int i=0;i& words) {\n\n for(int i=0 ; i int:\n max_len = 0\n visited = set()\n def dfs(nums, index, dfs_visited):\n if index in dfs_visited:\n return len(dfs_visited)\n \n # add the index to dfs_visited and visited\n visited.add(index)\n dfs_visited.add(index)\n return dfs(nums, nums[index], dfs_visited)\n \n for i in range(len(nums)):\n if i not in visited:\n max_len = max(max_len, dfs(nums, i, set()))\n return max_len", "solution_js": "var arrayNesting = function(nums) {\n\treturn nums.reduce((result, num, index) => {\n\t\tlet count = 1;\n\n\t\twhile (nums[index] !== index) {\n\t\t\tconst next = nums[index];\n\t\t\t[nums[index], nums[next]] = [nums[next], nums[index]];\n\t\t\tcount += 1;\n\t\t}\n\t\treturn Math.max(result, count);\n\t}, 0);\n};", "solution_java": "class Solution {\n public int arrayNesting(int[] nums) {\n int res=0;\n boolean[] visited = new boolean[nums.length];\n for(int i=0;i&nums,int ind,int arr[],int res)\n {\n if(arr[ind]==1)\n return res;\n res++;\n arr[ind]=1;\n return dfs(nums,nums[ind],arr,res);\n }\n int arrayNesting(vector& nums) {\n \n int arr[nums.size()],ans=0;\n for(int i=0;i n, we know that n itself is prime.\n#\n# Complexity is O(sqrt(n)) in bad cases (if n is prime), but can be much better\n# if n only has small prime factors, e.g. for n = 3**k it's O(k) = O(log(n)).\n\nclass Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n while n % 2 == 0:\n # Kill even factors\n n //= 2\n result = 1\n p = 3\n while n != 1:\n count = 1\n while n % p == 0:\n n //= p\n count += 1\n result *= count\n if p**2 >= n:\n # Rest of n is prime, stop here\n if n > p:\n # We have not counted n yet\n result *= 2\n break\n p += 2\n return result", "solution_js": "var consecutiveNumbersSum = function(n) {\n let count = 1;\n for (let numberOfTerms = 2; numberOfTerms < Math.sqrt(2*n) + 1; numberOfTerms++) {\n let startNumber = (n - numberOfTerms * (numberOfTerms - 1) / 2) / numberOfTerms;\n if (Number.isInteger(startNumber) && startNumber !== 0) {\n count++;\n }\n }\n return count;\n};", "solution_java": "class Solution {\n\n public int consecutiveNumbersSum(int n) {\n final double eightN = (8d * ((double) n)); // convert to double because 8n can overflow int\n final int maxTriangular = (int) Math.floor((-1d + Math.sqrt(1d + eightN)) / 2d);\n int ways = 1;\n int triangular = 1;\n for (int m = 2; m <= maxTriangular; ++m) {\n triangular += m;\n final int difference = n - triangular;\n if ((difference % m) == 0) {\n ways++;\n }\n }\n return ways;\n }\n\n}", "solution_c": "class Solution {\npublic:\n int consecutiveNumbersSum(int n) {\n int count = 0;\n for(int i = 2 ; i < n ; i++){\n int sum_1 = i*(i+1)/2;\n if(sum_1 > n)\n break;\n if((n-sum_1)%i == 0)\n count++;\n }\n return count+1;\n }\n};" }, { "title": "Maximum Erasure Value", "algo_input": "You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.\n\nReturn the maximum score you can get by erasing exactly one subarray.\n\nAn array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).\n\n \nExample 1:\n\nInput: nums = [4,2,4,5,6]\nOutput: 17\nExplanation: The optimal subarray here is [2,4,5,6].\n\n\nExample 2:\n\nInput: nums = [5,2,1,2,5,2,1,2,5]\nOutput: 8\nExplanation: The optimal subarray here is [5,2,1] or [1,2,5].\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 104\n\n", "solution_py": "class Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n max_sum = 0\n seen = set()\n for l in range(len(nums)):\n seen.clear()\n curr_sum = 0\n r = l\n while r < len(nums):\n if nums[r] in seen:\n break\n curr_sum += nums[r]\n seen.add(nums[r])\n r += 1\n max_sum = max(max_sum, curr_sum)\n return max_sum", "solution_js": "var maximumUniqueSubarray = function(nums) {\n let nmap = new Int8Array(10001), total = 0, best = 0\n for (let left = 0, right = 0; right < nums.length; right++) {\n nmap[nums[right]]++, total += nums[right]\n while (nmap[nums[right]] > 1)\n nmap[nums[left]]--, total -= nums[left++]\n best = Math.max(best, total)\n }\n return best\n};", "solution_java": "class Solution {\n public int maximumUniqueSubarray(int[] nums) {\n short[] nmap = new short[10001];\n int total = 0, best = 0;\n for (int left = 0, right = 0; right < nums.length; right++) {\n nmap[nums[right]]++;\n total += nums[right];\n while (nmap[nums[right]] > 1) {\n nmap[nums[left]]--;\n total -= nums[left++];\n }\n best = Math.max(best, total);\n }\n return best;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumUniqueSubarray(vector& nums) {\n int curr_sum=0, res=0;\n\n //set to store the elements\n unordered_set st;\n\n int i=0,j=0;\n while(j0) {\n //Removing the ith element untill we reach the repeating element\n st.erase(nums[i]);\n curr_sum-=nums[i];\n i++;\n }\n //Add the current element to set and curr_sum value\n curr_sum+=nums[j];\n st.insert(nums[j++]);\n\n //res variable to keep track of largest curr_sum encountered till now...\n res = max(res, curr_sum);\n }\n\n return res;\n }\n};" }, { "title": "HTML Entity Parser", "algo_input": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.\n\nThe special characters and their entities for HTML are:\n\n\n\tQuotation Mark: the entity is &quot; and symbol character is \".\n\tSingle Quote Mark: the entity is &apos; and symbol character is '.\n\tAmpersand: the entity is &amp; and symbol character is &.\n\tGreater Than Sign: the entity is &gt; and symbol character is >.\n\tLess Than Sign: the entity is &lt; and symbol character is <.\n\tSlash: the entity is &frasl; and symbol character is /.\n\n\nGiven the input text string to the HTML parser, you have to implement the entity parser.\n\nReturn the text after replacing the entities by the special characters.\n\n \nExample 1:\n\nInput: text = \"&amp; is an HTML entity but &ambassador; is not.\"\nOutput: \"& is an HTML entity but &ambassador; is not.\"\nExplanation: The parser will replace the &amp; entity by &\n\n\nExample 2:\n\nInput: text = \"and I quote: &quot;...&quot;\"\nOutput: \"and I quote: \\\"...\\\"\"\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 105\n\tThe string may contain any possible characters out of all the 256 ASCII characters.\n\n", "solution_py": "class Solution:\n def entityParser(self, text: str) -> str:\n d = {\""\" : '\"' , \"'\":\"'\" , \"&\" : \"&\" , \">\" : \">\" , \"<\":\"<\" , \"⁄\" : \"/\"}\n \n \n \n ans = \"\"\n i = 0\n while i < len(text):\n bag = \"\"\n \n #condition if find & and next char is not & also and handdling index out of range for i + 1\n if i+1 < len(text) and text[i] == \"&\" and text[i+1] != \"&\":\n \n #create subtring for speacial char till \";\"\n for j in range(i , len(text)):\n if text[j] == \";\":\n bag += text[j]\n break\n else:\n bag += text[j]\n \n #if that not present in dict we added same as it is\n if bag not in d:\n ans += bag\n else:\n ans += d[bag]\n \n #increment by length of bag \n i += len(bag)\n \n #otherwise increment by 1\n else:\n ans += text[i]\n i += 1\n return ans\n ", "solution_js": "/**\n * @param {string} text\n * @return {string}\n */\nvar entityParser = function(text) {\n const entityMap = {\n '"': `\"`,\n ''': `'`,\n '&': `&`,\n '>': `>`,\n '<': `<`,\n '⁄': `/`\n }\n \n stack = [], entity = \"\";\n \n for(const char of text) {\n stack.push(char);\n if(char == '&') {\n if(entity.length > 0) entity = \"\";\n entity += char;\n }\n else if(char == ';' && entity.length > 0) {\n entity += char;\n \n if(entity in entityMap) {\n while(stack.length && stack[stack.length - 1] !== '&') {\n stack.pop();\n }\n stack.pop();\n stack.push(entityMap[entity]);\n }\n \n entity = \"\";\n }\n else if(entity.length > 0) {\n entity += char;\n }\n }\n \n return stack.join('');\n};", "solution_java": "class Solution {\n public String entityParser(String text) {\n return text.replace(\""\",\"\\\"\").replace(\"'\",\"'\").replace(\">\",\">\").replace(\"<\",\"<\").replace(\"⁄\",\"/\").replace(\"&\",\"&\");\n }\n}", "solution_c": "class Solution {\npublic:\n string entityParser(string text) {\n mapmp;\n mp[\""\"] = '\\\"';\n mp[\"'\"] = '\\'';\n mp[\"&\"] = '&';\n mp[\">\"] = '>';mp[\"<\"]='<';\n mp[\"⁄\"] = '/';\n \n for(int i =0;i>temp) {\n if(temp.compare(0, sw.size(),sw)==0) return i;\n i++;\n }\n return -1;\n }\n};" }, { "title": "Moving Stones Until Consecutive", "algo_input": "There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.\n\nIn one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.\n\nThe game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\n\nReturn an integer array answer of length 2 where:\n\n\n\tanswer[0] is the minimum number of moves you can play, and\n\tanswer[1] is the maximum number of moves you can play.\n\n\n \nExample 1:\n\nInput: a = 1, b = 2, c = 5\nOutput: [1,2]\nExplanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.\n\n\nExample 2:\n\nInput: a = 4, b = 3, c = 2\nOutput: [0,0]\nExplanation: We cannot make any moves.\n\n\nExample 3:\n\nInput: a = 3, b = 5, c = 1\nOutput: [1,2]\nExplanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.\n\n\n \nConstraints:\n\n\n\t1 <= a, b, c <= 100\n\ta, b, and c have different values.\n\n", "solution_py": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n a,b,c = sorted([a,b,c])\n d1 = abs(b-a)-1 \n d2 = abs(c-b)-1\n mi = 2\n if d1 == 0 and d2 == 0: mi = 0\n elif d1 <= 1 or d2 <= 1: mi =1 \n ma = c - a - 2\n return [mi,ma]", "solution_js": "var numMovesStones = function(a, b, c) {\n const nums = [a, b, c];\n\n nums.sort((a, b) => a - b);\n\n const leftGap = nums[1] - nums[0] - 1;\n const rightGap = nums[2] - nums[1] - 1;\n\n const maxMoves = leftGap + rightGap;\n\n if (leftGap == 0 && rightGap == 0) return [0, 0];\n if (leftGap > 1 && rightGap > 1) return [2, maxMoves];\n return [1, maxMoves];\n};", "solution_java": "class Solution {\n public int[] numMovesStones(int a, int b, int c) {\n int[] arr ={a,b,c};\n int[] arr2 = {a,b,c};\n int maximum = findMaximum(arr);\n int minimum = findMinimum(maximum,arr2);\n return new int[]{minimum,maximum};\n }\n public int findMaximum(int[] arr){\n Arrays.sort(arr);\n int count = 0;\n if(arr[0] == (arr[1]-1) && arr[1] == (arr[2] -1) ) return count;\n if(arr[0] == arr[1]-1){\n arr[2]--;\n count++;\n }\n else{\n arr[0]++;\n count++;\n }\n return count + findMaximum(arr);\n\n }\n\n public int findMinimum(int max,int[] arr){\n Arrays.sort(arr);\n if(max == 0) return 0;\n else if(Math.abs(arr[0]-arr[1]) >2 && Math.abs(arr[1]-arr[2]) >2 ) return 2;\n else return 1;\n }\n}", "solution_c": "class Solution {\npublic:\n\n vector numMovesStones(int a, int b, int c) {\n\n vector arr = {a, b, c};\n\n sort(arr.begin(), arr.end());\n\n // find minimum moves\n\n int mini = 0;\n\n if(arr[1] - arr[0] == 1 && arr[2] - arr[1] == 1)\n {\n mini = 0;\n }\n else if(arr[1] - arr[0] <= 2 || arr[2] - arr[1] <= 2)\n {\n mini = 1;\n }\n else\n {\n mini = 2;\n }\n\n // find maximum moves\n\n int maxi = (arr[1] - arr[0] - 1) + (arr[2] - arr[1] - 1);\n\n return {mini, maxi};\n }\n};" }, { "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", "algo_input": "Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.\n\n \nExample 1:\n\nInput: nums = [1,1,1,1,1], target = 2\nOutput: 2\nExplanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).\n\n\nExample 2:\n\nInput: nums = [-1,3,5,1,4,2,-9], target = 6\nOutput: 2\nExplanation: There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\t0 <= target <= 106\n\n", "solution_py": "'''\ngreedy, prefix sum with hashtable\nO(n), O(n)\n'''\nclass Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n # hash set to record previously encountered prefix sums\n prefix_sums = {0}\n \n res = prefix_sum = 0\n for num in nums:\n prefix_sum += num\n if prefix_sum - target in prefix_sums:\n res += 1\n # greedily discard prefix sums before num\n # thus not considering subarrays that start at before num \n prefix_sums = {prefix_sum} \n else:\n prefix_sums.add(prefix_sum)\n return res", "solution_js": "var maxNonOverlapping = function(nums, target) {\n const seen = new Set();\n let total = 0, result = 0;\n \n for(let n of nums) {\n total += n;\n \n if(total === target || seen.has(total - target)) {\n total = 0;\n result++;\n seen.clear()\n } else seen.add(total)\n }\n return result;\n};", "solution_java": "class Solution {\n public int maxNonOverlapping(int[] nums, int target) {\n Map valToPos = new HashMap<>();\n int sums = 0;\n int count = 0;\n int lastEndPos = 0;\n valToPos.put(0, 0);\n for (int i = 0; i < nums.length; i++) {\n sums += nums[i];\n int pos = valToPos.getOrDefault(sums - target, -1);\n if (pos >= lastEndPos) {\n count += 1;\n lastEndPos = i + 1;\n }\n valToPos.put(sums, i + 1);\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n unordered_map mpp ;\n int maxNonOverlapping(vector& nums, int target) {\n\n int sum = 0 , ways = 0 , prev = INT_MIN ;\n mpp[0] = -1 ;\n for(int i = 0 ; i < nums.size() ; ++i ){\n sum += nums[i] ;\n if(mpp.find(sum - target) != end(mpp) and mpp[sum-target] >= prev ) ++ways , prev = i ;\n mpp[sum] = i ;\n }\n return ways ;\n }\n};" }, { "title": "Maximum Building Height", "algo_input": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.\n\nHowever, there are city restrictions on the heights of the new buildings:\n\n\n\tThe height of each building must be a non-negative integer.\n\tThe height of the first building must be 0.\n\tThe height difference between any two adjacent buildings cannot exceed 1.\n\n\nAdditionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.\n\nIt is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.\n\nReturn the maximum possible height of the tallest building.\n\n \nExample 1:\n\nInput: n = 5, restrictions = [[2,1],[4,1]]\nOutput: 2\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\n\nExample 2:\n\nInput: n = 6, restrictions = []\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\n\n\nExample 3:\n\nInput: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 109\n\t0 <= restrictions.length <= min(n - 1, 105)\n\t2 <= idi <= n\n\tidi is unique.\n\t0 <= maxHeighti <= 109\n\n", "solution_py": "class Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n arr = restrictions\n arr.extend([[1,0],[n,n-1]])\n arr.sort()\n n = len(arr)\n for i in range(1,n):\n arr[i][1] = min(arr[i][1], arr[i-1][1]+arr[i][0]-arr[i-1][0])\n for i in range(n-2,-1,-1):\n arr[i][1] = min(arr[i][1], arr[i+1][1]+arr[i+1][0]-arr[i][0])\n res = 0\n for i in range(1,n):\n #position where height can be the highest between arr[i-1][0] and arr[i][0]\n k = (arr[i][1]-arr[i-1][1]+arr[i][0]+arr[i-1][0])//2\n res = max(res, arr[i-1][1]+k-arr[i-1][0])\n return res", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} restrictions\n * @return {number}\n */\nvar maxBuilding = function(n, restrictions) {\n let maxHeight=0;\n restrictions.push([1,0]);//Push extra restriction as 0 for 1\n restrictions.push([n,n-1]);//Push extra restrition as n-1 for n\n restrictions.sort(function(a,b){return a[0]-b[0]});\n //Propogate from left to right to tighten the restriction: Check building restriction can be furhter tightened due to the left side building restriction.\n for(let i=1;i=0;i--){\n restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i+1][0]-restrictions[i][0])+restrictions[i+1][1]);\n }\n let max=0;\n for(let i=0;i list=new ArrayList<>();\n list.add(new int[]{1,0});\n for(int[] restriction:restrictions){\n list.add(restriction);\n }\n Collections.sort(list,new IDSorter());\n\n if(list.get(list.size()-1)[0]!=n){\n list.add(new int[]{n,n-1});\n }\n\n for(int i=1;i=0;i--){\n list.get(i)[1]=Math.min(list.get(i)[1],list.get(i+1)[1] + list.get(i+1)[0] - list.get(i)[0]);\n }\n\n int result=0;\n for(int i=1;i{\n @Override\n public int compare(int[] myself,int[] other){\n return myself[0]-other[0];\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int maxBuilding(int n, vector>& restrictions) {\n restrictions.push_back({1, 0});\n restrictions.push_back({n, n-1}); \n sort(restrictions.begin(), restrictions.end()); \n for (int i = restrictions.size()-2; i >= 0; --i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]); \n }\n \n int ans = 0; \n for (int i = 1; i < restrictions.size(); ++i) {\n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]); \n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])/2); \n }\n return ans; \n }\n};" }, { "title": "Find Winner on a Tic Tac Toe Game", "algo_input": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:\n\n\n\tPlayers take turns placing characters into empty squares ' '.\n\tThe first player A always places 'X' characters, while the second player B always places 'O' characters.\n\t'X' and 'O' characters are always placed into empty squares, never on filled ones.\n\tThe game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\n\tThe game also ends if all squares are non-empty.\n\tNo more moves can be played if the game is over.\n\n\nGiven a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return \"Draw\". If there are still movements to play return \"Pending\".\n\nYou can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.\n\n \nExample 1:\n\nInput: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput: \"A\"\nExplanation: A wins, they always play first.\n\n\nExample 2:\n\nInput: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput: \"B\"\nExplanation: B wins.\n\n\nExample 3:\n\nInput: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput: \"Draw\"\nExplanation: The game ends in a draw since there are no moves to make.\n\n\n \nConstraints:\n\n\n\t1 <= moves.length <= 9\n\tmoves[i].length == 2\n\t0 <= rowi, coli <= 2\n\tThere are no repeated elements on moves.\n\tmoves follow the rules of tic tac toe.\n\n", "solution_py": "class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n wins = [\n [(0, 0), (0, 1), (0, 2)],\n [(1, 0), (1, 1), (1, 2)],\n [(2, 0), (2, 1), (2, 2)],\n [(0, 0), (1, 0), (2, 0)],\n [(0, 1), (1, 1), (2, 1)],\n [(0, 2), (1, 2), (2, 2)],\n [(0, 0), (1, 1), (2, 2)],\n [(0, 2), (1, 1), (2, 0)],\n ]\n \n def checkWin(S):\n for win in wins:\n flag = True\n for pos in win:\n if pos not in S:\n flag = False\n break\n if flag:\n return True\n return False\n \n A, B = set(), set()\n for i, (x, y) in enumerate(moves):\n if i % 2 == 0:\n A.add((x, y))\n else:\n B.add((x, y))\n \n if checkWin(A):\n return 'A'\n elif checkWin(B):\n return 'B'\n \n return \"Draw\" if len(moves) == 9 else \"Pending\"", "solution_js": "/**\n * @param {number[][]} moves\n * @return {string}\n */\nlet validate = (arr) => {\n let set = [...new Set(arr)];\n return set.length == 1 && set[0] != 0;\n}\n\nvar tictactoe = function(moves) {\n let grid = [[0,0,0],[0,0,0],[0,0,0]];\n for(let i in moves){\n let [x,y] = moves[i]\n grid[x][y] = (i % 2 == 1) ? -1 : 1;\n if(validate(grid[x]) \n || validate(grid.reduce((prev, curr) => [...prev, curr[y]], []))\n || validate([grid[0][0], grid[1][1], grid[2][2]])\n || validate([grid[0][2], grid[1][1], grid[2][0]])\n )\n return (i % 2) ? \"B\" : \"A\";\n }\n return (moves.length == 9) ? \"Draw\" : \"Pending\"\n};", "solution_java": "/**\nHere is my solution : \n\nTime Complexity O(M) \nSpace Complaexity O(1)\n*/\n\nclass Solution {\n public String tictactoe(int[][] moves) {\n \n int [][] rcd = new int[3][3]; // rcd[0] --> rows , rcd[1] --> columns , rcd[2] --> diagonals\n \n for(int turn =0 ; turn < moves.length ; turn++){\n \n\t\t\tint AorB =-1;\n if(turn%2==0){AorB=1;}\n \n rcd[0][moves[turn][0]]+= AorB; \n rcd[1][moves[turn][1]]+= AorB; \n \n if(moves[turn][0]== moves[turn][1]){rcd[2][0]+=AorB;} // first diagonal\n if(moves[turn][0]+moves[turn][1]-2 == 0){rcd[2][1]+=AorB;} //2nd diagonal \n \n if( Math.abs(rcd[0][moves[turn][0]]) == 3 || Math.abs(rcd[1][moves[turn][1]]) == 3 \n ||Math.abs(rcd[2][0]) ==3 || Math.abs(rcd[2][1]) ==3 ){\n \n\t\t\t return AorB == 1 ? \"A\" : \"B\"; }\n } \n \n return moves.length == 9 ? \"Draw\" : \"Pending\";\n \n }\n}", "solution_c": "class Solution {\npublic:\n string tictactoe(vector>& moves)\n {\n vector> grid(3,vector(3));\n char val='x';\n for(auto &p:moves)\n {\n grid[p[0]][p[1]]=val;\n\n val=val=='x'?'o':'x';\n }\n for (int i = 0; i < 3; i++){\n //check row\n if (grid[i][0] == 'x' && grid[i][1] == 'x' && grid[i][2] == 'x')return \"A\";\n if (grid[i][0] == 'o' && grid[i][1] == 'o' && grid[i][2] == 'o')return \"B\";\n\n //check columns\n if (grid[0][i] == 'x' && grid[1][i] == 'x' && grid[2][i] == 'x')return \"A\";\n if (grid[0][i] == 'o' && grid[1][i] == 'o' && grid[2][i] == 'o')return \"B\";\n }\n //check diagonal\n if (grid[0][0] == 'x' && grid[1][1] == 'x' && grid[2][2] == 'x')return \"A\";\n if (grid[0][2] == 'x' && grid[1][1] == 'x' && grid[2][0] == 'x')return \"A\";\n if (grid[0][0] == 'o' && grid[1][1] == 'o' && grid[2][2] == 'o')return \"B\";\n if (grid[0][2] == 'o' && grid[1][1] == 'o' && grid[2][0] == 'o')return \"B\";\n\n if(moves.size()==9)\n {\n return \"Draw\";\n }\n return \"Pending\";\n\n }\n};\n//if you like the solution plz upvote." }, { "title": "Minimum Time to Finish the Race", "algo_input": "You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.\n\n\n\tFor example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc.\n\n\nYou are also given an integer changeTime and an integer numLaps.\n\nThe race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds.\n\nReturn the minimum time to finish the race.\n\n \nExample 1:\n\nInput: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\nOutput: 21\nExplanation: \nLap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.\n\n\nExample 2:\n\nInput: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\nOutput: 25\nExplanation: \nLap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds. \n\n\n \nConstraints:\n\n\n\t1 <= tires.length <= 105\n\ttires[i].length == 2\n\t1 <= fi, changeTime <= 105\n\t2 <= ri <= 105\n\t1 <= numLaps <= 1000\n\n", "solution_py": "class Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n # by observation, we can try to find out the optimal usage within certain numLaps\n # use DP\n # the optimal usage of this lap = min(change tire , no change)\n # dp(laps) = min( dp(laps-1)+dp(1) + dp(laps-2)+dp(2) + ...)\n \n # we don't want to use tires too many laps, which will create unrealistic single lap time\n\t\t# we can evaluate single lap time by using changeTime <= 100000 and r >= 2\n\t\t# x = minimal continously laps\n\t\t# single lap time = 1*2^x <= 100000 -> x can't go more than 19\n\t\tlimit = 19\n tires = list(set([(t1, t2) for t1, t2 in tires]))\n memo = [[(-1,-1) for _ in range(min(limit,numLaps)+1)] for _ in range(len(tires))]\n \n for i in range(len(tires)):\n for j in range(1, min(limit,numLaps)+1): # lap 1 to numLaps\n if j == 1:\n memo[i][j] = (tires[i][0], tires[i][0]) # total time, lap time\n else:\n # print('i, j', i, j)\n tmp = memo[i][j-1][1]*tires[i][1] # cost of continuously use tire this lap\n memo[i][j] = (memo[i][j-1][0]+tmp, tmp)\n \n @cache\n def dp(laps):\n if laps == 1:\n return min(memo[i][1][0] for i in range(len(tires)))\n \n # no change:\n best_time = min(memo[i][laps][0] for i in range(len(tires))) if laps <= limit else float('inf')\n \n # change tire:\n\t\t\t# e.g. change tire at this lap and see if it'll be faster -> dp(laps-1) + changeTime + dp(1)\n # check all previous laps: dp(a) + changeTime + dp(b) until a < b\n for j in range(1, laps):\n a, b = laps-j, j\n if a >= b:\n ta = dp(a)\n tb = dp(b)\n if ta+tb+changeTime < best_time:\n best_time = ta+tb+changeTime\n return best_time\n \n return dp(numLaps)", "solution_js": "var minimumFinishTime = function(tires, changeTime, numLaps) { \n const n = tires.length\n const smallestTire = Math.min(...tires.map(t => t[1]))\n const maxSameTire = Math.floor(Math.log(changeTime) / Math.log(smallestTire)) + 1\n const sameTireLast = Array(n).fill(0)\n\t\n\t// DP array tracking what is the min cost to complete lap i using same tire\n const sameTire = Array(maxSameTire + 1).fill(Infinity)\n for (let lap = 1; lap <= maxSameTire; lap++) {\n tires.forEach((tire, i) => {\n sameTireLast[i] += tire[0] * tire[1] ** (lap - 1)\n sameTire[lap] = Math.min(sameTire[lap], sameTireLast[i])\n })\n }\n \n const dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 1; i < numLaps + 1; i++) {\n if (i <= maxSameTire) dp[i] = sameTire[i]\n\t\t// at each lap, we can either use the same tire up to this lap (sameTire[i])\n\t\t// or a combination of 2 different best times, \n\t\t// eg lap 6: use best time from lap 3 + lap 3\n\t\t// or from lap 4 + lap 2\n\t\t// or lap 5 + lap 1\n for (let j = 1; j < i / 2 + 1; j++) {\n dp[i] = Math.min(dp[i], dp[i-j] + changeTime + dp[j])\n }\n }\n return dp[numLaps]\n};", "solution_java": "class Solution {\n int changeTime;\n public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n this.changeTime = changeTime;\n int[] minTime = new int[numLaps + 1];\n Arrays.fill(minTime, Integer.MAX_VALUE);\n\n for (int[] tire : tires){\n populateMinTime(tire, minTime);\n }\n\n int[] dp = new int[numLaps + 1];\n for (int i = 1; i <= numLaps; i++){\n dp[i] = minTime[i]; // maxValue for dp[i] is Integer.MAX_VALUE, no need to worry about overflow\n for (int j = 1; j < i; j++){\n dp[i] = Math.min(dp[i], dp[j] + changeTime + dp[i - j]); // it will never overflow, since dp[j] are far less than Integer.MAX_VALUE\n }\n }\n return dp[numLaps];\n }\n\n private void populateMinTime(int[] tire, int[] minTime){\n int sum = 0;\n int base = tire[0];\n int ex = tire[1];\n int spent = 1;\n for (int i = 1; i < minTime.length; i++){\n spent = (i == 1) ? base : spent * ex;\n if (spent > changeTime + base){break;} // set boundary\n sum += spent;\n minTime[i] = Math.min(minTime[i], sum);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumFinishTime(vector>& tires, int changeTime, int numLaps) {\n int n = tires.size();\n // to handle the cases where numLaps is small\n // without_change[i][j]: the total time to run j laps consecutively with tire i\n vector> without_change(n, vector(20, 2e9));\n for (int i = 0; i < n; i++) {\n without_change[i][1] = tires[i][0];\n for (int j = 2; j < 20; j++) {\n if ((long long)without_change[i][j-1] * tires[i][1] >= 2e9)\n break;\n without_change[i][j] = without_change[i][j-1] * tires[i][1];\n }\n // since we define it as the total time, rather than just the time for the j-th lap\n // we have to make it prefix sum\n for (int j = 2; j < 20; j++) {\n if ((long long)without_change[i][j-1] + without_change[i][j] >= 2e9)\n break;\n without_change[i][j] += without_change[i][j-1];\n }\n }\n\n // dp[x]: the minimum time to finish x laps\n vector dp(numLaps+1, 2e9);\n for (int i = 0; i < n; i++) {\n dp[1] = min(dp[1], tires[i][0]);\n }\n for (int x = 1; x <= numLaps; x++) {\n if (x < 20) {\n // x is small enough, so an optimal solution might never changes tires!\n for (int i = 0; i < n; i++) {\n dp[x] = min(dp[x], without_change[i][x]);\n }\n }\n for (int j = x-1; j > 0 && j >= x-18; j--) {\n dp[x] = min(dp[x], dp[j] + changeTime + dp[x-j]);\n }\n }\n\n return dp[numLaps];\n }\n};" }, { "title": "Validate Binary Tree Nodes", "algo_input": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.\n\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\n\nNote that the nodes have no values and that we only use the node numbers in this problem.\n\n \nExample 1:\n\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\n\n\nExample 2:\n\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\n\n\nExample 3:\n\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n\n\n \nConstraints:\n\n\n\tn == leftChild.length == rightChild.length\n\t1 <= n <= 104\n\t-1 <= leftChild[i], rightChild[i] <= n - 1\n\n", "solution_py": " class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \n left_set=set(leftChild)\n right_set=set(rightChild) \n\n que=[]\n\n for i in range(n):\n if i not in left_set and i not in right_set:\n que.append(i)\n \n if len(que)>1 or len(que)==0:\n return False\n \n \n graph=defaultdict(list)\n\n for i in range(n):\n graph[i]=[]\n\n if leftChild[i]!=-1:\n graph[i].append(leftChild[i])\n\n if rightChild[i]!=-1:\n graph[i].append(rightChild[i])\n \n visited=set()\n visited.add(que[0])\n \n \n while len(que)>0:\n item=que.pop(0)\n \n\n children=graph[item]\n\n for child in children:\n if child not in visited:\n que.append(child)\n visited.add(child)\n else:\n return False\n\n\n for i in range(n):\n if i not in visited:\n return False\n\n return True", "solution_js": "var validateBinaryTreeNodes = function(n, leftChild, rightChild) {\n\t// find in-degree for each node\n const inDeg = new Array(n).fill(0);\n for(let i = 0; i < n; ++i) {\n if(leftChild[i] !== -1) {\n ++inDeg[leftChild[i]]; \n }\n if(rightChild[i] !== -1) {\n ++inDeg[rightChild[i]];\n }\n }\n\t// find the root node and check each node has only one in-degree\n let rootNodeId = -1;\n for(let i = 0; i < n; ++i) {\n if(inDeg[i] === 0) {\n rootNodeId = i;\n } else if(inDeg[i] > 1) {\n return false;\n }\n }\n\t// if no root node found -> invalid BT\n if(rootNodeId === -1) {\n return false;\n }\n\t// BFS to check that each node is visited at least and at most once\n const visited = new Set();\n const queue = [rootNodeId];\n \n while(queue.length) {\n const nodeId = queue.shift();\n \n if(visited.has(nodeId)) {\n return false;\n }\n visited.add(nodeId);\n \n const leftNode = leftChild[nodeId],\n rightNode = rightChild[nodeId];\n if(leftNode !== -1) {\n queue.push(leftNode);\n }\n if(rightNode !== -1) {\n queue.push(rightNode);\n }\n }\n\t// checking each node is visited at least once\n return visited.size === n;};", "solution_java": "import java.util.Arrays;\n\nclass Solution {\n static class UF {\n int[] parents;\n int size;\n UF(int n) {\n parents = new int[n];\n size = n;\n Arrays.fill(parents, -1);\n }\n \n int find(int x) {\n if (parents[x] == -1) {\n return x;\n }\n return parents[x] = find(parents[x]);\n }\n\n boolean union(int a, int b) {\n int pA = find(a), pB = find(b);\n if (pA == pB) {\n return false;\n }\n parents[pA] = pB;\n size--;\n return true;\n }\n\n boolean connected() {\n return size == 1;\n }\n }\n public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {\n UF uf = new UF(n);\n int[] indeg = new int[n];\n for (int i = 0; i < n; i++) {\n int l = leftChild[i], r = rightChild[i];\n if (l != -1) {\n /**\n * i: parent node\n * l: left child node\n * if i and l are already connected or the in degree of l is already 1\n */\n if (!uf.union(i, l) || ++indeg[l] > 1) {\n return false;\n }\n }\n if (r != -1) {\n // Same thing for parent node and the right child node\n if (!uf.union(i, r) || ++indeg[r] > 1) {\n return false;\n }\n }\n }\n return uf.connected();\n }\n}", "solution_c": "class Solution {\npublic:\n int find_parent(vector&parent,int x){\n if(parent[x]==x)\n return x;\n return parent[x]=find_parent(parent,parent[x]);\n }\n bool validateBinaryTreeNodes(int n, vector& leftChild, vector& rightChild) {\n vector parent(n);\n for(int i=0;i int:\n return sum(accumulate(c for _,c in sorted(Counter(nums).items(), reverse=True)[:-1]))", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar reductionOperations = function(nums) {\n nums.sort((a,b)=>a-b);\n let count = 0;\n for(let i = nums.length - 1;i>0;i--)\n if(nums[i] !== nums[i-1])\n count += nums.length - i\n return count\n};", "solution_java": "class Solution {\n public int reductionOperations(int[] nums) {\n Map valMap = new TreeMap<>(Collections.reverseOrder());\n\n for (int i=0; i entry : valMap.entrySet()) {\n opsCount += entry.getValue() * (--mapSize);\n }\n return opsCount;\n }\n}", "solution_c": "class Solution {\npublic:\n int reductionOperations(vector& nums) {\n int n = nums.size();\n \n map mp;\n for(int i = 0; i < n; i ++) {\n mp[nums[i]] ++; // storing the frequency\n }\n \n int ans = 0;\n int pre = 0;\n for (auto i = mp.end(); i != mp.begin(); i--) {\n ans += i -> second + pre; // total operations\n pre += i -> second; // maintaing the previous frequency count\n }\n return ans;\n }\n};" }, { "title": "Minimum Number of K Consecutive Bit Flips", "algo_input": "You are given a binary array nums and an integer k.\n\nA k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\n\nReturn the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.\n\nA subarray is a contiguous part of an array.\n\n \nExample 1:\n\nInput: nums = [0,1,0], k = 1\nOutput: 2\nExplanation: Flip nums[0], then flip nums[2].\n\n\nExample 2:\n\nInput: nums = [1,1,0], k = 2\nOutput: -1\nExplanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].\n\n\nExample 3:\n\nInput: nums = [0,0,0,1,0,1,1,0], k = 3\nOutput: 3\nExplanation: \nFlip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= k <= nums.length\n\n", "solution_py": "class Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n flips = [0]*len(nums)\n csum = 0\n\n for left in range(0, len(nums)-k+1):\n if (nums[left] + csum) % 2 == 0:\n flips[left] += 1\n csum += 1\n if left >= k-1:\n csum -= flips[left-k+1]\n\n for check in range(len(nums)-k+1, len(nums)):\n if (nums[check] + csum) % 2 == 0:\n return -1\n if check >= k-1:\n csum -= flips[check-k+1]\n\n return sum(flips)", "solution_js": "var minKBitFlips = function(nums, k) {\n let count = 0\n \n for(let i=0; i n ==1) ? count : -1\n};", "solution_java": "class Solution {\n public int minKBitFlips(int[] nums, int k) {\n int target = 0, ans = 0;;\n boolean[] flip = new boolean[nums.length+1];\n for (int i = 0; i < nums.length; i++){\n if (flip[i]){\n target^=1;\n }\n if (inums.length-k&&nums[i]==target){\n return -1;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minKBitFlips(vector& nums, int k) {\n \n int n = nums.size();\n \n int flips = 0; // flips on current positions\n vector flip(n+1,0); // to set end pointer for a flip i.e i+k ->-1\n int ops = 0; // answer\n \n for(int i=0;i n){\n return -1;\n }\n \n ops++; //increment ans\n flips++; // do flip at this position\n flip[i+k] = -1; // set poiter where current flip ends\n \n }\n \n return ops;\n \n }\n};" }, { "title": "Find Median from Data Stream", "algo_input": "The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.\n\n\n\tFor example, for arr = [2,3,4], the median is 3.\n\tFor example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.\n\n\nImplement the MedianFinder class:\n\n\n\tMedianFinder() initializes the MedianFinder object.\n\tvoid addNum(int num) adds the integer num from the data stream to the data structure.\n\tdouble findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.\n\n\n \nExample 1:\n\nInput\n[\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n[[], [1], [2], [], [3], []]\nOutput\n[null, null, null, 1.5, null, 2.0]\n\nExplanation\nMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0\n\n\n \nConstraints:\n\n\n\t-105 <= num <= 105\n\tThere will be at least one element in the data structure before calling findMedian.\n\tAt most 5 * 104 calls will be made to addNum and findMedian.\n\n\n \nFollow up:\n\n\n\tIf all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?\n\tIf 99% of all integer numbers from the stream are in the range [0, 100], how would you optimize your solution?\n\n", "solution_py": "class MedianFinder:\n\n def __init__(self):\n self.min_hp = []\n self.max_hp = []\n \n def addNum(self, num: int) -> None:\n if len(self.min_hp) == len(self.max_hp):\n if len(self.max_hp) and num<-self.max_hp[0]:\n cur = -heapq.heappop(self.max_hp)\n heapq.heappush(self.max_hp, -num)\n heapq.heappush(self.min_hp, cur)\n else:\n heapq.heappush(self.min_hp, num)\n else:\n if num>self.min_hp[0]:\n cur = heapq.heappop(self.min_hp)\n heapq.heappush(self.min_hp, num)\n heapq.heappush(self.max_hp, -cur)\n else:\n heapq.heappush(self.max_hp, -num)\n \n def findMedian(self) -> float:\n if len(self.min_hp) == len(self.max_hp):\n return (self.min_hp[0] + -self.max_hp[0]) /2\n else:\n return self.min_hp[0]", "solution_js": "var MedianFinder = function() {\n this.left = new MaxPriorityQueue();\n this.right = new MinPriorityQueue();\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nMedianFinder.prototype.addNum = function(num) {\nlet { right, left } = this\n if (right.size() > 0 && num > right.front().element) {\n right.enqueue(num)\n } else {\n left.enqueue(num)\n }\n\n if (Math.abs(left.size() - right.size()) == 2) {\n if (left.size() > right.size()) {\n right.enqueue(left.dequeue().element)\n } else {\n left.enqueue(right.dequeue().element)\n }\n }\n};\n\n/**\n * @return {number}\n */\nMedianFinder.prototype.findMedian = function() {\n let { left, right } = this\n if (left.size() > right.size()) {\n return left.front().element\n } else if(right.size() > left.size()) {\n return right.front().element\n } else{\n // get the sum of all\n return (left.front().element + right.front().element) / 2\n }\n};\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * var obj = new MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */", "solution_java": "class MedianFinder {\n\n PriorityQueue maxHeap;\n PriorityQueue minHeap;\n\n public MedianFinder() {\n maxHeap= new PriorityQueue((a,b)->b-a);\n minHeap= new PriorityQueue();\n }\n\n public void addNum(int num) {\n\n //Pushing\n if ( maxHeap.isEmpty() || ((int)maxHeap.peek() > num) ){\n maxHeap.offer(num);\n }\n else{\n minHeap.offer(num);\n }\n\n //Balancing\n if ( maxHeap.size() > minHeap.size()+ 1){\n minHeap.offer(maxHeap.peek());\n maxHeap.poll();\n }\n else if (minHeap.size() > maxHeap.size()+ 1 ){\n maxHeap.offer(minHeap.peek());\n minHeap.poll();\n }\n\n }\n\n public double findMedian() {\n\n //Evaluating Median\n if ( maxHeap.size() == minHeap.size() ){ // Even Number\n return ((int)maxHeap.peek()+ (int)minHeap.peek())/2.0;\n }\n else{ //Odd Number\n if ( maxHeap.size() > minHeap.size()){\n return (int)maxHeap.peek()+ 0.0;\n }\n else{ // minHeap.size() > maxHeap.size()\n return (int)minHeap.peek()+ 0.0;\n }\n }\n }\n}", "solution_c": "class MedianFinder {\npublic:\n /* Implemented @StefanPochmann's Incridible Idea */\n priority_queue small, large;\n MedianFinder() {\n \n }\n \n void addNum(int num) {\n small.push(num); // cool three step trick\n large.push(-small.top());\n small.pop();\n while(small.size() < large.size()){\n small.push(-large.top());\n large.pop();\n }\n }\n \n double findMedian() {\n return small.size() > large.size()\n ? small.top()\n : (small.top() - large.top())/2.0;\n }\n};" }, { "title": "Reformat Date", "algo_input": "Given a date string in the form Day Month Year, where:\n\n\n\tDay is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"}.\n\tMonth is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"}.\n\tYear is in the range [1900, 2100].\n\n\nConvert the date string to the format YYYY-MM-DD, where:\n\n\n\tYYYY denotes the 4 digit year.\n\tMM denotes the 2 digit month.\n\tDD denotes the 2 digit day.\n\n\n \nExample 1:\n\nInput: date = \"20th Oct 2052\"\nOutput: \"2052-10-20\"\n\n\nExample 2:\n\nInput: date = \"6th Jun 1933\"\nOutput: \"1933-06-06\"\n\n\nExample 3:\n\nInput: date = \"26th May 1960\"\nOutput: \"1960-05-26\"\n\n\n \nConstraints:\n\n\n\tThe given dates are guaranteed to be valid, so no error handling is necessary.\n\n", "solution_py": "class Solution:\n def reformatDate(self, date: str) -> str:\n\n m_dict_={\"Jan\":\"01\", \"Feb\":\"02\", \"Mar\":\"03\", \"Apr\":\"04\", \"May\":\"05\", \"Jun\":\"06\", \"Jul\":\"07\", \"Aug\":\"08\", \"Sep\":\"09\", \"Oct\":\"10\", \"Nov\":\"11\", \"Dec\":\"12\"}\n\n day=date[:-11]\n\n if len(day)==1:\n day=\"0\"+day\n\n return(date[-4:] + \"-\" + m_dict_[date[-8:-5]] + \"-\" + day)", "solution_js": "var reformatDate = function(date) {\n const ans = [];\n const month = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n \n const [inputDate,inputMonth,inputYear] = date.split(' ');\n ans.push(inputYear);\n ans.push(\"-\");\n \n const monthIndex = month.findIndex(mon => mon === inputMonth);\n const formatedMonth = String(monthIndex + 1).padStart(2,'0');\n ans.push(formatedMonth);\n ans.push(\"-\");\n \n const slicedDate = inputDate.slice(0,2);\n if(+slicedDate >= 10){\n ans.push(slicedDate);\n }else{\n const formatedDate = inputDate.slice(0,1).padStart(2,'0');\n ans.push(formatedDate)\n }\n \n return ans.join('');\n};", "solution_java": "class Solution {\n public String reformatDate(String date) {\n int len = date.length();\n \n String[] monthArray = {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"};\n \n String year = date.substring(len - 4);\n int month = Arrays.asList(monthArray).indexOf(date.substring(len - 8, len - 5)) + 1;\n String day = date.substring(0, len - 11);\n \n StringBuffer sb = new StringBuffer();\n \n sb.append(year + \"-\");\n \n if(month < 10)\n sb.append(\"0\" + month + \"-\");\n else\n sb.append(month + \"-\");\n \n if(day.length() == 1) \n sb.append(\"0\" + day);\n else\n sb.append(day);\n \n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string reformatDate(string date) {\n mapm;\n m[\"Jan\"] =1;\n m[\"Feb\"] =2;\n m[\"Mar\"] =3;\n m[\"Apr\"] =4;\n m[\"May\"] =5;\n m[\"Jun\"] =6;\n m[\"Jul\"] =7;\n m[\"Aug\"] =8;\n m[\"Sep\"] =9;\n m[\"Oct\"] =10;\n m[\"Nov\"] =11;\n m[\"Dec\"] =12;\n string ans;\n for(int i=date.length()-4; i int:\n ans,m=0,[0]*40401\n c=set(((x,y,r) for x,y,r in c))\n for x, y, r in c:\n for i in range(x-r, x+r+1):\n d=int(sqrt(r*r-(x-i)*(x-i)))\n m[i*201+y-d:i*201+y+d+1]=[1]*(d+d+1)\n return sum(m)", "solution_js": "var countLatticePoints = function(circles) {\n let minX=minY=Infinity, maxX=maxY=-Infinity;\n for(let i=0; i answer = new HashSet();\n \n for (int[] c : circles) {\n int x = c[0], y = c[1], r = c[2];\n \n // traversing over all the points that lie inside the smallest square capable of containing the whole circle\n for (int xx = x - r; xx <= x + r; xx++)\n for (int yy = y - r; yy <= y + r; yy++)\n if ((r * r) >= ((x - xx) * (x - xx)) + ((y - yy) * (y - yy)))\n answer.add(xx + \":\" + yy);\n }\n \n return answer.size();\n }\n}", "solution_c": "class Solution {\npublic:\n bool circle(int x , int y , int c1 , int c2, int r){\n if((x-c1)*(x-c1) + (y-c2)*(y-c2) <= r*r) \n return true ;\n return false ;\n }\n \n int countLatticePoints(vector>& circles) {\n int n = circles.size() , ans = 0 ;\n set> set ;\n for(auto v : circles){\n int r = v[2] , x = v[0] , y = v[1]; \n for(int i = x-r ; i <= x+r ; i++)\n for(int j = y-r ; j <= y+r ; j++)\n if(circle(i,j,x,y,r)){\n pair p(i,j) ;\n set.insert(p) ;\n }\n }\n return set.size() ;\n }\n};" }, { "title": "Distribute Candies to People", "algo_input": "We distribute some number of candies, to a row of n = num_people people in the following way:\n\nWe then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.\n\nThen, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.\n\nThis process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift).\n\nReturn an array (of length num_people and sum candies) that represents the final distribution of candies.\n\n \nExample 1:\n\nInput: candies = 7, num_people = 4\nOutput: [1,2,3,1]\nExplanation:\nOn the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\n\n\nExample 2:\n\nInput: candies = 10, num_people = 3\nOutput: [5,2,3]\nExplanation: \nOn the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n\n\n \nConstraints:\n\n\n\t1 <= candies <= 10^9\n\t1 <= num_people <= 1000\n\n", "solution_py": "class Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n candy_dict = {}\n for i in range(num_people) : \n candy_dict[i] = 0 \n \n candy, i, totalCandy = 1, 0, 0\n while totalCandy < candies : \n if i >= num_people : \n i = 0\n if candies - totalCandy >= candy : \n candy_dict[i] += candy \n totalCandy += candy\n else : \n candy_dict[i] += candies - totalCandy\n totalCandy += candies - totalCandy\n i += 1 \n candy += 1 \n return candy_dict.values()", "solution_js": "var distributeCandies = function(candies, num_people) {\n\n let i = 1, j=0;\n const result = new Array(num_people).fill(0);\n while(candies >0){\n result[j] += i;\n candies -= i;\n if(candies < 0){\n result[j] += candies;\n break;\n }\n j++;\n if(j === num_people)\n j=0;\n\n i++;\n }\n return result;\n};", "solution_java": "class Solution {\n public int[] distributeCandies(int candies, int num_people) {\n int n=num_people;\n int a[]=new int[n];\n int k=1;\n while(candies>0){\n for(int i=0;i=k){\n a[i]+=k;\n candies-=k;\n k++;\n }\n else{\n a[i]+=candies;\n candies=0;\n break;\n }\n }\n }\n return a;\n }\n}", "solution_c": "class Solution {\npublic:\n vector distributeCandies(int candies, int num_people) {\n vector Candies (num_people, 0);\n int X = 0;\n while (candies)\n {\n for (int i = 0; i < num_people; ++i)\n {\n int Num = X * num_people + i + 1;\n if (candies >= Num)\n {\n Candies[i] += Num;\n candies -= Num;\n }\n else\n {\n Candies[i] += candies;\n candies = 0;\n break;\n }\n }\n ++X;\n }\n return Candies;\n }\n};" }, { "title": "Maximize Score After N Operations", "algo_input": "You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\n\nIn the ith operation (1-indexed), you will:\n\n\n\tChoose two elements, x and y.\n\tReceive a score of i * gcd(x, y).\n\tRemove x and y from nums.\n\n\nReturn the maximum score you can receive after performing n operations.\n\nThe function gcd(x, y) is the greatest common divisor of x and y.\n\n \nExample 1:\n\nInput: nums = [1,2]\nOutput: 1\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1\n\n\nExample 2:\n\nInput: nums = [3,4,6,8]\nOutput: 11\nExplanation: The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,6]\nOutput: 14\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n\n\n \nConstraints:\n\n\n\t1 <= n <= 7\n\tnums.length == 2 * n\n\t1 <= nums[i] <= 106\n\n", "solution_py": "from functools import lru_cache\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n def gcd(a, b):\n while a:\n a, b = b%a, a\n return b\n halfplus = len(nums)//2 + 1\n @lru_cache(None)\n def dfs(mask, k):\n if k == halfplus:\n return 0\n res = 0\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n if not(mask & (1< gcdVal = new HashMap<>();\n for (int i = 0; i < n; ++i) {\n for (int j = i + 1; j < n; ++j) {\n gcdVal.put((1 << i) + (1 << j), gcd(nums[i], nums[j]));\n }\n }\n \n int[] dp = new int[1 << n];\n \n for (int i = 0; i < (1 << n); ++i) {\n int bits = Integer.bitCount(i); // how many numbers are used\n if (bits % 2 != 0) // odd numbers, skip it\n continue;\n for (int k : gcdVal.keySet()) {\n if ((k & i) != 0) // overlapping used numbers\n continue;\n dp[i ^ k] = Math.max(dp[i ^ k], dp[i] + gcdVal.get(k) * (bits / 2 + 1));\n }\n }\n \n return dp[(1 << n) - 1];\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}\n\n// Time: O(2^n * n^2)\n// Space: O(2 ^ n)", "solution_c": "int dp[16384];\nint gcd_table[14][14];\n\nclass Solution {\npublic:\n int maxScore(vector& nums) {\n memset(dp, -1, sizeof(dp));\n int sz = nums.size();\n\n // Build the GCD table \n for (int i = 0; i < sz; ++i) {\n for (int j = i+1; j < sz; ++j) {gcd_table[i][j] = gcd(nums[i], nums[j]);}\n }\n\n // Looping from state 0 to (1< int:\n return len(set(nums) - {0})", "solution_js": "var minimumOperations = function(nums) {\n let k = new Set(nums) // convert array to set; [...nums] is destructuring syntax\n return k.has(0) ? k.size-1 : k.size; // we dont need 0, hence if zero exists return size-1\n};", "solution_java": "class Solution {\n public int minimumOperations(int[] nums) {\n Set s = new HashSet<>();\n int result = 0;\n if(nums[0] == 0 && nums.length == 1){\n return 0;\n }\n else{\n for (int num : nums) {\n s.add(num);\n }\n for (int num : nums) {\n s.remove(0);\n }\n result = s.size();;\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumOperations(vector& nums) {\n priority_queue , greater > pq;\n \n for(int i=0;i str:\n def convertToInt(numStr):\n currNum = 0\n N = len(numStr)\n for i in range(N - 1, -1, -1):\n digit = ord(numStr[i]) - ord('0')\n currNum += pow(10, N-i-1) * digit\n \n return currNum\n \n n1 = convertToInt(num1)\n n2 = convertToInt(num2)\n return str(n1 * n2)\n ", "solution_js": "var multiply = function(num1, num2) {\n const m = num1.length;\n const n = num2.length;\n\n const steps = [];\n let carry = 0;\n for(let i = m - 1; i >= 0; i -= 1) {\n const digitOne = parseInt(num1[i]);\n let step = \"0\".repeat(m - 1 - i);\n\n carry = 0;\n for(let j = n - 1; j >= 0; j -= 1) {\n const digitTwo = parseInt(num2[j]);\n\n const product = digitOne * digitTwo + carry;\n const newDigit = product % 10;\n carry = Math.floor(product / 10);\n\n step = newDigit + step;\n }\n\n if(carry > 0) step = carry + step;\n steps.push(step);\n }\n\n for(let i = 0; i < steps.length - 1; i += 1) {\n let nextStep = steps[i + 1];\n let step = steps[i];\n step = \"0\".repeat(nextStep.length - step.length) + step;\n\n carry = 0;\n let newStep = \"\";\n for(let j = step.length - 1; j >= 0; j -= 1) {\n const sum = parseInt(nextStep[j]) + parseInt(step[j]) + carry;\n const digit = sum % 10;\n carry = Math.floor(sum / 10);\n newStep = digit + newStep;\n }\n\n if(carry > 0) newStep = carry + newStep;\n steps[i + 1] = newStep;\n }\n\n let result = steps[steps.length - 1];\n let leadingZeros = 0\n while(leadingZeros < result.length - 1 && result[leadingZeros] === '0') {\n leadingZeros += 1;\n }\n\n return result.slice(leadingZeros);\n};", "solution_java": "class Solution {\n public String multiply(String num1, String num2) {\n if(num1.equals(\"0\") || num2.equals(\"0\"))\n return \"0\";\n int[] arr=new int[num1.length()+num2.length()];\n\n int index=0;\n for(int i=num1.length()-1;i>=0;i--)\n {\n int carry=0;\n int column=0;\n for(int j=num2.length()-1;j>=0;j--)\n {\n int a=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');\n int temp=(arr[index+column]+carry+a);\n arr[index+column]=temp%10;\n carry=temp/10;\n column++;\n }\n if(carry!=0)\n {\n arr[index+column]=carry;\n }\n index++;\n }\n String ans=\"\";\n index=arr.length-1;\n while(arr[index]==0)\n {\n index--;\n }\n for(int i=index;i>=0;i--)\n {\n ans+=arr[i];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\n void compute(string &num, int dig, int ind, string &ans){\n int c = 0; // carry digit..\n int i = num.size()-1;\n // again travarsing the string in reverse\n while(i >= 0){\n int mul = dig*(num[i]-'0') + c; // the curr digit's multiplication\n c = mul/10; // carry update..\n mul %= 10; // mul update in a single digit..\n if(ind >= ans.length()){ // here if the index where we'll put the value is out of bounds...\n ans.push_back('0' + mul);\n }\n else{\n // here adding the val with the previous digit and further computing the carry...\n mul += (ans[ind] - '0');\n c += mul/10;\n mul %= 10;\n ans[ind] = ('0' + mul);\n }\n i--;\n ind++; // increment the index where we'll put the val;\n }\n \n if(c > 0){ // if carry is non-zero...\n ans.push_back('0' + c);\n }\n \n } \npublic:\n string multiply(string num1, string num2) {\n string ans = \"\"; // the string which we have to return as answer..\n if(num1 == \"0\" || num2 == \"0\") return \"0\"; // base case..\n int ind = 0; // the index from which we'll add the multiplied value to the ans string\n for(int i = num1.size()-1; i >= 0; ind++,i--){ \n // travarsing in reverse dir. on num1 and increasing ind bcz for every digit\n // of num1 we'll add the multiplication in a index greater than the previous iteration\n int dig = num1[i]-'0'; // the digit with which we'll multiply by num2..\n compute(num2, dig, ind, ans); // function call for every digit and num2\n }\n// we have calculated the ans in a reverse way such that we can easily add a leading digit & now reversing it...\n reverse(ans.begin(), ans.end()); \n return ans;\n }\n};" }, { "title": "Best Sightseeing Pair", "algo_input": "You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.\n\nThe score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.\n\nReturn the maximum score of a pair of sightseeing spots.\n\n \nExample 1:\n\nInput: values = [8,1,5,2,6]\nOutput: 11\nExplanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11\n\n\nExample 2:\n\nInput: values = [1,2]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t2 <= values.length <= 5 * 104\n\t1 <= values[i] <= 1000\n\n", "solution_py": "class Solution:\n \"\"\"\n Approach: \n O(n^2) is very straight forward\n For all the possible pairs\n for i in range(n)\n for j in range(i+1, n)\n value[i] = max(value[i], value[i] + value[j] + i - j`)\n \n we can do this problem in O(n) as well\n values = [8, 1, 5, 2, 6]\n max_val = [0, 0, 0, 0, 0]\n max_val[i] = max(max_val[i-1]-1, values[i-1]-1)\n we have to do it once from left side and then from right side\n \"\"\"\n def maxScoreSightseeingPair(self, values: List[int]) -> int:\n left_max_vals = [float('-inf') for _ in range(len(values))]\n right_max_vals = [float('-inf') for _ in range(len(values))]\n \n for i in range(1, len(values)):\n left_max_vals[i] = max(left_max_vals[i-1]-1, values[i-1]-1)\n \n for i in range(len(values)-2, -1, -1):\n right_max_vals[i] = max(right_max_vals[i+1]-1, values[i+1]-1)\n \n max_pair = float('-inf')\n for i in range(len(values)):\n max_pair = max(max_pair, values[i] + max(left_max_vals[i], right_max_vals[i]))\n return max_pair", "solution_js": "/**\n * @param {number[]} values\n * @return {number}\n */\nvar maxScoreSightseeingPair = function(values) {\n let n=values.length,\n prevIndexMaxAddition=values[n-1],\n maxValue=-2;\n for(let i=n-2;i>-1;i--){\n let curIndexMaxAddition=Math.max(values[i],prevIndexMaxAddition-1);\n let curIndexMaxValue=values[i]+prevIndexMaxAddition-1;\n if(maxValue& values) {\n int ans=-1e9;\n int maxSum=values[0];\n int n=values.size();\n for(int i=1;i bool:\n if (rec2[1]>=rec1[3] or rec2[0]>=rec1[2] or rec2[3]<=rec1[1] or rec1[0]>=rec2[2]) :\n \n return False\n else:\n return True", "solution_js": "/**\n * @param {number[]} rec1\n * @param {number[]} rec2\n * @return {boolean}\n */\nvar isRectangleOverlap = function(rec1, rec2) {\n if(rec1[0] >= rec2[2] || rec2[0] >= rec1[2] || rec1[1] >= rec2[3] || rec2[1] >= rec1[3]){\n return false\n }\n return true\n};", "solution_java": "// Rectangle Overlap\n// https://leetcode.com/problems/rectangle-overlap/\n\nclass Solution {\n public boolean isRectangleOverlap(int[] rec1, int[] rec2) {\n int x1 = rec1[0];\n int y1 = rec1[1];\n int x2 = rec1[2];\n int y2 = rec1[3];\n int x3 = rec2[0];\n int y3 = rec2[1];\n int x4 = rec2[2];\n int y4 = rec2[3];\n if (x1 >= x4 || x2 <= x3 || y1 >= y4 || y2 <= y3) {\n return false;\n }\n return true; \n }\n}", "solution_c": "class Solution {\npublic:\n bool isRectangleOverlap(vector& rec1, vector& rec2) {\n int ax1 = rec1[0];\n int ay1 = rec1[1];\n int ax2 = rec1[2];\n int ay2 = rec1[3];\n \n int bx1 = rec2[0];\n int by1 = rec2[1];\n int bx2 = rec2[2];\n int by2 = rec2[3];\n\n int x5 = max(ax1,bx1);\n int y5 = max(ay1,by1);\n int x6 = min(ax2,bx2);\n int y6 = min(ay2,by2);\n if(x5 bool:\n # Base case, remaining string is a valid solution\n if last_val and int(s) == last_val - 1:\n return True\n\n # Iterate through increasingly larger slices of s\n for i in range(1, len(s)):\n cur = int(s[:i])\n # If current slice is equal to last_val - 1, make\n # recursive call with remaining string and updated last_val\n if last_val is None or cur == last_val - 1:\n if self.splitString(s[i:], cur):\n return True\n\n return False", "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar splitString = function(s) {\n\n const backtracking = (index, prevStringValue) => {\n if(index === s.length) {\n return true;\n }\n for(let i = index; i < s.length; i++) {\n const currStringValue = s.slice(index ,i + 1);\n\n if(parseInt(prevStringValue, 10) === parseInt(currStringValue, 10) + 1) {\n if(backtracking(i + 1, currStringValue)) {\n return true;\n }\n }\n }\n }\n // we need to have at least two values to compare, so we start with the for outside the backtracking function\n for (let i = 1; i <= s.length - 1; i++) {\n const currStringValue = s.slice(0, i);\n if (backtracking(i, currStringValue)) {\n return true;\n }\n }\n return false\n};", "solution_java": "class Solution {\n public boolean splitString(String s) {\n return isRemainingValid(s, null);\n }\n private boolean isRemainingValid(String s, Long previous) {\n long current =0;\n for(int i=0;i= 10000000000L) return false; // Avoid overflow\n if(previous == null) {\n if (isRemainingValid(s.substring(i+1), current)) \n return true;\n } else if(current == previous - 1 && (i==s.length()-1 || isRemainingValid(s.substring(i+1), current)))\n return true;\n }\n return false;\n }\n}", "solution_c": "class Solution {\n bool helper(string s, long long int tar) {\n if (stoull(s) == tar) return true;\n for (int i = 1; i < s.size(); ++i) {\n if (stoull(s.substr(0, i)) != tar) continue;\n if (helper(s.substr(i, s.size()-i), tar-1))\n return true;\n }\n return false;\n }\npublic:\n bool splitString(string s) {\n for (int i = 1; i < s.size(); ++i) {\n long long int tar = stoull(s.substr(0, i));\n if (helper(s.substr(i, s.size()-i), tar-1))\n return true;\n }\n return false;\n }\n};" }, { "title": "Transpose Matrix", "algo_input": "Given a 2D integer array matrix, return the transpose of matrix.\n\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n\n\n\n \nExample 1:\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[1,4,7],[2,5,8],[3,6,9]]\n\n\nExample 2:\n\nInput: matrix = [[1,2,3],[4,5,6]]\nOutput: [[1,4],[2,5],[3,6]]\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 1000\n\t1 <= m * n <= 105\n\t-109 <= matrix[i][j] <= 109\n\n", "solution_py": "class Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n rows=len(matrix)\n cols=len(matrix[0])\n ans=[[0]*rows]*cols\n for i in range(cols):\n for j in range(rows):\n ans[i][j]=matrix[j][i]\n return ans", "solution_js": "var transpose = function(matrix){\n let result = []\n for(let i=0;i> transpose(vector>& matrix) {\n \n vector>result;\n map>m;\n \n for(int i=0;iv = matrix[i];\n for(int j=0;j 1 ----> 9\n\n node.next = node.next.next;\n // 4 1 9\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n void deleteNode(ListNode* node) {\n int temp = node->val;\n node->val = node->next->val;\n node->next->val = temp;\n \n ListNode* delNode = node->next;\n node->next = node->next->next;\n delete delNode;\n }\n};" }, { "title": "Flatten a Multilevel Doubly Linked List", "algo_input": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.\n\nGiven the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.\n\nReturn the head of the flattened list. The nodes in the list must have all of their child pointers set to null.\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput: [1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n\n\nExample 2:\n\nInput: head = [1,2,null,3]\nOutput: [1,3,2]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n\n\nExample 3:\n\nInput: head = []\nOutput: []\nExplanation: There could be empty list in the input.\n\n\n \nConstraints:\n\n\n\tThe number of Nodes will not exceed 1000.\n\t1 <= Node.val <= 105\n\n\n \nHow the multilevel linked list is represented in test cases:\n\nWe use the multilevel linked list from Example 1 above:\n\n 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL\n\nThe serialization of each level is as follows:\n\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\n\n\nTo serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:\n\n[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]\n\n\nMerging the serialization of each level and removing trailing nulls we obtain:\n\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n\n", "solution_py": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n\"\"\"\n\nclass Solution:\n def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]': \n node = head\n while node:\n if node.child: # If there is a child travel to last node of the child\n child = node.child\n while child.next:\n child = child.next\n child.next = node.next # Update the next of child to the the next of the current node\n if node.next: # update the prev of the next node to chile to make it valid doubly linked list\n node.next.prev = child\n node.next = node.child # Update the child to become the next of the current\n node.next.prev = node # update the prev of the next node to chile to make it valid doubly linked list\n node.child = None # Make the child of the current node None to fulfill the requirements\n node = node.next\n return head\n\n# time and space complexity\n# time: O(n)\n# space: O(1)", "solution_js": "var flatten = function(head) {\n var arr = [];\n var temp = head;\n var prev= null;\n while(temp)\n {\n if(temp.child!= null)\n {\n arr.push(temp.next);\n temp.next = temp.child;\n temp.child.prev = temp;\n temp.child = null;\n }\n prev = temp;\n temp = temp.next\n }\n for(var j=arr.length-1; j>=0; j--)\n {\n if(arr[j] != null)\n mergeOtherLists(arr[j]);\n }\n return head;\n\t\n\tfunction mergeOtherLists(root)\n\t\t{\n\t\t\tprev.next=root;\n\t\t\troot.prev=prev;\n\t\t while(root)\n\t\t\t {\n\t\t\t\t prev = root;\n\t\t\t\t root = root.next;\n\t\t\t }\n\t\t}\n};", "solution_java": "class Solution {\n public Node flatten(Node head) {\n Node curr = head ; // for traversal\n Node tail = head; // for keeping the track of previous node\n Stack stack = new Stack<>(); // for storing the reference of next node when child node encounters\n while(curr != null){\n if(curr.child != null){ // if there is a child\n Node child = curr.child; // creating a node for child\n if(curr.next != null){ // if there is list after we find child a child\n stack.push(curr.next); // pushing the list to the stack\n curr.next.prev = null; // pointing its previous to null\n }\n curr.next = child; // pointing the current's reference to child\n child.prev = curr; // pointing child's previous reference to current.\n curr.child = null; // pointing the current's child pointer to null\n }\n tail = curr ; // for keeping track of previous nodes\n curr= curr.next; // traversing\n }\n while(!stack.isEmpty()){ // checking if the stack has still nodes in it.\n curr = stack.pop(); // getting the last node of the list pushed into the stack\n tail.next = curr; // pointing the previos node to the last node\n curr.prev = tail; // pointing previos pointer of the last node to the previos node.\n while( curr != null){ // traversing the last node's popped out of stack\n tail = curr;\n curr = curr.next ;\n }\n }\n return head;\n }\n}", "solution_c": "class Solution {\npublic:\n Node* flatten(Node* head)\n {\n if(head==NULL) return head;\n Node *temp=head;\n stack stk;\n while(temp->next!=NULL || temp->child!=NULL || stk.size()!=0)\n {\n if(temp->next==NULL && temp->child==NULL && stk.size())\n {\n Node *a=stk.top();\n stk.pop();\n temp->next=a;\n a->prev=temp;\n }\n if(temp->child!=NULL)\n {\n if(temp->next!=NULL)\n {\n Node* a=temp->next;\n a->prev=NULL;\n stk.push(a);\n }\n temp->next=temp->child;\n temp->next->prev=temp;\n temp->child=NULL;\n \n }\n temp=temp->next;\n }\n return head;\n }\n};\nFeel free to ask in doubt in comment section" }, { "title": "Lucky Numbers in a Matrix", "algo_input": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.\n\nA lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.\n\n \nExample 1:\n\nInput: matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput: [15]\nExplanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\nExample 2:\n\nInput: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput: [12]\nExplanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\nExample 3:\n\nInput: matrix = [[7,8],[1,2]]\nOutput: [7]\nExplanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= n, m <= 50\n\t1 <= matrix[i][j] <= 105.\n\tAll elements in the matrix are distinct.\n\n", "solution_py": "class Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n min_, max_ = 0, 0\n min_temp = []\n max_temp = []\n m = len(matrix)\n n = len(matrix[0])\n for i in matrix:\n min_temp.append(min(i))\n print(min_temp)\n if n >= m:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))\n elif n == 1:\n for i in range(m):\n max_check = []\n for j in range(n):\n max_check.append(matrix[i][j])\n max_temp.append(max(max_check))\n return [max(max_temp)]\n else:\n for i in range(n):\n max_check = []\n for j in range(m):\n max_check.append(matrix[j][i])\n max_temp.append(max(max_check))\n return set(min_temp).intersection(set(max_temp))", "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nvar luckyNumbers = function(matrix) {\n let rowLucky = new Set();\n let colLucky = new Set();\n let cols = [...Array(matrix[0].length)].map(e => []);\n\n for (let i = 0; i < matrix.length; i++) {\n let row = matrix[i];\n rowLucky.add(Math.min(...row));\n\n // build columns\n for (let j = 0; j < row.length; j++) {\n cols[j].push(row[j]);\n }\n }\n\n // Compare sets\n for (const col of cols)\n colLucky.add(Math.max(...col));\n return [...rowLucky].filter(x => colLucky.has(x));\n};", "solution_java": "class Solution {\n public List luckyNumbers (int[][] matrix) {\n List luckyNums = new ArrayList();\n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int[] row : matrix){\n int min = row[0];\n int index = 0;\n boolean lucky = true;\n for(int col = 0; col < m; col++){\n if(min > row[col]){\n min = row[col];\n index = col;\n }\n }\n \n for(int r = 0; r < n; r++){\n if(min < matrix[r][index]){\n lucky = false;\n break;\n }\n }\n if(lucky){\n luckyNums.add(min);\n }\n \n }\n \n return luckyNums;\n \n }\n}", "solution_c": "class Solution {\npublic:\n vector luckyNumbers (vector>& matrix) {\n\n unordered_map>m;\n\n for(int i=0;itemp = matrix[i];\n for(int j=0;jmp;\n for(int i=0;ihelper = matrix[i];\n\n sort(helper.begin(),helper.end());\n\n mp[helper[0]]++;\n }\n vectorresult;\n for(auto i:m){\n vectorhelper = i.second;\n sort(helper.begin(),helper.end());\n int a = helper[helper.size()-1];\n if(mp.find(a)!=mp.end()){\n result.push_back(a);\n }\n }\n return result;\n }\n};" }, { "title": "Bricks Falling When Hit", "algo_input": "You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:\n\n\n\tIt is directly connected to the top of the grid, or\n\tAt least one other brick in its four adjacent cells is stable.\n\n\nYou are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).\n\nReturn an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.\n\nNote that an erasure may refer to a location with no brick, and if it does, no bricks drop.\n\n \nExample 1:\n\nInput: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\nOutput: [2]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].\n\n\nExample 2:\n\nInput: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\nOutput: [0,0]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 200\n\tgrid[i][j] is 0 or 1.\n\t1 <= hits.length <= 4 * 104\n\thits[i].length == 2\n\t0 <= xi <= m - 1\n\t0 <= yi <= n - 1\n\tAll (xi, yi) are unique.\n\n", "solution_py": "from collections import defaultdict\n\nclass Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n parent = defaultdict()\n sz = defaultdict(lambda:1)\n empty = set()\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n pi = find(i)\n pj = find(j)\n if pi != pj:\n parent[pi] = pj\n sz[pj] += sz[pi]\n row = len(grid)\n col = len(grid[0])\n for r in range(row):\n for c in range(col):\n parent[(r,c)] = (r,c)\n parent[(row,col)] = (row,col)\n for r, c in hits:\n if grid[r][c]:\n grid[r][c] = 0\n else:\n empty.add((r,c))\n for r in range(row):\n for c in range(col):\n if not grid[r][c]:\n continue\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r, c),(r+dr, c+dc))\n if r == 0:\n union((r,c),(row,col))\n res = [0]*len(hits)\n for i in range(len(hits)-1,-1,-1):\n r, c = hits[i]\n if (r,c) in empty:\n continue\n grid[r][c] = 1\n curbricks = sz[find((row,col))]\n for dr, dc in [[-1,0],[1,0],[0,1],[0,-1]]:\n if 0 <= r + dr < row and 0 <= c + dc < col and grid[r+dr][c+dc]:\n union((r,c),(r+dr,c+dc))\n if r == 0:\n union((r,c),(row,col))\n nextbricks = sz[find((row,col))]\n if nextbricks > curbricks:\n res[i] = nextbricks - curbricks - 1\n return res", "solution_js": " var hitBricks = function(grid, hits) {\n let output = []\n for (let i = 0; i < hits.length; i++) {\n let map = {};\n \n if (grid[hits[i][0]][hits[i][1]] == 1) {\n \n grid[hits[i][0]][hits[i][1]] = 0;\n \n \n for (let j = 0; j= grid.length || j >= grid[0].length || i < 0 || j < 0) return;\n \n let key = i +'_'+ j\n \n if (map[key]) return;\n \n if (grid[i][j] == 1) {\n \n map[key] = 1;\n \n dfs(grid, output, map, i+1, j);\n dfs(grid, output, map, i-1, j);\n dfs(grid, output, map, i, j+1);\n dfs(grid, output, map, i, j-1);\n \n }\n \n}\n\nfunction removeBricks (grid, map, output) {\n let count = 0;\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[row].length; col++) {\n let key = row +'_'+ col;\n \n if (grid[row][col] == 1 && !map[key] ) {\n grid[row][col] = 0;\n count++\n }\n }\n }\n output.push(count)\n \n}", "solution_java": "class Solution {\n int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};\n\n public int[] hitBricks(int[][] grid, int[][] hits) {\n //marking all the hits that has a brick with -1\n for(int i=0;i=0;i--){\n int row = hits[i][0];\n int col = hits[i][1];\n \n //hit is at empty space so continue\n if(grid[row][col] == 0)\n continue;\n \n //marking it with 1, this signifies that a brick is present in an unstable state and will be restored in the future\n grid[row][col] = 1;\n // checking brick stability, if it's unstable no need to visit the neighbours\n if(!isStable(grid, row, col))\n continue;\n\t\t\t\n\t\t\t//So now as our brick is stable we can restore all the bricks connected to it\n //mark all the unstable bricks as stable and get the count\n res[i] = markAndCountStableBricks(grid, hits[i][0], hits[i][1])-1; //Subtracting 1 from the total count, as we don't wanna include the starting restored brick\n }\n \n return res;\n }\n \n private int markAndCountStableBricks(int[][] grid, int row, int col){\n if(grid[row][col] == 0 || grid[row][col] == -1)\n return 0;\n \n grid[row][col] = 2;\n int stableBricks = 1;\n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 0 || grid[r][c] == -1 || grid[r][c] == 2)\n continue;\n \n stableBricks += markAndCountStableBricks(grid, r, c);\n }\n \n return stableBricks;\n }\n \n private boolean isStable(int[][] grid, int row, int col){\n if(row == 0)\n return true;\n \n for(int[] dir:dirs){\n int r = row+dir[0];\n int c = col+dir[1];\n \n if(r < 0 || r >= grid.length || c < 0 || c >= grid[0].length)\n continue;\n \n if(grid[r][c] == 2)\n return true;\n }\n \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n\t// Helper function to determine if the passed node is connected to the top of the matrix\n bool isConnected(vector>& vis, int& i, int& j){\n if(i==0)\n return true;\n \n if(i>0 && vis[i-1][j])\n return true;\n if(j>0 && vis[i][j-1])\n return true;\n if(i hitBricks(vector>& grid, vector>& hits) {\n vector ans(hits.size(), 0);\n \n\t\t//Remove all the bricks which are hit during entire process\n vector> mat = grid;\n for(int i=0; i> vis(grid.size(), vector (grid[0].size(), false));\n queue> q;\n for(int i=0; i0 && mat[idx-1][jdx]==1){\n if(!vis[idx-1][jdx])\n q.push({idx-1, jdx});\n vis[idx-1][jdx]=true;\n }\n if(jdx>0 && mat[idx][jdx-1]==1){\n if(!vis[idx][jdx-1])\n q.push({idx, jdx-1});\n vis[idx][jdx-1]=true;\n }\n if(idx=0; i--){\n\t\t\t//If no brick was present in original grid matrix, continue, otherwise \n\t\t\t//add brick to that position\n if(grid[hits[i][0]][hits[i][1]]==0)\n continue;\n mat[hits[i][0]][hits[i][1]] = 1;\n \n\t\t\t//If this brick not connected to top of matrix, ans=0 and continue\n if(!isConnected(vis, hits[i][0], hits[i][1]))\n continue;\n \n\t\t\t//This brick connects between visited nodes and not visited nodes, do BFS\n\t\t\t//to make all reachable nodes visited and count them\n q.push({hits[i][0], hits[i][1]});\n vis[hits[i][0]][hits[i][1]] = true;\n int cnt=0;\n while(!q.empty()){\n int idx = q.front().first, jdx = q.front().second;\n q.pop();\n cnt++;\n if(idx>0 && mat[idx-1][jdx]==1 && !vis[idx-1][jdx]){\n q.push({idx-1, jdx});\n vis[idx-1][jdx]=true;\n }\n if(jdx>0 && mat[idx][jdx-1]==1 && !vis[idx][jdx-1]){\n q.push({idx, jdx-1});\n vis[idx][jdx-1]=true;\n }\n if(idx str:\n queryIP = queryIP.replace(\".\",\":\")\n ct = 0\n for i in queryIP.split(\":\"):\n if i != \"\":\n ct += 1\n if ct == 4:\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if i.isnumeric():\n if len(i) > 1:\n if i.count('0') == len(i) or int(i) > 255 or i[0] == '0':\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv4\"\n elif ct == 8:\n a = ['a','b','c','d','e','f','A','B','C','D','E','F']\n for i in queryIP.split(\":\"):\n if i == \"\":\n return \"Neither\"\n if len(i) < 5:\n for j in i:\n if j not in a and j.isdigit() == False:\n return \"Neither\"\n else:\n return \"Neither\"\n return \"IPv6\"\n else:\n return \"Neither\"\n \n\n\n ", "solution_js": "var validIPAddress = function(queryIP) {\n const iPv4 = () => {\n const address = queryIP.split('.');\n if (address.length !== 4) return null;\n\n for (const str of address) {\n const ip = parseInt(str);\n if (ip < 0 || ip > 255) return null;\n if (ip.toString() !== str) return null;\n }\n return 'IPv4';\n };\n\n const iPv6 = () => {\n const address = queryIP.split(':');\n if (address.length !== 8) return null;\n const config = '0123456789abcdefABCDEF';\n const check = address.every(str => {\n if (str === '' || str.length > 4) return false;\n for (const s of str) {\n if (!config.includes(s)) return false;\n }\n return true;\n });\n return check ? 'IPv6' : null;\n };\n\n return iPv4() ?? iPv6() ?? 'Neither';\n};", "solution_java": "class Solution {\n public String validIPAddress(String queryIP) {\n String regexIpv4 = \"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\";\n \n String regexIpv6 = \"((([0-9a-fA-F]){1,4})\\\\:){7}(([0-9a-fA-F]){1,4})\";\n \n if(queryIP.matches(regexIpv4))\n return \"IPv4\";\n else if(queryIP.matches(regexIpv6))\n return \"IPv6\";\n else\n return \"Neither\";\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkforIPv6(string IP){\n int n = IP.size();\n vectorstore;\n string s = \"\";\n for(int i=0; i 4 or s.size() == 0){\n return false;\n }\n for(int j=0; j= 'a' and s[j] <= 'f'){\n continue;\n }\n else if(s[j] >= 'A' and s[j] <= 'F'){\n continue;\n }\n else if(s[j] >= '0' and s[j] <= '9'){\n continue;\n }\n else{\n return false;\n }\n }\n }\n return true;\n }\n \n bool checkforIPv4(string IP){\n int n = IP.size();\n vectorstore;\n string s = \"\";\n for(int i=0; i 3 or s.size() == 0){\n return false;\n }\n int num = 0;\n for(int j=0; j= 2 and s[0] == '0' and s[1] == '0'){\n return false;\n }\n if(s.size() >= 2 and s[0] == '0' and s[1] != '0'){\n return false;\n }\n if(s[j] >= '0' and s[j] <= '9'){\n // Do nothing.\n }\n else{\n return false;\n }\n num = num*10 + (s[j]-'0');\n }\n if(num > 255 or num < 0){\n return false;\n }\n }\n return true;\n }\n string validIPAddress(string queryIP) {\n bool IPv6 = checkforIPv6(queryIP);\n bool IPv4 = checkforIPv4(queryIP);\n if(IPv6){\n return \"IPv6\";\n }\n if(IPv4){\n return \"IPv4\";\n }\n return \"Neither\";\n }\n};" }, { "title": "Minimum Moves to Equal Array Elements II", "algo_input": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\n\nIn one move, you can increment or decrement an element of the array by 1.\n\nTest cases are designed so that the answer will fit in a 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation:\nOnly two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]\n\n\nExample 2:\n\nInput: nums = [1,10,2,9]\nOutput: 16\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n \n n=len(nums)\n nums.sort()\n \n if n%2==1:\n median=nums[n//2]\n else:\n median = (nums[n//2 - 1] + nums[n//2]) // 2\n \n ans=0\n \n for val in nums:\n ans+=abs(val-median)\n \n return ans\n ", "solution_js": "var minMoves2 = function(nums) {\n // Sort the array low to high\n nums.sort(function(a, b) { return a-b;});\n let i = 0;\n let j = nums.length - 1;\n let res = 0;\n /**\n * Sum up the difference between the next highest and lowest numbers. Regardless of what number we wish to move towards, the number of moves is the same.\n */\n while (i < j){\n res += nums[j] - nums[i];\n i++;\n j--;\n }\n return res;\n};", "solution_java": "class Solution {\n public int minMoves2(int[] nums) {\n Arrays.sort(nums);\n int idx=(nums.length-1)/2;\n int sum=0;\n for(int i=0;i& nums) {\n int result = 0, length = nums.size();\n sort(nums.begin(), nums.end());\n for (int i = 0; i < length; i++) {\n int median = length / 2;\n result += abs(nums[i] - nums[median]);\n }\n return result;\n }\n};" }, { "title": "Longest ZigZag Path in a Binary Tree", "algo_input": "You are given the root of a binary tree.\n\nA ZigZag path for a binary tree is defined as follow:\n\n\n\tChoose any node in the binary tree and a direction (right or left).\n\tIf the current direction is right, move to the right child of the current node; otherwise, move to the left child.\n\tChange the direction from right to left or from left to right.\n\tRepeat the second and third steps until you can't move in the tree.\n\n\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\n\nReturn the longest ZigZag path contained in that tree.\n\n \nExample 1:\n\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\n\n\nExample 2:\n\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n\n\nExample 3:\n\nInput: root = [1]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 5 * 104].\n\t1 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n def longestZigZag(self, root: Optional[TreeNode]) -> int:\n self.res = 0\n\n def helper(root):\n if root is None:\n return -1, -1\n\n leftRight = helper(root.left)[1] + 1\n rightLeft = helper(root.right)[0] + 1\n self.res = max(self.res, leftRight, rightLeft)\n return leftRight, rightLeft\n\n helper(root)\n return self.res", "solution_js": "/** https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/\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 longestZigZag = function(root) {\n this.out = 0;\n\n // Recursive left and right node and find the largest height\n let left = dfs(root.left, false) + 1;\n let right = dfs(root.right, true) + 1;\n this.out = Math.max(this.out, Math.max(left, right));\n \n return this.out;\n};\n\nvar dfs = function(node, isLeft) {\n // Node is null, we return -1 because the caller will add 1, so result in 0 (no node visited)\n if (node == null) {\n return -1;\n }\n \n // No left or right node, we return 0 because the caller will add 1, so result in 1 (visited 1 node - this one)\n if (node.left == null && node.right == null) {\n return 0;\n }\n \n // Recursive to see which one is higher, zigzag to left or zigzag to right\n let left = dfs(node.left, false) + 1;\n let right = dfs(node.right, true) + 1;\n this.out = Math.max(this.out, Math.max(left, right));\n \n return isLeft === true ? left : right;\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 static class Pair{\n int left=-1;\n int right=-1;\n int maxLen=0;\n }\n public int longestZigZag(TreeNode root) {\n Pair ans=longestZigZag_(root);\n return ans.maxLen;\n }\n\n public Pair longestZigZag_(TreeNode root) {\n if(root==null)\n return new Pair();\n Pair l=longestZigZag_(root.left);\n Pair r=longestZigZag_(root.right);\n\n Pair myAns=new Pair();\n myAns.left=l.right+1;\n myAns.right=r.left+1;\n int max=Math.max(myAns.left,myAns.right);\n myAns.maxLen=Math.max(max,Math.max(l.maxLen,r.maxLen));\n return myAns;\n\n }\n\n}", "solution_c": "class Solution {\n typedef long long ll;\n typedef pair pi;\npublic:\n ll ans = 0;\n pi func(TreeNode* nd) {\n if(!nd){\n return {-1,-1};\n }\n pi p = { func(nd->left).second + 1, func(nd->right).first + 1 };\n ans = max({ans, p.first, p.second});\n return p;\n }\n int longestZigZag(TreeNode* root) {\n func(root);\n return ans;\n }\n};" }, { "title": "Rearrange Array Elements by Sign", "algo_input": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.\n\nYou should rearrange the elements of nums such that the modified array follows the given conditions:\n\n\n\tEvery consecutive pair of integers have opposite signs.\n\tFor all integers with the same sign, the order in which they were present in nums is preserved.\n\tThe rearranged array begins with a positive integer.\n\n\nReturn the modified array after rearranging the elements to satisfy the aforementioned conditions.\n\n \nExample 1:\n\nInput: nums = [3,1,-2,-5,2,-4]\nOutput: [3,-2,1,-5,2,-4]\nExplanation:\nThe positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. \n\n\nExample 2:\n\nInput: nums = [-1,1]\nOutput: [1,-1]\nExplanation:\n1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 2 * 105\n\tnums.length is even\n\t1 <= |nums[i]| <= 105\n\tnums consists of equal number of positive and negative integers.\n\n", "solution_py": "class Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]", "solution_js": "var rearrangeArray = function(nums) {\n let result = Array(nums.length).fill(0);\n let posIdx = 0, negIdx = 1;\n for(let i=0;i0) {\n result[posIdx] = nums[i]\n posIdx +=2;\n } else {\n result[negIdx] = nums[i]\n negIdx +=2;\n }\n }\n return result;\n };", "solution_java": "class Solution {\n public int[] rearrangeArray(int[] nums) {\n int[] res = new int[nums.length];\n int resIdx = 0;\n int posIdx = -1;\n int minusIdx = -1;\n\n for(int i=0;i 0 )minusIdx++;\n res[resIdx++] = nums[minusIdx];\n }\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\n// Uncomment/comment the below two lines for logs\n// #define ENABLE_LOG(...) __VA_ARGS__\n#define ENABLE_LOG(...)\n\npublic:\n vector rearrangeArray(vector& nums) {\n const int chunk_size = (int)(sqrt(nums.size())) / 2 * 2 + 2; // make it always an even number\n const int original_n = nums.size();\n constexpr int kPadPositive = 100006;\n constexpr int kPadNegative = -100006;\n // Pad the array to have size of a multiple of 4 * chunk_size\n for (int i=0; i chunk_buffer(chunk_size); // stores sorted result\n for (int i=0; i < nums.size(); i += chunk_size) {\n chunk_buffer.clear();\n for (int j=i; j 0)\n chunk_buffer.push_back(nums[j]);\n for (int j=i; j= chunk_size, we extract chunk_size positives into an all-positive chunk and put the remaining (m+p-chunk_size positives and n+q negatives) into the \"buffer\" chunk\n // b) if n+q >= chunk_size, we extract chunk_size negatives into an all-negative chunk and make the remaining (m+p positives and n+q-chunk_size negatives) the \"buffer\" chunk\n // Note that in either of the above two cases, the relative order for positive/negative numbers are unchanged\n\n chunk_buffer = vector{nums.begin(), nums.begin() + chunk_size};\n for (int i = chunk_size; i= chunk_size) {\n // Copy positives to the previous chunk\n copy_n(chunk_buffer.cbegin(), m, nums.begin() + i - chunk_size);\n copy_n(nums.cbegin() + i, chunk_size - m, nums.begin() + i - chunk_size + m);\n vector new_buffer;\n // the remaining positives (m+p-chunk_size) from this chunk\n copy_n(nums.cbegin() + i + (chunk_size - m),\n p - (chunk_size - m),\n back_inserter(new_buffer));\n // the remaining negatives in buffer\n copy_n(chunk_buffer.cbegin() + m, n, back_inserter(new_buffer));\n // the remaining negatives in this chunk\n copy_n(nums.cbegin() + i + p, q, back_inserter(new_buffer));\n chunk_buffer = move(new_buffer);\n } else {\n // Copy negatives to the previous chunk\n copy_n(chunk_buffer.cbegin() + m, n, nums.begin() + i - chunk_size);\n copy_n(nums.cbegin() + i + p, chunk_size - n, nums.begin() + i - chunk_size + n);\n vector new_buffer;\n // the remaining positives in buffer\n copy_n(chunk_buffer.cbegin(), m, back_inserter(new_buffer));\n // the remaining positives in this chunk\n copy_n(nums.cbegin() + i, p, back_inserter(new_buffer));\n // the remaining negatives from this chunk\n copy_n(nums.cbegin() + i + p + chunk_size - n, q - (chunk_size - n),\n back_inserter(new_buffer));\n chunk_buffer = move(new_buffer);\n }\n }\n copy_n(chunk_buffer.cbegin(), chunk_size, nums.begin() + nums.size() - chunk_size);\n\n ENABLE_LOG(\n cout << \"homonegeous array: \";\n for (int v: nums) cout << v << \" \"; cout << endl;\n )\n\n // Step 3:\n // After the above step, we will have sqrt(N) / 2 all-positive chunks and sqrt(N) / 2 all-negative chunks.\n // Their initial chunk location is at (0, 1, 2, ..., sqrt(N))\n // We want them to interleave each other, i.e., Positive Chunk1, Negative Chunk 1, Positive Chunk 2, Negative Chunk 2\n // which could be achieved via cyclic permutation using an additional array tracking the target location of each chunk\n\n // due to above padding, chunk_cnt is always a multiple of 4\n const int chunk_cnt = nums.size() / chunk_size;\n\n vector target(chunk_cnt); // O(sqrt(N))\n int positive_chunks = 0, negative_chunks = 0;\n for (int i=0; i 0)\n target[i] = (positive_chunks++) * 2;\n else\n target[i] = (negative_chunks++) * 2 + 1;\n }\n for (int i=0; i two_chunk_elements_interleaved; // O(2 * chunk_size) = O(sqrt(N))\n for (int i=0; i bool:\n\n a = 0\n\n while a ** 2 <= c:\n b = math.sqrt(c - a ** 2)\n\n if b.is_integer():\n return True\n\n a += 1\n\n return False", "solution_js": "var judgeSquareSum = function(c) {\n\tlet a = 0;\n\tlet b = Math.sqrt(c) | 0;\n\n\twhile (a <= b) {\n\t\tconst sum = a ** 2 + b ** 2;\n\t\tif (sum === c) return true;\n\t\tsum > c ? b -= 1 : a += 1;\n\t}\n\treturn false;\n};", "solution_java": "class Solution {\n public boolean judgeSquareSum(int c) {\n long a = 0;\n long b = (long) Math.sqrt(c);\n\n while(a<=b){\n if(((a*a) + (b*b)) == c){\n return true;\n }\n else if((((a*a)+(b*b)) < c)){\n a++;\n }\n else{\n b--;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool judgeSquareSum(int c) {\n long long start=0,end=0;\n while(end*endc){\n end--;\n } else {\n start++;\n }\n }\n return false;\n }\n};" }, { "title": "Most Stones Removed with Same Row or Column", "algo_input": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.\n\nA stone can be removed if it shares either the same row or the same column as another stone that has not been removed.\n\nGiven an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.\n\n \nExample 1:\n\nInput: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput: 5\nExplanation: One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.\n\n\nExample 2:\n\nInput: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput: 3\nExplanation: One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.\n\n\nExample 3:\n\nInput: stones = [[0,0]]\nOutput: 0\nExplanation: [0,0] is the only stone on the plane, so you cannot remove it.\n\n\n \nConstraints:\n\n\n\t1 <= stones.length <= 1000\n\t0 <= xi, yi <= 104\n\tNo two stones are at the same coordinate point.\n\n", "solution_py": "class Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n def dfs(row,col):\n if seen[(row,col)]:\n return 0\n seen[(row,col)] = True\n for r,c in tableRow[row]:\n dfs(r,c)\n for r,c in tableCol[col]:\n dfs(r,c)\n return 1\n\n tableRow, tableCol = {},{}\n for row,col in stones:\n if row not in tableRow:\n tableRow[row] = set()\n if col not in tableCol:\n tableCol[col] = set()\n tableRow[row].add((row,col))\n tableCol[col].add((row,col))\n\n count,seen= 0, {(row,col):False for row,col in stones}\n for row,col in stones:\n count += dfs(row,col)\n return abs(len(stones)-count)", "solution_js": "/**\n * @param {number[][]} stones\n * @return {number}\n */\nvar removeStones = function(stones) {\n \n const n = stones.length\n // initial number of components(a.k.a island)\n let numComponents = n\n \n //initial forest for union find\n let forest = new Array(n).fill(0).map((ele, index) => index)\n\n // recursively finding the root of rarget node\n const find = (a) => {\n if(forest[a] === a) {\n return a\n }\n return find(forest[a])\n }\n \n // function for uniting two stones\n const union = (a, b) => {\n const rootA = find(a)\n const rootB = find(b)\n if(rootA != rootB) {\n //connect their roots if currently they are not connected\n forest[rootA] = rootB\n //subtract the number of islands by one since two islands are connected now\n numComponents -= 1\n }\n }\n \n for(let i = 0; i < stones.length - 1; i++) {\n for(let j = i + 1; j < stones.length; j++) {\n // if two stones are connected(i.e. share same row or column), unite them\n if(stones[i][0] === stones[j][0] || stones[i][1] === stones[j][1]) {\n union(i, j)\n }\n }\n }\n\n // this is the most confusing part.\n // The number of stones can be removed is not equal to the number of islands.\n // e.g. we have two islands with total of 10 stores, each island will leave one extra stone after the \n // removal, therefore we can remove 10 - 2 = 8 stones in total\n return n - numComponents\n};", "solution_java": "class Solution {\n public int removeStones(int[][] stones) {\n int ret=0;\n DisjointSet ds=new DisjointSet(stones.length);\n\n for(int i=0;ireturn size in negative\n public int union(int idx1, int idx2) {\n int p1=find(idx1);\n int p2=find(idx2);\n\n if(p1==p2) { //same parent so directly returning size\n return sets[p1];\n }else {\n int w1=Math.abs(sets[p1]);\n int w2=Math.abs(sets[p2]);\n\n if(w1>w2) {\n sets[p2]=p1;\n\n //collapsing FIND\n sets[idx1]=p1;\n sets[idx2]=p1;\n\n return sets[p1]=-(w1+w2);\n }else {\n sets[p1]=p2;\n\n //collapsing FIND\n sets[idx1]=p2;\n sets[idx2]=p2;\n\n return sets[p2]=-(w1+w2);\n }\n }\n }\n\n // collapsing FIND\n //find parent\n public int find(int idx) {\n int p=idx;\n while(sets[p]>=0) {\n p=sets[p];\n }\n return p;\n }\n }\n}", "solution_c": "class Solution {\n class UnionFind \n {\n vector parent, rank;\n public:\n int count = 0;\n UnionFind(int n)\n {\n count = n;\n parent.assign(n, 0);\n rank.assign(n, 0);\n for(int i=0;i>& stones) {\n int n = stones.size();\n UnionFind uf(n);\n for(int i=0;i high:\n return high\n mid = (low + high) // 2\n if arr[mid] > value:\n return self.binary_search(arr, low, mid-1, value)\n else:\n return self.binary_search(arr, mid+1, high, value)\n\n def numFriendRequests(self, ages: List[int]) -> int:\n ages = sorted(ages)\n total_count = 0\n for i in range(len(ages)-1, -1, -1):\n if i+1 < len(ages) and ages[i] == ages[i+1]:\n total_count+= prev_count\n continue\n\n prev_count = 0\n lower_limit = 0.5 * ages[i] + 7\n index = self.binary_search(ages, 0, i-1, lower_limit)\n prev_count = i - (index+1)\n total_count+=prev_count\n return total_count", "solution_js": "var numFriendRequests = function(ages) {\n const count = new Array(121).fill(0);\n\n ages.forEach((age) => count[age]++);\n\n let res = 0; // total friend request sent\n let tot = 0; // cumulative count of people so far\n\n for (let i = 0; i <= 120; i++) {\n\n if (i > 14 && count[i] != 0) {\n const limit = Math.floor(0.5 * i) + 7;\n const rest = tot - count[limit];\n\n res += (count[i] * rest); // current age group send friend request to other people who are within their limit\n res += (count[i] * (count[i] - 1)); // current age group send friend request to each other\n }\n\n tot += count[i];\n count[i] = tot;\n }\n\n return res;\n};", "solution_java": "class Solution {\n static int upperBound(int arr[], int target) {\n int l = 0, h = arr.length - 1;\n for (; l <= h;) {\n int mid = (l + h) >> 1;\n if (arr[mid] <= target)\n l = mid + 1;\n else\n h = mid - 1;\n }\n return l;\n }\n public int numFriendRequests(int[] ages) {\n long ans = 0;\n Arrays.sort(ages);\n\t\t// traversing order doesn't matter as we are doing binary-search in whole array\n\t\t// you can traverse from left side also\n for(int i = ages.length - 1;i >= 0;--i){\n int k = upperBound(ages,ages[i] / 2 + 7);\n int t = upperBound(ages,ages[i]);\n ans += Math.max(0,t - k - 1);\n }\n return (int)ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numFriendRequests(vector& ages) {\n sort(ages.begin(), ages.end());\n int sum = 0;\n for (int i=ages.size()-1; i>=0; i--) {\n int cutoff = 0.5f * ages[i] + 7;\n int j = upper_bound(ages.begin(), ages.end(), cutoff) - ages.begin();\n int k = upper_bound(ages.begin(), ages.end(), ages[i]) - ages.begin();\n sum += max(0, k-j-1);\n }\n return sum;\n }\n};" }, { "title": "Rank Teams by Votes", "algo_input": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.\n\nThe ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.\n\nGiven an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.\n\nReturn a string of all teams sorted by the ranking system.\n\n \nExample 1:\n\nInput: votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput: \"ACB\"\nExplanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.\nTeam B was ranked second by 2 voters and was ranked third by 3 voters.\nTeam C was ranked second by 3 voters and was ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team and team B is the third.\n\n\nExample 2:\n\nInput: votes = [\"WXYZ\",\"XYZW\"]\nOutput: \"XWYZ\"\nExplanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. \n\n\nExample 3:\n\nInput: votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput: \"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation: Only one voter so his votes are used for the ranking.\n\n\n \nConstraints:\n\n\n\t1 <= votes.length <= 1000\n\t1 <= votes[i].length <= 26\n\tvotes[i].length == votes[j].length for 0 <= i, j < votes.length.\n\tvotes[i][j] is an English uppercase letter.\n\tAll characters of votes[i] are unique.\n\tAll the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.\n\n", "solution_py": "#[\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\n#d = {\n# \"A\": [5, 0, 0],\n# \"B\": [0, 2, 3],\n# \"C\": [0, 3, 2]\n#}\n#keys represent the candidates\n#index of array in dict represent the rank\n#value of array item represent number of votes casted\n#ref: https://www.programiz.com/python-programming/methods/built-in/sorted\nclass Solution:\n #T=O(mn + mlgm), S=O(mn)\n\t#n=number of votes\n\t#m=number of candidates and m(number of ranks) is constant(26)\n def rankTeams(self, votes: List[str]) -> str:\n d = {}\n #build the dict\n #T=O(mn), S=O(mn)\n\t\t#n=number of votes, m=number of candidates(26)\n for vote in votes:\n for i, c in enumerate(vote):\n #if key not in dict\n if c not in d:\n #d[char] = [0, 0, 0]\n d[c] = [0]*len(vote)\n #increment the count of votes for each rank\n #d[\"A\"][0] = 1\n d[c][i] += 1\n #sort the dict keys in ascending order because if there is a tie we return in ascending order\n\t\t#sorted uses a stable sorting algorithm\n #T=O(mlgm), S=O(m)\n vote_names = sorted(d.keys()) #d.keys()=[\"A\", \"B\", \"C\"]\n #sort the dict keys based on votes for each rank in descending order\n #T=O(mlgm), S=O(m)\n #sorted() always returns a list\n vote_rank = sorted(vote_names, reverse=True, key= lambda x: d[x])\n #join the list\n return \"\".join(vote_rank)", "solution_js": "var rankTeams = function(votes) {\n if(votes.length == 1)\n return votes[0];\n let map = new Map()\n for(let vote of votes){\n for(let i = 0; i < vote.length;i++){\n if(!(map.has(vote[i]))){\n //create all the values set as zero\n map.set(vote[i],Array(vote.length).fill(0))\n }\n let val = map.get(vote[i])\n val[i] = val[i] + 1\n map.set(vote[i], val)\n }\n }\n\n let obj = [...map.entries()]; //converting as array [\"A\",[5,0,0]]\n obj = obj.sort((a,b) => {\n for(let i = 0; i < a[1].length;i++){\n if(a[1][i] > b[1][i])\n return -1;\n else if(a[1][i] < b[1][i])\n return 1;\n }\n // if all chars are in same positon return the value charcode\n return a[0].charCodeAt(0) - b[0].charCodeAt(0);\n })\n return obj.map(item => item[0]).join('')\n};", "solution_java": "class Solution {\n public String rankTeams(String[] votes) {\n int n = votes.length;\n int teams = votes[0].length();\n Map map = new HashMap<>();\n List chars = new ArrayList<>();\n\n for(int i = 0 ; i < teams ; i++) {\n char team = votes[0].charAt(i);\n map.put(team, new int[teams]);\n chars.add(team);\n }\n\n for(int i = 0 ; i < n ; i++) {\n String round = votes[i];\n for(int j = 0 ; j < round.length() ; j++) {\n map.get(round.charAt(j))[j]+=1;\n }\n }\n\n chars.sort((a,b) -> {\n int[] l1 = map.get(a);\n int[] l2 = map.get(b);\n for(int i = 0 ; i < l1.length; i++) {\n if(l1[i] < l2[i]) {\n return 1;\n }\n else if(l1[i] > l2[i]) {\n return -1;\n }\n }\n return a.compareTo(b);\n });\n\n StringBuilder sb = new StringBuilder();\n for(char c : chars) {\n sb.append(c);\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n\n static bool cmp(vectora, vectorb){\n\n for(int i = 1; ib[i];\n }\n }\n\n return a[0]& votes) {\n\n int noofteams = votes[0].size();\n string ans = \"\";\n vector>vec(noofteams, vector(noofteams+1, 0));\n\n unordered_mapmp;\n for(int i = 0; i None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n prev = None #You can also define that variable inside the init function using self keyword\n def dfs(root):\n nonlocal prev\n\n if not root:\n return\n\n dfs(root.right)\n dfs(root.left)\n\n root.right = prev\n root.left = None\n prev = root\n\n dfs(root)\n# If the above solution is hard to understand than one can do level order traversal\n#Using Stack DS but this will increase the space complexity to O(N).", "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 {void} Do not return anything, modify root in-place instead.\n */\nvar flatten = function(root) {\n const dfs = (node) => {\n if (!node) return\n\n if (!node.left && !node.right) return node\n\n const leftNode = node.left\n const rightNode = node.right\n\n const leftTree = dfs(leftNode)\n const rightTree = dfs(rightNode)\n\n if (leftTree) leftTree.right = rightNode\n\n node.left = null\n node.right = leftNode || rightNode\n\n return rightTree || leftTree\n }\n\n dfs(root)\n return root\n};", "solution_java": "class Solution {\n public void flatten(TreeNode root) {\n TreeNode curr=root;\n while(curr!=null)\n {\n if(curr.left!=null)\n {\n TreeNode prev=curr.left;\n while(prev.right!=null)\n prev=prev.right;\n prev.right=curr.right;\n curr.right=curr.left; \n curr.left=null; \n }\n curr=curr.right;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* prev= NULL;\n \n void flatten(TreeNode* root) {\n if(root==NULL) return;\n \n flatten(root->right);\n flatten(root->left);\n \n root->right=prev;\n root->left= NULL;\n prev=root;\n }\n};" }, { "title": "Minimum Insertion Steps to Make a String Palindrome", "algo_input": "Given a string s. In one step you can insert any character at any index of the string.\n\nReturn the minimum number of steps to make s palindrome.\n\nA Palindrome String is one that reads the same backward as well as forward.\n\n \nExample 1:\n\nInput: s = \"zzazz\"\nOutput: 0\nExplanation: The string \"zzazz\" is already palindrome we don't need any insertions.\n\n\nExample 2:\n\nInput: s = \"mbadm\"\nOutput: 2\nExplanation: String can be \"mbdadbm\" or \"mdbabdm\".\n\n\nExample 3:\n\nInput: s = \"leetcode\"\nOutput: 5\nExplanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 500\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def minInsertions(self, s: str) -> int:\n n = len(s)\n prev_prev = [0]*n\n prev = [0]*n\n curr = [0] * n\n\n for l in range(1, n):\n for i in range(l, n):\n if s[i] == s[i-l]:\n curr[i] = prev_prev[i-1]\n else:\n curr[i] = min(prev[i-1], prev[i])+1\n # print(curr)\n prev_prev, prev, curr = prev, curr, prev_prev\n \n return prev[-1]", "solution_js": "var minInsertions = function(s) {\n const len = s.length;\n const dp = new Array(len).fill(0).map(() => {\n return new Array(len).fill(-1);\n });\n\n const compute = (i = 0, j = len - 1) => {\n if(i >= j) return 0;\n\n if(dp[i][j] != -1) return dp[i][j];\n\n if(s[i] == s[j]) return compute(i + 1, j - 1);\n\n return dp[i][j] = Math.min(\n compute(i + 1, j),\n compute(i, j - 1)\n ) + 1;\n }\n return compute();\n};", "solution_java": "class Solution {\n public int minInsertions(String s) {\n StringBuilder sb = new StringBuilder(s);\n String str = sb.reverse().toString();\n int m=s.length();\n int n=str.length();\n System.out.println(str);\n return LCS(s,str,m,n);\n\n }\n public int LCS(String x, String y,int m,int n){\n int [][] t = new int [m+1][n+1];\n for(int i=0;i str:\n l=list(text.split(\" \"))\n l=sorted(l,key= lambda word: len(word))\n l=' '.join(l)\n return l.capitalize()", "solution_js": "var arrangeWords = function(text) {\n let sorted = text.toLowerCase().split(' ');\n \n sorted.sort((a, b) => a.length - b.length);\n \n sorted[0] = sorted[0].charAt(0).toUpperCase() + sorted[0].slice(1);\n \n return sorted.join(' ');\n};", "solution_java": "class Solution {\n public String arrangeWords(String text) {\n String[] words = text.split(\" \");\n for (int i = 0; i < words.length; i++) {\n words[i] = words[i].toLowerCase();\n }\n Arrays.sort(words, (s, t) -> s.length() - t.length());\n words[0] = Character.toUpperCase(words[0].charAt(0)) + words[0].substring(1);\n return String.join(\" \", words);\n }\n}", "solution_c": "class Solution {\npublic:\n vector> words ;\n string arrangeWords(string text) {\n //convert to lowercase alphabet \n text[0] += 32 ;\n \n istringstream iss(text) ;\n string word = \"\" ;\n\t\t\n\t\t//pos is the index of each word in text.\n int pos = 0 ;\n \n while(iss >> word){\n words.push_back({word,pos});\n ++pos ;\n }\n \n\t\t//sort by length and pos.\n sort(begin(words),end(words),[&](const pair &p1 , const pair &p2)->bool{\n if(size(p1.first) == size(p2.first)) return p1.second < p2.second ;\n return size(p1.first) < size(p2.first);\n });\n \n string ans = \"\" ;\n for(auto &x : words) ans += x.first + \" \" ;\n ans.pop_back() ;\n \n //convert to uppercase alphabet \n ans[0] -= 32 ;\n return ans ;\n \n \n }\n};" }, { "title": "Maximum Depth of N-ary Tree", "algo_input": "Given a n-ary tree, find its maximum depth.\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n\n \nExample 1:\n\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: 3\n\n\nExample 2:\n\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: 5\n\n\n \nConstraints:\n\n\n\tThe total number of nodes is in the range [0, 104].\n\tThe depth of the n-ary tree is less than or equal to 1000.\n\n", "solution_py": "class Solution:\n def maxDepth(self, root: 'Node') -> int:\n \n if not root : return 0\n \n if root.children :\n return 1 + max([self.maxDepth(x) for x in root.children])\n else :\n return 1 ", "solution_js": "/**\n * // Definition for a Node.\n * function Node(val,children) {\n * this.val = val;\n * this.children = children;\n * };\n */\n\n/**\n * @param {Node|null} root\n * @return {number}\n */\nvar maxDepth = function(root) {\n let max = 0;\n\n if (!root) {\n return max;\n }\n\n const search = (root, index) => {\n max = Math.max(index, max);\n\n if (root?.children && root?.children.length > 0) {\n for (let i = 0; i < root.children.length; i++) {\n search(root.children[i], index+1);\n }\n }\n }\n\n search(root, 1);\n\n return max;\n};", "solution_java": "class Solution {\n public int maxDepth(Node root) {\n if (root == null) return 0;\n int[] max = new int[]{0};\n dfs(root,1,max);\n return max[0];\n }\n public static void dfs(Node root, int depth, int[] max) {\n if (depth>max[0]) max[0] = depth;\n if(root==null){\n return;\n }\n ++depth;\n for(Node n:root.children) dfs(n, depth, max);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxDepth(Node* root) \n {\n if(root == NULL)\n {\n return 0;\n }\n int dep = 1, mx = INT_MIN;\n helper(root, dep, mx);\n return mx;\n }\n \n void helper(Node *root, int dep, int& mx)\n {\n if(root->children.size() == 0)\n {\n mx = max(mx, dep);\n }\n for(int i = 0 ; ichildren.size() ; i++)\n {\n helper(root->children[i], dep+1, mx);\n }\n }\n};" }, { "title": "Smallest String With A Given Numeric Value", "algo_input": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.\n\nThe numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8.\n\nYou are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.\n\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n\n \nExample 1:\n\nInput: n = 3, k = 27\nOutput: \"aay\"\nExplanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.\n\n\nExample 2:\n\nInput: n = 5, k = 73\nOutput: \"aaszz\"\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\tn <= k <= 26 * n\n\n", "solution_py": "class Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n ans = ['a']*n # Initialize the answer to be 'aaa'.. length n\n val = n #Value would be length as all are 'a'\n\n for i in range(n-1, -1, -1):\n if val == k: # if value has reached k, we have created our lexicographically smallest string\n break\n val -= 1 # reduce value by one as we are removing 'a' and replacing by a suitable character\n ans[i] = chr(96 + min(k - val, 26)) # replace with a character which is k - value or 'z'\n val += ord(ans[i]) - 96 # add the value of newly appended character to value\n\n return ''.join(ans) # return the ans string in the by concatenating the list", "solution_js": "var getSmallestString = function(n, k) {\n k -= n\n let alpha ='_bcdefghijklmnopqrstuvwxy_',\n ans = 'z'.repeat(~~(k / 25))\n if (k % 25) ans = alpha[k % 25] + ans\n return ans.padStart(n, 'a')\n};", "solution_java": "class Solution {\n public String getSmallestString(int n, int k) {\n char[] ch = new char[n];\n for(int i=0;i0) {\n currChar=Math.min(25,k);\n ch[--n]+=currChar;\n k-=currChar;\n }\n return String.valueOf(ch);\n }\n}", "solution_c": "class Solution {\npublic:\n string getSmallestString(int n, int k) {\n string str=\"\";\n for(int i=0;i=0 && diff>0;i--){\n if(diff>25){\n str[i]='z';\n diff-=25;\n }else{\n str[i]=char('a'+diff);\n return str;\n }\n }\n return str;\n }\n};\n// a a a a a\n// 5\n// diff= 73-5\n// " }, { "title": "Maximum XOR of Two Numbers in an Array", "algo_input": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.\n\n \nExample 1:\n\nInput: nums = [3,10,5,25,2,8]\nOutput: 28\nExplanation: The maximum result is 5 XOR 25 = 28.\n\n\nExample 2:\n\nInput: nums = [14,70,53,83,49,91,36,80,92,51,66,70]\nOutput: 127\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 105\n\t0 <= nums[i] <= 231 - 1\n\n", "solution_py": "class Solution:\n\tdef findMaximumXOR(self, nums: List[int]) -> int:\n\t\tTrieNode = lambda: defaultdict(TrieNode)\n\t\troot = TrieNode()\n\t\tfor n in nums:\n\t\t\tcur = root\n\t\t\tfor i in range(31,-1,-1):\n\t\t\t\tbit = 1 if n&(1< {\n let p = trie;\n for(let i = 31; i >= 0; i--) {\n const isSet = (num >> i) & 1;\n if(!p[isSet]) p[isSet] = {};\n p = p[isSet];\n }\n }\n const xor = (num) => {\n let p = trie;\n let ans = 0;\n for(let i = 31; i >= 0; i--) {\n const isSet = ((num >> i) & 1);\n const opp = 1 - isSet;\n const hasOpp = p[opp];\n if(hasOpp) {\n ans = ans | (1<= 0; i--) {\n int bit = (num >> i) & 1;\n if (!node.containsKey(bit)) {\n node.put(bit, new Node());\n }\n node = node.get(bit);\n }\n }\n \n public static int getMax(int num) {\n Node node = root;\n int maxNum = 0;\n \n for (int i = 31; i >= 0; i--) {\n int bit = (num >> i) & 1;\n if (node.containsKey(1 - bit)) {\n maxNum = maxNum | (1 << i);\n node = node.get(1 - bit);\n }\n else {\n node = node.get(bit);\n }\n }\n return maxNum;\n }\n}\n\n\nclass Solution {\n public int findMaximumXOR(int[] nums) {\n Trie trie = new Trie();\n \n for (int i = 0; i < nums.length; i++) {\n trie.insert(nums[i]);\n }\n \n int maxi = 0;\n for (int i = 0; i < nums.length; i++) {\n maxi = Math.max(maxi, trie.getMax(nums[i]));\n }\n return maxi;\n }\n}", "solution_c": "class Solution {\npublic:\n struct TrieNode {\n //trie with max 2 child, not taking any bool or 26 size value because no need\n TrieNode* one;\n TrieNode* zero;\n };\n void insert(TrieNode* root, int n) {\n TrieNode* curr = root;\n for (int i = 31; i >= 0; i--) {\n int bit = (n >> i) & 1; //it will find 31st bit and check it is 1 or 0\n if (bit == 0) {\n if (curr->zero == nullptr) { //if 0 then we will continue filling on zero side\n TrieNode* newNode = new TrieNode(); \n curr->zero = newNode; \n }\n curr = curr->zero; //increase cur to next zero position\n }\n else {\n //similarly if we get 1 \n if (curr->one == nullptr) {\n TrieNode* newNode = new TrieNode();\n curr->one = newNode;\n }\n curr = curr->one;\n }\n }\n }\n int findmax(TrieNode* root, int n) {\n TrieNode* curr = root;\n int ans = 0;\n for (int i = 31; i >= 0; i--) {\n int bit = (n >> i) & 1;\n if (bit == 1) {\n if (curr->zero != nullptr) { //finding complement , if find 1 then we will check on zero side\n ans += (1 << i); //push values in ans\n curr = curr->zero;\n }\n else {\n curr = curr->one; //if we don't get then go to one's side\n }\n }\n else {\n //similarly on zero side if we get 0 then we will check on 1 s side\n if (curr->one != nullptr) { \n ans += (1 << i);\n curr = curr->one;\n }\n else {\n curr = curr->zero;\n }\n }\n }\n return ans;\n }\n\n int findMaximumXOR(vector& nums) {\n int n = nums.size();\n TrieNode* root = new TrieNode();\n int ans = 0;\n for (int i = 0; i < n; i++) {\n insert(root, nums[i]); //it will make trie by inserting values\n }\n for (int i = 1; i < n; i++) {\n ans = max(ans, findmax(root, nums[i])); //find the necessary complementory values and maximum store\n }\n return ans;\n }\n};" }, { "title": "Valid Number", "algo_input": "A valid number can be split up into these components (in order):\n\n\n\tA decimal number or an integer.\n\t(Optional) An 'e' or 'E', followed by an integer.\n\n\nA decimal number can be split up into these components (in order):\n\n\n\t(Optional) A sign character (either '+' or '-').\n\tOne of the following formats:\n\t\n\t\tOne or more digits, followed by a dot '.'.\n\t\tOne or more digits, followed by a dot '.', followed by one or more digits.\n\t\tA dot '.', followed by one or more digits.\n\t\n\t\n\n\nAn integer can be split up into these components (in order):\n\n\n\t(Optional) A sign character (either '+' or '-').\n\tOne or more digits.\n\n\nFor example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"], while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"].\n\nGiven a string s, return true if s is a valid number.\n\n \nExample 1:\n\nInput: s = \"0\"\nOutput: true\n\n\nExample 2:\n\nInput: s = \"e\"\nOutput: false\n\n\nExample 3:\n\nInput: s = \".\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 20\n\ts consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.\n\n", "solution_py": "class Solution:\n def isNumber(self, s: str) -> bool:\n if s == \"inf\" or s == \"-inf\" or s == \"+inf\" or s == \"Infinity\" or s == \"-Infinity\" or s == \"+Infinity\":\n return False\n try:\n float(s)\n except (Exception):\n return False\n return True", "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar isNumber = function(s) {\n const n = s.length;\n const CHAR_CODE_UPPER_E = 'E'.charCodeAt(0);\n const CHAR_CODE_LOWER_E = 'e'.charCodeAt(0);\n const CHAR_CODE_UPPER_A = 'A'.charCodeAt(0);\n const CHAR_CODE_UPPER_Z = 'Z'.charCodeAt(0);\n const CHAR_CODE_LOWER_A = 'a'.charCodeAt(0);\n const CHAR_CODE_LOWER_Z = 'z'.charCodeAt(0);\n\n let sign = '';\n let decimal = '';\n let exponential = '';\n let exponentialSign = '';\n let num = '';\n for(let i = 0; i < n; i += 1) {\n const char = s[i];\n const charCode = s.charCodeAt(i);\n\n if(char === '+' || char === '-') {\n if(i === n - 1) return false;\n if(i === 0) {\n sign = char;\n continue;\n }\n\n if(exponentialSign.length > 0) return false;\n if(!(s[i - 1] === 'e' || s[i - 1] === 'E')) return false;\n exponentialSign = char;\n continue;\n }\n\n if(char === '.') {\n if(decimal.length > 0) return false;\n if(exponential.length > 0) return false;\n if(num.length === 0 && i === n - 1) return false;\n\n decimal = char;\n continue;\n }\n\n if(charCode === CHAR_CODE_UPPER_E || charCode === CHAR_CODE_LOWER_E) {\n if(exponential.length > 0) return false;\n if(i === n - 1) return false;\n if(num.length === 0) return false;\n\n exponential = char;\n continue;\n }\n\n if(charCode >= CHAR_CODE_UPPER_A && charCode <= CHAR_CODE_UPPER_Z) {\n return false;\n }\n\n if(charCode >= CHAR_CODE_LOWER_A && charCode <= CHAR_CODE_LOWER_Z) {\n return false;\n }\n\n num += char;\n }\n\n return true;\n};", "solution_java": "class Solution {\n public boolean isNumber(String s) {\n try{\n int l=s.length();\n if(s.equals(\"Infinity\")||s.equals(\"-Infinity\")||s.equals(\"+Infinity\")||s.charAt(l-1)=='f'||s.charAt(l-1)=='d'||s.charAt(l-1)=='D'||s.charAt(l-1)=='F')\n return false;\n double x=Double.parseDouble(s);\n return true;\n }\n catch(Exception e){\n return false;\n }\n \n }\n}", "solution_c": "/*\nMax Possible combination of characters in the string has followig parts(stages) :\n +/- number . number e/E +/- number\nstages: 0 1 2 3 4 5 6 7\n\nNow check each characters at there correct stages or not and increament the stage\nas per the character found at ith position.\n\n*/\n\nclass Solution {\npublic:\n bool isNumber(string s){\n char stage = 0;\n for(int i = 0; i 1 && stage < 5){ stage = 5; }\n else if(s[i] == '.' && stage < 3) {\n //both side of '.' do not have any digit then return false\n if(stage <= 1 && ( i + 1 >= s.size() || !(s[i+1] >= '0' && s[i+1] <= '9')) ) return false;\n stage = 3;\n }else if(s[i] >= '0' && s[i] <= '9'){\n if(!(stage == 2 || stage == 4 || stage == 7) ) stage++;\n if(stage == 1 || stage == 6 ) stage++;\n }else return false;\n }\n if(stage <= 1 || stage == 5 || stage == 6) return false;\n return true;\n }\n};" }, { "title": "Sort Integers by The Number of 1 Bits", "algo_input": "You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.\n\nReturn the array after sorting it.\n\n \nExample 1:\n\nInput: arr = [0,1,2,3,4,5,6,7,8]\nOutput: [0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]\n\n\nExample 2:\n\nInput: arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput: [1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 500\n\t0 <= arr[i] <= 104\n\n", "solution_py": "class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n binary = []\n final = []\n arr.sort()\n for i in arr:\n binary.append(bin(i).count(\"1\"))\n for i,j in zip(arr,binary):\n final.append((i,j))\n z = sorted(final, key=lambda x:x[1])\n \n ls = []\n for k in z:\n ls.append(k[0])\n \n return ls", "solution_js": "var sortByBits = function(arr) {\n const map = {};\n \n for (let n of arr) {\n let counter = 0, item = n;\n \n while (item > 0) {\n\t\t\tcounter += (item & 1); //increment counter if the lowest (i.e. the rightest) bit is 1\n\t\t\titem = (item >> 1); //bitwise right shift (here is equivalent to division by 2)\n }\n \n map[n] = counter;\n }\n\n return arr.sort((a, b) => map[a] - map[b] || a - b) //sort by number of 1 bits; if equal, sort by value\n};", "solution_java": "class Solution {\n public int[] sortByBits(int[] arr) {\n\n Integer[] arrInt = new Integer[arr.length];\n\n for(int i=0;i() {\n @Override\n public int compare(Integer a, Integer b) {\n int aBits=numOfBits(a);\n int bBits=numOfBits(b);\n if(aBits==bBits) {\n return a-b;\n }\n return aBits-bBits;\n }\n });\n\n for(int i=0;i>>1;\n }\n\n return bits;\n }\n}", "solution_c": "class Solution {\npublic:\n vector sortByBits(vector& arr) {\n int n = size(arr);\n priority_queue> pq;\n \n for(auto &x : arr) {\n int count = 0;\n int a = x;\n while(a) {\n count += a & 1;\n a >>= 1;\n }\n pq.push({count, x});\n }\n n = n - 1;\n while(!pq.empty()) {\n arr[n--] = pq.top().second;\n pq.pop();\n }\n \n return arr;\n }\n};" }, { "title": "Valid Palindrome II", "algo_input": "Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n\n \nExample 1:\n\nInput: s = \"aba\"\nOutput: true\n\n\nExample 2:\n\nInput: s = \"abca\"\nOutput: true\nExplanation: You could delete the character 'c'.\n\n\nExample 3:\n\nInput: s = \"abc\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def validPalindrome(self, s: str) -> bool:\n has_deleted = False\n\n def compare(s, has_deleted):\n\n if len(s) <= 1:\n return True\n\n if s[0] == s[-1]:\n return compare(s[1:-1], has_deleted)\n else:\n if not has_deleted:\n return compare(s[1:], True) or compare(s[:-1], True)\n else:\n return False\n\n return compare(s, has_deleted)", "solution_js": "/*\nSolution:\n\n1. Use two pointers, one initialised to 0 and the other initialised to end of string. Check if characters at each index\nare the same. If they are the same, shrink both pointers. Else, we have two possibilities: one that neglects character\nat left pointer and the other that neglects character at right pointer. Hence, we check if s[low+1...right] is a palindrome\nor s[low...right-1] is a palindrome. If one of them is a palindrome, we know that we can form a palindrome with one deletion and return true. Else, we require more than one deletion, and hence we return false.\n*/\nvar validPalindrome = function(s) {\n let low = 0, high = s.length-1;\n while (low < high) {\n if (s[low] !== s[high]) {\n return isPalindrome(s, low+1, high) || isPalindrome(s, low, high-1);\n }\n low++, high--;\n }\n return true;\n // T.C: O(N)\n // S.C: O(1)\n};\n\nfunction isPalindrome(str, low, high) {\n while (low < high) {\n if (str[low] !== str[high]) return false;\n low++, high--;\n }\n return true;\n}", "solution_java": "class Solution {\n boolean first = false;\n public boolean validPalindrome(String s) {\n int left = 0;\n int right = s.length()-1;\n \n \n while(left <= right){\n if( s.charAt(left) == (s.charAt(right))){\n left++;\n right--;\n }else if(!first){\n first = true;\n String removeLeft = s.substring(0,left).concat(s.substring(left+1));\n String removeright = s.substring(0,right).concat(s.substring(right+1));\n left++;\n right--;\n return validPalindrome(removeLeft) || validPalindrome(removeright); \n } else {\n return false;\n }\n }\n return true; \n }\n}", "solution_c": "class Solution {\n int first_diff(string s) {\n for (int i = 0; i < (s.size() + 1) / 2; ++i) {\n if (s[i] != s[s.size() - 1 - i]) {\n return i;\n }\n }\n return -1;\n }\npublic:\n bool validPalindrome(string s) {\n int diff = first_diff(s);\n if (diff == -1 || (s.size() % 2 == 0 && diff + 1 == s.size() / 2)) {\n // abca. If we have pattern like this than we can delete one of the symbols\n return true;\n }\n \n bool first_valid = true;\n for (int i = diff; i < (s.size() + 1) / 2; ++i) {\n if (s[i] != s[s.size() - 2 - i]) {\n first_valid = false;\n break;\n }\n }\n \n bool second_valid = true;\n for (int i = diff; i < (s.size() + 1) / 2; ++i) {\n if (s[i + 1] != s[s.size() - 1 - i]) {\n second_valid = false;\n break;\n }\n }\n return first_valid || second_valid;\n }\n};" }, { "title": "Add Two Numbers", "algo_input": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\n \nExample 1:\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [7,0,8]\nExplanation: 342 + 465 = 807.\n\n\nExample 2:\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\nExample 3:\n\nInput: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput: [8,9,9,9,0,0,0,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in each linked list is in the range [1, 100].\n\t0 <= Node.val <= 9\n\tIt is guaranteed that the list represents a number that does not have leading zeros.\n\n", "solution_py": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummyHead = ListNode(0)\n tail = dummyHead\n carry = 0\n\n while l1 is not None or l2 is not None or carry != 0:\n digit1 = l1.val if l1 is not None else 0\n digit2 = l2.val if l2 is not None else 0\n\n sum = digit1 + digit2 + carry\n digit = sum % 10\n carry = sum // 10\n\n newNode = ListNode(digit)\n tail.next = newNode\n tail = tail.next\n\n l1 = l1.next if l1 is not None else None\n l2 = l2.next if l2 is not None else None\n\n result = dummyHead.next\n dummyHead.next = None\n return result", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nvar addTwoNumbers = function(l1, l2) {\n var List = new ListNode(0);\n var head = List;\n var sum = 0;\n var carry = 0;\n\n while(l1!==null||l2!==null||sum>0){\n\n if(l1!==null){\n sum = sum + l1.val;\n l1 = l1.next;\n }\n if(l2!==null){\n sum = sum + l2.val;\n l2 = l2.next;\n }\n if(sum>=10){\n carry = 1;\n sum = sum - 10;\n }\n\n head.next = new ListNode(sum);\n head = head.next;\n\n sum = carry;\n carry = 0;\n\n }\n\n return List.next;\n};", "solution_java": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n if(l1 == null) return l2;\n if(l2 == null) return l1;\n \n ListNode dummy = new ListNode(-1);\n ListNode temp = dummy;\n int carry = 0;\n while(l1 != null || l2 != null || carry != 0){\n int sum = 0;\n if(l1 != null){\n sum += l1.val;\n l1 = l1.next;\n }\n if(l2 != null){\n sum += l2.val;\n l2 = l2.next;\n } \n sum += carry;\n carry = sum / 10;\n ListNode node = new ListNode(sum % 10);\n temp.next = node;\n temp = temp.next;\n }\n return dummy.next;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode *head1, *head2, *head3, *temp;\n head1=l1;\n head2 = l2;\n head3=NULL;\n int carry = 0, res = 0;\n while(head1 && head2){\n res = head1->val +head2->val + carry;\n carry = res/10;\n head1->val = res%10;\n if(!head3){\n head3 = head1;\n temp = head3;\n }\n else{\n temp->next = head1;\n temp = temp->next;\n }\n head1 = head1->next;\n head2 = head2->next;\n }\n while(head1){\n res = head1->val + carry;\n carry = res/10;\n head1->val = res%10;\n temp->next = head1;\n temp = temp->next;\n head1 = head1->next;\n }\n while(head2){\n res = head2->val + carry;\n carry = res/10;\n head2->val = res%10;\n temp->next = head2;\n temp = temp->next;\n head2 = head2->next;\n }\n if(carry){\n ListNode* result = new ListNode();\n result->val = carry;\n result->next = NULL;\n temp->next = result;\n temp = temp->next;\n }\n return head3;\n }\n};" }, { "title": "Next Greater Numerically Balanced Number", "algo_input": "An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.\n\nGiven an integer n, return the smallest numerically balanced number strictly greater than n.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 22\nExplanation: \n22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.\n\n\nExample 2:\n\nInput: n = 1000\nOutput: 1333\nExplanation: \n1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.\n\n\nExample 3:\n\nInput: n = 3000\nOutput: 3133\nExplanation: \n3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.\n\n\n \nConstraints:\n\n\n\t0 <= n <= 106\n\n", "solution_py": "class Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n n_digits = len(str(n))\n \n next_max = {\n 1: [1],\n 2: [22],\n 3: [122, 333],\n 4: [1333, 4444],\n 5: [14444, 22333, 55555],\n 6: [122333, 224444, 666666, 155555],\n 7: [1224444, 2255555, 3334444, 1666666, 7777777]\n }\n \n if n >= int(str(n_digits) * n_digits):\n n_digits += 1\n return min(next_max[n_digits])\n \n ans = float('inf')\n for num in sorted(next_max[n_digits]): \n cands = set(permutations(str(num)))\n cands = sorted(map(lambda x: int(\"\".join(x)), cands))\n \n loc = bisect.bisect(cands, n)\n if loc < len(cands): \n ans = min(ans, cands[loc])\n \n return ans", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar nextBeautifulNumber = function(n) {\n //1224444 is next minimum balanced number after 10^6\n for(let i=n+1; i<=1224444;i++){//Sequency check each number from n+1 to 1224444\n if(isNumericallyBalanced(i)){\n return i;//Return the number if is a balanced number\n }\n }\n function isNumericallyBalanced(n){\n let map={},d,nStr=n.toString();\n while(n>0){//Create a map of digits with frequency\n d = n%10;\n if(d>nStr.length){//If we have found a digit greater than the lenght of the number like 227333, here when we see 7, we can return false\n return false;\n }\n if(map[d]===undefined){\n map[d]=1;\n }else{\n map[d]++;\n if(map[d]>d){//If a digit has frequency more than its value, for example 22333344, here when we see fourth 3 than we can return false\n return false;\n }\n }\n n = Math.floor(n/10);\n }\n for(let key in map){//Check if frequency is equal to the digit\n if(map[key]!==parseInt(key)){\n return false;\n }\n }\n return true;\n }\n};", "solution_java": "class Solution {\n public int nextBeautifulNumber(int n) {\n\n while(true){\n n++;\n int num = n; //test this number\n int [] freq = new int[10]; // 0 to 9\n\n while(num > 0){ //calculate freq of each digit in the num\n int rem = num % 10; //this is remainder\n num = num / 10; //this is quotient\n freq[rem] = freq[rem] + 1; //increase its frequency\n if(freq[rem] > rem) break;\n }\n\n boolean ans = true;\n\n for(int i = 0;i<10;i++){ //check frequency of each digit\n if(freq[i] != i && freq[i] != 0){\n ans = false;\n break;\n }\n }\n\n if(ans == true){\n return n;\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n bool valid(int n)\n {\n vector map(10,0);\n while(n)\n {\n int rem = n%10;\n map[rem]++;\n n = n/10;\n }\n for(int i=0; i<10; i++)\n if(map[i] && map[i]!=i) return false;\n return true;\n }\n \n int nextBeautifulNumber(int n) {\n \n while(true) \n {\n ++n;\n if(valid(n))\n return n;\n }\n return 1;\n }\n};" }, { "title": "Is Subsequence", "algo_input": "Given two strings s and t, return true if s is a subsequence of t, or false otherwise.\n\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n\n \nExample 1:\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nExample 2:\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n \nConstraints:\n\n\n\t0 <= s.length <= 100\n\t0 <= t.length <= 104\n\ts and t consist only of lowercase English letters.\n\n\n \nFollow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?", "solution_py": "class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n if len(s) > len(t):return False\n if len(s) == 0:return True\n subsequence=0\n for i in range(0,len(t)):\n if subsequence <= len(s) -1:\n print(s[subsequence])\n if s[subsequence]==t[i]:\n\n subsequence+=1\n return subsequence == len(s) ", "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isSubsequence = function(s, t) {\n for (let i = 0, n = s.length; i < n; i++)\n if (t.includes(s[i]))\n t = t.slice(t.indexOf(s[i]) + 1);\n else return false;\n \n return true;\n}", "solution_java": "class Solution \n{\n public boolean isSubsequence(String s, String t) \n {\n int i,x,p=-1;\n if(s.length()>t.length())\n return false;\n for(i=0;ip)\n p=x;\n else\n return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isSubsequence(string s, string t) {\n int n = s.length(),m=t.length();\n int j = 0; \n // For index of s (or subsequence\n \n // Traverse s and t, and\n // compare current character\n // of s with first unmatched char\n // of t, if matched\n // then move ahead in s\n for (int i = 0; i < m and j < n; i++)\n if (s[j] == t[i])\n j++;\n \n // If all characters of s were found in t\n return (j == n);\n }\n};" }, { "title": "Permutation in String", "algo_input": "Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.\n\nIn other words, return true if one of s1's permutations is the substring of s2.\n\n \nExample 1:\n\nInput: s1 = \"ab\", s2 = \"eidbaooo\"\nOutput: true\nExplanation: s2 contains one permutation of s1 (\"ba\").\n\n\nExample 2:\n\nInput: s1 = \"ab\", s2 = \"eidboaoo\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= s1.length, s2.length <= 104\n\ts1 and s2 consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n s1_map = {}\n s2_map = {}\n for i in range(ord('a') , ord('z') + 1):\n s1_map[chr(i)] = 0\n s2_map[chr(i)] = 0\n \n for i in s1:\n s1_map[i] += 1\n \n l = 0\n r = 0\n \n while r < len(s2):\n print(s2_map , l ,r)\n if r == 0:\n while r < len(s1):\n s2_map[s2[r]] += 1\n r += 1\n if s2_map == s1_map:\n return True\n\n else:\n s2_map[s2[l]] -= 1\n s2_map[s2[r]] += 1\n \n if s2_map == s1_map:\n return True\n else:\n l += 1\n r += 1\n \n return False ", "solution_js": "const getCharIdx = (c) => c.charCodeAt(0) - 'a'.charCodeAt(0);\nconst isEqual = (a, b) => a.every((v, i) => v == b[i]);\n\nvar checkInclusion = function(s1, s2) {\n const occS1 = new Array(26).fill(0);\n const occS2 = new Array(26).fill(0);\n\n const s1Len = s1.length, s2Len = s2.length;\n\n if(s1Len > s2Len) return false;\n\n let l = 0, r = 0;\n for(; r < s1Len ; r++) {\n occS1[getCharIdx(s1[r])]++;\n occS2[getCharIdx(s2[r])]++;\n }\n\n if(isEqual(occS1, occS2)) {\n return true;\n }\n\n for(; r < s2Len; r++) {\n occS2[getCharIdx(s2[r])]++;\n occS2[getCharIdx(s2[l++])]--;\n\n if(isEqual(occS1, occS2)) return true;\n }\n\n return false;\n};", "solution_java": "class Solution {\n public boolean checkInclusion(String s1, String s2) {\n if(s1.length() > s2.length()) {\n return false;\n }\n \n int[]s1Count = new int[26];\n int[]s2Count = new int[26];\n \n for(int i = 0; i < s1.length(); i++) {\n char c = s1.charAt(i);\n char s = s2.charAt(i);\n s1Count[c - 'a'] += 1;\n s2Count[s - 'a'] += 1;\n }\n \n int matches = 0;\n \n for(int i = 0; i < 26;i++) {\n if(s1Count[i] == s2Count[i]) {\n matches+=1;\n }\n }\n \n int left = 0;\n for(int right = s1.length(); right < s2.length();right++) {\n if(matches == 26) {\n return true;\n }\n \n int index = s2.charAt(right) - 'a';\n s2Count[index] += 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] + 1 == s2Count[index]) {\n matches -= 1;\n }\n \n index = s2.charAt(left) - 'a';\n s2Count[index] -= 1;\n if(s1Count[index] == s2Count[index]) {\n matches += 1;\n }\n else if(s1Count[index] - 1 == s2Count[index]) {\n matches -= 1;\n }\n left += 1;\n }\n \n if(matches == 26) {\n return true;\n }\n \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool checkInclusion(string s1, string s2) {\n\t\tsort(s1.begin(),s1.end());\n\t\tint n = s1.size(), m = s2.size();\n\t\tfor(int i=0;i<=m-n;i++)\n\t\t{\n\t\t\tstring s = s2.substr(i,n);\n\t\t\tsort(s.begin(),s.end());\n\t\t\tif(s1 == s) return true;\n\t\t}\n\t\treturn false;\n\t}\n};" }, { "title": "Egg Drop With 2 Eggs and N Floors", "algo_input": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.\n\nYou know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\n\nIn each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n\n \nExample 1:\n\nInput: n = 2\nOutput: 2\nExplanation: We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.\n\n\nExample 2:\n\nInput: n = 100\nOutput: 14\nExplanation: One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\n", "solution_py": "class Solution:\n @cache\n def twoEggDrop(self, n: int) -> int:\n return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1)", "solution_js": "/** https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/\n * @param {number} n\n * @return {number}\n */\nvar twoEggDrop = function(n) {\n // Writing down strategy on example 2 we can observe following pattern:\n // Drop at floor: 9 22 34 45 55 64 72 79 85 90 94 97 99 100\n // Diff from prev: 13 12 11 10 9 8 7 6 5 4 3 2 1\n \n // So we have hypothesis algorithm\n // That is, `n` minus `d` until `result(n)` is smaller than `d`, where `d` start at 1 and increment by 1 for each iteration. If `result(n)` is 0, subtract 1, else return the result\n \n let d = 1;\n \n while (n > d) {\n n -= d;\n d++;\n }\n \n if (n == 0) {\n d--;\n }\n \n return d;\n};", "solution_java": "class Solution {\n public int twoEggDrop(int n) {\n int egg = 2; // hard coded to 2 eggs for this problem\n int[][] dp = new int[n+1][egg+1];\n return eggDrop(n, egg, dp);\n }\n\n int eggDrop(int n, int egg, int[][] dp) {\n if(n <= 2 || egg == 1) return n;\n if(dp[n][egg] != 0) return dp[n][egg];\n int min = n; // when you drop at each floor starting from 1\n for(int i = 1; i < n; i++) {\n int eggBreak = 1 + eggDrop(i-1, egg-1, dp); // drops needed if egg breaks at this floor\n int noEggBreak = 1 + eggDrop(n-i, egg, dp); // drops needed if egg does not break at this floor\n int moves = Math.max(eggBreak, noEggBreak); // since we want certain moves for n floor take max\n min = Math.min(min, moves);\n }\n dp[n][egg] = min;\n return min;\n }\n}", "solution_c": "int dp[1001][1001];\nclass Solution {\npublic:\n int solve(int e, int f){\n if(f == 0 || f == 1){\n return f;\n }\n if(e == 1){\n return f;\n }\n if(dp[e][f] != -1) return dp[e][f];\n int mn = INT_MAX;\n int left = 1, right = f;\n while(left <= right){\n int mid = left + (right-left)/2;\n int left_result = solve(e-1,mid-1);\n int right_result = solve(e,f-mid);\n mn = min(mn,1+max(left_result, right_result));\n if(left_result int:\n costs.sort()\n i= 0\n for price in costs:\n if price<= coins:\n i+= 1\n coins-= price\n else:\n break\n return i", "solution_js": "var maxIceCream = function(costs, coins) {\n costs.sort((a, b) => a - b);\n let count = 0;\n\n for (let i = 0; i < costs.length; i++) {\n if (costs[i] <= coins) {\n count++;\n coins -= costs[i]\n } else {\n break; // a small optimization, end the loop early if coins go down to zero before we reach end of the length of costs.\n }\n }\n return count;\n};", "solution_java": "class Solution {\n public int maxIceCream(int[] costs, int coins) {\n\n //Greedy Approach\n //a. sort cost in increasing order\n\n Arrays.sort(costs);\n\n int count = 0;\n for(int cost : costs){\n\n //b. check remainig coin is greater or equal than cuurent ice - cream cost\n if(coins - cost >= 0) {\n coins -= cost;\n count++;\n }\n }\n\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxIceCream(vector& costs, int coins) {\n int n=costs.size();\n\n sort(costs.begin(),costs.end());\n \n int i=0;\n for(;i=costs[i];i++){\n coins-=costs[i];\n }\n \n return i;\n }\n};" }, { "title": "Lowest Common Ancestor of Deepest Leaves", "algo_input": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.\n\nRecall that:\n\n\n\tThe node of a binary tree is a leaf if and only if it has no children\n\tThe depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.\n\tThe lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.\n\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 leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\n\nExample 2:\n\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree, and it's the lca of itself.\n\n\nExample 3:\n\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 1000].\n\t0 <= Node.val <= 1000\n\tThe values of the nodes in the tree are unique.\n\n\n \nNote: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/\n", "solution_py": "class Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n\n self.max_lvl = (0,[])\n self.pathes = {}\n def rec(root,parent,lvl):\n if not root:\n return\n if lvl > self.max_lvl[0]:\n self.max_lvl = (lvl,[root])\n elif lvl == self.max_lvl[0]:\n self.max_lvl = (lvl,self.max_lvl[1]+[root])\n self.pathes[root] = parent\n rec(root.left,root,lvl+1)\n rec(root.right,root,lvl+1)\n rec(root,None,0)\n print(self.max_lvl)\n # for key in self.pathes:\n # if key!=None and self.pathes[key]!=None:\n # print(key.val,\"-\",self.pathes[key].val)\n if len(self.max_lvl[1]) < 2:\n return self.max_lvl[1][0]\n parent = self.max_lvl[1]\n while len(parent) > 1:\n temp = set()\n for p in parent:\n temp.add(self.pathes.get(p,None))\n parent = temp\n return parent.pop()", "solution_js": "var lcaDeepestLeaves = function(root) {\n if(!root) return root;\n // keep track of max depth if node have both deepest node\n let md = 0, ans = null;\n const compute = (r = root, d = 0) => {\n if(!r) {\n md = Math.max(md, d);\n return d;\n }\n\n const ld = compute(r.left, d + 1);\n const rd = compute(r.right, d + 1);\n\n if(ld == rd && ld == md) {\n ans = r;\n }\n\n return Math.max(ld, rd);\n }\n compute();\n return ans;\n};", "solution_java": "class Solution {\n public TreeNode lcaDeepestLeaves(TreeNode root) {\n if (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": "class Solution {\npublic:\n \n stackst;\n \n vectorvec;\n int mx = INT_MIN;\n \n void ch(TreeNode * root, int h){\n if(!root) return ;\n ch(root->left, h+1);\n ch(root->right, h+1);\n \n if(h==mx){\n vec.push_back(root);\n }\n else if(h>mx){\n vec.clear();\n vec.push_back(root);\n mx = h;\n }\n }\n \n bool uf = 0;\n \n void check(TreeNode * root, TreeNode * it){\n \n if(!root or uf) return ;\n \n st.push(root);\n \n if(root->val == it->val){\n uf = 1;\n return ;\n }\n \n check(root->left, it);\n check(root->right, it);\n \n if(!uf)\n st.pop();\n }\n \n TreeNode* lcaDeepestLeaves(TreeNode* root) {\n vec.clear();\n ch(root, 0);\n vector>ans;\n ans.clear();\n int mnx = INT_MAX;\n for(auto it:vec){\n uf = 0;\n check(root, it);\n vectortemp;\n \n while(!st.empty()){\n temp.push_back(st.top());\n st.pop();\n }\n reverse(temp.begin(), temp.end());\n ans.push_back(temp);\n int p = temp.size();\n mnx = min(mnx, p);\n }\n \n TreeNode * rt = new TreeNode(0);\n if(ans.size() == 1){\n return ans[0][ans[0].size()-1];\n }\n bool lb = 0;\n \n \n for(int j=0; j float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n", "solution_js": "/**\n * @param {number[][]} classes\n * @param {number} extraStudents\n * @return {number}\n */\nclass MaxHeap {\n constructor() {\n this.heap = [];\n }\n\n push(value) {\n this.heap.push(value);\n this.heapifyUp(this.heap.length - 1);\n }\n\n pop() {\n if (this.heap.length === 0) {\n return null;\n }\n if (this.heap.length === 1) {\n return this.heap.pop();\n }\n\n const top = this.heap[0];\n this.heap[0] = this.heap.pop();\n this.heapifyDown(0);\n\n return top;\n }\n\n heapifyUp(index) {\n while (index > 0) {\n const parent = Math.floor((index - 1) / 2);\n if (this.heap[parent][0] < this.heap[index][0]) {\n [this.heap[parent], this.heap[index]] = [this.heap[index], this.heap[parent]];\n index = parent;\n } else {\n break;\n }\n }\n }\n\n heapifyDown(index) {\n const n = this.heap.length;\n while (true) {\n let largest = index;\n const left = 2 * index + 1;\n const right = 2 * index + 2;\n\n if (left < n && this.heap[left][0] > this.heap[largest][0]) {\n largest = left;\n }\n if (right < n && this.heap[right][0] > this.heap[largest][0]) {\n largest = right;\n }\n\n if (largest !== index) {\n [this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];\n index = largest;\n } else {\n break;\n }\n }\n }\n\n size() {\n return this.heap.length;\n }\n}\n\nvar maxAverageRatio = function(classes, extraStudents) {\n const n = classes.length;\n\n // Helper function to calculate pass ratio increase\n const passRatioIncrease = (pass, total) => (pass + 1) / (total + 1) - pass / total;\n\n // Initialize max heap to keep track of classes with maximum improvement\n const maxHeap = new MaxHeap();\n\n for (let j = 0; j < n; j++) {\n const [pass, total] = classes[j];\n if (pass !== total) {\n const increase = passRatioIncrease(pass, total);\n maxHeap.push([increase, j]);\n }\n }\n\n let totalPassRatio = 0;\n\n for (let j = 0; j < n; j++) {\n totalPassRatio += classes[j][0] / classes[j][1];\n }\n\n for (let i = 0; i < extraStudents; i++) {\n if (maxHeap.size() === 0) {\n break; // No more classes to consider\n }\n\n const [increase, maxIndex] = maxHeap.pop();\n const [pass, total] = classes[maxIndex];\n const newPass = pass + 1;\n const newTotal = total + 1;\n const newIncrease = passRatioIncrease(newPass, newTotal);\n const newAvg = (totalPassRatio - (pass / total)) + (newPass / newTotal);\n\n if (newAvg <= totalPassRatio) {\n break; // No further improvement possible\n }\n\n totalPassRatio = newAvg;\n classes[maxIndex][0]++;\n classes[maxIndex][1]++;\n maxHeap.push([newIncrease, maxIndex]);\n }\n\n return totalPassRatio / n;\n};", "solution_java": "class Solution {\n public double maxAverageRatio(int[][] classes, int extraStudents) {\n PriorityQueue pq = new PriorityQueue<>(new Comparator(){\n public int compare(double[] a, double[] b){\n double adiff = (a[0]+1)/(a[1]+1) - (a[0]/a[1]);\n double bdiff = (b[0]+1)/(b[1]+1) - (b[0]/b[1]);\n if(adiff==bdiff) return 0;\n return adiff>bdiff? -1:1;\n }\n });\n\n for(int[] c:classes) pq.add(new double[]{c[0],c[1]});\n\n for(int i =0;i a, pair b){\n double ad = (a.first+1)/(double)(a.second+1) - (a.first)/(double)a.second;\n double bd = (b.first+1)/(double)(b.second+1) - (b.first)/(double)b.second;\n return ad < bd;\n }\n};\n\nclass Solution {\npublic:\n double maxAverageRatio(vector>& classes, int extraStudents) {\n double acc = 0;\n priority_queue, vector>, cmp> que;\n for(vector i: classes)\n que.push(make_pair(i[0],i[1]));\n while(extraStudents--){\n pair cur = que.top(); que.pop();\n cur.first++, cur.second++;\n que.push(cur);\n }\n while(!que.empty()){\n pair cur = que.top(); que.pop();\n acc += cur.first / (double) cur.second;\n }\n return acc / (double) classes.size();\n }\n};" }, { "title": "Domino and Tromino Tiling", "algo_input": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.\n\nGiven an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.\n\nIn a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are show above.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\n", "solution_py": "class Solution(object):\n def numTilings(self, n):\n dp = [1, 2, 5] + [0] * n\n for i in range(3, n):\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007\n return dp[n - 1]", "solution_js": "var numTilings = function(n) {\n let mod = 10 ** 9 + 7;\n let len = 4;\n let ways = new Array(len).fill(0);\n\n // base cases\n ways[0] = 1;\n ways[1] = 1;\n ways[2] = 2;\n\n // already calculated above\n if (n < len - 1) {\n return ways[n];\n }\n\n // use % len to circulate values inside our array\n for (var i = len - 1; i <= n;i++) {\n ways[i % len] = (\n ways[(len + i - 1) % len] * 2\n +\n ways[(len + i - 3) % len]\n ) % mod;\n }\n\n return ways[(i - 1) % len];\n};", "solution_java": "class Solution {\n public int numTilings(int n) {\n long[] dp = new long[n + 3]; dp[0] = 1; dp[1] = 2; dp[2] = 5;\n for (int i = 3; i < n; i ++) {\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007;\n }\n return (int)dp[n - 1];\n }\n}", "solution_c": "class Solution {\npublic:\n int numTilings(int n) {\n long dp[n+1];\n dp[0]=1;\n for(int i=1; i<=n; i++){\n if(i<3)\n dp[i]=i;\n else\n dp[i] = (dp[i-1]*2+dp[i-3])%1000000007;\n }\n return (int)dp[n];\n }\n};" }, { "title": "Largest Number At Least Twice of Others", "algo_input": "You are given an integer array nums where the largest integer is unique.\n\nDetermine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.\n\n \nExample 1:\n\nInput: nums = [3,6,1,0]\nOutput: 1\nExplanation: 6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4]\nOutput: -1\nExplanation: 4 is less than twice the value of 3, so we return -1.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 50\n\t0 <= nums[i] <= 100\n\tThe largest element in nums is unique.\n\n", "solution_py": "class Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n if len(nums) is 1:\n return 0\n dom = max(nums)\n i = nums.index(dom)\n nums.remove(dom)\n if max(nums) * 2 <= dom:\n return i\n return -1", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar dominantIndex = function(nums) {\n let first = -Infinity;\n let second = -Infinity;\n let ans = 0;\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] > first) {\n second = first;\n first = nums[i];\n ans = i;\n } else if (nums[i] > second) {\n second = nums[i];\n }\n }\n return first >= second * 2 ? ans : -1;\n};", "solution_java": "class Solution {\n public int dominantIndex(int[] nums) {\n if(nums == null || nums.length == 0){\n return -1;\n }\n \n if(nums.length == 1){\n return 0;\n }\n int max = Integer.MIN_VALUE + 1;\n int secondMax = Integer.MIN_VALUE;\n int index = 0;\n \n for(int i = 0; i < nums.length; i++){\n if(nums[i] > max){\n secondMax = max;\n max = nums[i];\n index = i;\n } else if(nums[i] != max && nums[i] > secondMax){\n secondMax = nums[i];\n }\n }\n if(secondMax * 2 <= max){\n return index;\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int dominantIndex(vector& nums) {\n if(nums.size() < 2){\n return nums.size()-1;\n }\n int max1 = INT_MIN;\n int max2 = INT_MIN;\n int result = -1;\n for(int i=0;i max1){\n result = i;\n max2 = max1;\n max1 = nums[i];\n }else if(nums[i] > max2){\n max2 = nums[i];\n }\n }\n return max1 >= 2*max2 ? result : -1;\n }\n};" }, { "title": "First Letter to Appear Twice", "algo_input": "Given a string s consisting of lowercase English letters, return the first letter to appear twice.\n\nNote:\n\n\n\tA letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.\n\ts will contain at least one letter that appears twice.\n\n\n \nExample 1:\n\nInput: s = \"abccbaacz\"\nOutput: \"c\"\nExplanation:\nThe letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.\n\n\nExample 2:\n\nInput: s = \"abcdd\"\nOutput: \"d\"\nExplanation:\nThe only letter that appears twice is 'd' so we return 'd'.\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 100\n\ts consists of lowercase English letters.\n\ts has at least one repeated letter.\n\n", "solution_py": "class Solution:\n def repeatedCharacter(self, s: str) -> str:\n occurences = defaultdict(int)\n for char in s:\n occurences[char] += 1\n if occurences[char] == 2:\n return char", "solution_js": " var repeatedCharacter = function(s) {\n const m = {};\n \n for(let i of s) {\n if(i in m) {\n m[i]++\n } else {\n m[i] = 1\n }\n \n if(m[i] == 2) {\n return i\n }\n }\n};", "solution_java": "class Solution {\n public char repeatedCharacter(String s) {\n HashSet hset = new HashSet<>();\n for(char ch:s.toCharArray())\n {\n if(hset.contains(ch))\n return ch;\n else\n hset.add(ch);\n }\n return ' ';\n }\n}", "solution_c": "class Solution\n{\npublic:\n char repeatedCharacter(string s)\n {\n unordered_map mp; //for storing occurrences of char\n\n char ans;\n for(auto it:s)\n {\n if(mp.find(it) != mp.end()) //any char which comes twice first will be the ans;\n {\n ans = it;\n break;\n }\n mp[it]++; //increase the count of char\n }\n return ans;\n }\n};" }, { "title": "Check If It Is a Good Array", "algo_input": "Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.\n\nReturn True if the array is good otherwise return False.\n\n \nExample 1:\n\nInput: nums = [12,5,7,23]\nOutput: true\nExplanation: Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1\n\n\nExample 2:\n\nInput: nums = [29,6,10]\nOutput: true\nExplanation: Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1\n\n\nExample 3:\n\nInput: nums = [3,6]\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 10^5\n\t1 <= nums[i] <= 10^9\n\n", "solution_py": "class Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n def gcd(a,b):\n while a:\n a, b = b%a, a\n return b\n return reduce(gcd,nums)==1", "solution_js": "var isGoodArray = function(nums) {\n let gcd = nums[0]\n\n for(let n of nums){while(n){[gcd, n] = [n, gcd % n]}}\n\n return (gcd === 1)\n};", "solution_java": "class Solution {\n public boolean isGoodArray(int[] nums) {\n int gcd = nums[0];\n for(int i =1; i& nums) {\n int gcd=0;\n for(int i=0; i List[int]:\n\n ## Basic information: height and width of board\n h, w = len(board), len(board[0])\n\n # ----------------------------------------------------------------------------\n\n # Use pathon native cahce as memoization for DP\n @cache\n def visit(i, j):\n\n if i == h-1 and j == w-1:\n ## Base case:\n\n # score for start coordinate = 0\n # paht count for start coordinate = 1\n return 0, 1\n\n elif i >= w or j >= h or board[i][j] == 'X':\n\n ## Base case:\n # Out-of-boundary, or meet obstacle\n return 0, 0\n\n ## General case:\n # update from three possible preivous moves from right, down, and diagonal\n\n right_score, right_path_count = visit(i, j+1)\n down_score, down_path_count = visit(i+1, j)\n diag_score, diag_path_count = visit(i+1, j+1)\n\n max_prevScore = max(right_score, down_score, diag_score)\n\n cur_path_count = 0\n cur_score = int(board[i][j]) if board[i][j] != \"E\" else 0\n\n if right_score == max_prevScore : cur_path_count += right_path_count\n if down_score == max_prevScore : cur_path_count += down_path_count\n if diag_score == max_prevScore : cur_path_count += diag_path_count\n\n return max_prevScore + cur_score, cur_path_count\n # ----------------------------------------------------------------------------\n\n ## Remark: Remember to take modulo by constant, this is defined by description\n CONST = 10**9 + 7\n maxScore, validPathCount = visit(0, 0)\n\n return [maxScore % CONST, validPathCount % CONST] if validPathCount else [0, 0]", "solution_js": "var pathsWithMaxScore = function(board) {\n let n = board.length, dp = Array(n + 1).fill(0).map(() => Array(n + 1).fill(0).map(() => [-Infinity, 0]));\n let mod = 10 ** 9 + 7;\n dp[n - 1][n - 1] = [0, 1]; // [max score, number of paths]\n\n for (let i = n - 1; i >= 0; i--) {\n for (let j = n - 1; j >= 0; j--) {\n if (board[i][j] === 'X' || board[i][j] === 'S') continue;\n\n let paths = [dp[i][j + 1], dp[i + 1][j + 1], dp[i + 1][j]];\n for (let [maxScore, numPaths] of paths) {\n if (dp[i][j][0] < maxScore) {\n dp[i][j] = [maxScore, numPaths];\n } else if (dp[i][j][0] === maxScore) {\n dp[i][j][1] = (dp[i][j][1] + numPaths) % mod;\n }\n }\n let score = board[i][j] === 'E' ? 0 : Number(board[i][j]);\n dp[i][j][0] += score;\n }\n }\n return dp[0][0][1] === 0 ? [0, 0] : dp[0][0];\n};", "solution_java": "class Solution {\n public int[] pathsWithMaxScore(List board) {\n int M = (int)1e9+7;\n int m = board.size();\n int n = board.get(0).length();\n int[][] dp = new int[m][n];\n int[][] ways = new int[m][n];\n ways[0][0]=1; // base case.\n int[][] dirs = {{-1, 0}, {0, -1}, {-1, -1}}; // all 3 ways where we can travel.\n for (int i=0;idp[i][j]){\n dp[i][j]=cur+dp[x][y];\n ways[i][j]=0;\n }\n if (cur+dp[x][y]==dp[i][j]){\n ways[i][j]+=ways[x][y];\n ways[i][j]%=M;\n }\n }\n }\n }\n return new int[]{dp[m-1][n-1], ways[m-1][n-1]};\n }\n}", "solution_c": "class Solution {\npublic:\n int mod=1e9+7;\n map,pair>h;\n pairsolve(vector&board,int i,int j,int n,int m)\n {\n //base case if you reach top left then 1 path hence return 1\n if(i==0 && j==0)return {0,1};\n //return 0 as no path is detected\n if(i<0 || j<0 || i>=n || j>=m || board[i][j]=='X')return {INT_MIN,0};\n //check if it is stored or not\n if(h.find({i,j})!=h.end())return h[{i,j}];\n int no=0,cnt=0;\n if(board[i][j]!='S')no=board[i][j]-'0';\n //top ,left ,top left\n auto a=solve(board,i-1,j,n,m);\n auto b=solve(board,i,j-1,n,m);\n auto c=solve(board,i-1,j-1,n,m);\n //maxi ans\n int curr=(max(a.first,max(b.first,c.first)))%mod;\n //if maxi ans == a , b , c then increament count of a ,b,c\n if(curr==a.first)cnt+=a.second;\n if(curr==b.first)cnt+=b.second;\n if(curr==c.first)cnt+=c.second;\n return h[{i,j}]={(curr+no)%mod,cnt%mod};\n }\n vector pathsWithMaxScore(vector& board) {\n auto ans=solve(board,board.size()-1,board[0].size()-1,board.size(),board[0].size());\n if(ans.first<0)return {0,0};\n return {ans.first%mod,ans.second%mod};\n }\n};" }, { "title": "Path with Maximum Probability", "algo_input": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].\n\nGiven two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.\n\nIf there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.\n\n \nExample 1:\n\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput: 0.25000\nExplanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\n\n\nExample 2:\n\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput: 0.30000\n\n\nExample 3:\n\n\n\nInput: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput: 0.00000\nExplanation: There is no path between 0 and 2.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 10^4\n\t0 <= start, end < n\n\tstart != end\n\t0 <= a, b < n\n\ta != b\n\t0 <= succProb.length == edges.length <= 2*10^4\n\t0 <= succProb[i] <= 1\n\tThere is at most one edge between every two nodes.\n\n", "solution_py": "class Solution(object):\n def maxProbability(self, n, edges, succProb, start, end):\n adj=[[] for i in range(n)]\n dist=[sys.maxsize for i in range(n)]\n heap=[]\n c=0\n for i,j in edges:\n adj[i].append([j,succProb[c]])\n adj[j].append([i,succProb[c]])\n c+=1\n heapq.heappush(heap,[-1.0,start])\n dist[start]=1\n while(heap):\n prob,u=heapq.heappop(heap)\n for v,w in adj[u]:\n if(dist[v]>-abs(w*prob)):\n dist[v]=-abs(w*prob)\n heapq.heappush(heap,[dist[v],v])\n if(sys.maxsize==dist[end]):\n return 0.00000\n else:\n return -dist[end]", "solution_js": "var maxProbability = function(n, edges, succProb, start, end) {\n const graph = new Map();\n edges.forEach(([a, b], i) => {\n const aSet = graph.get(a) || [];\n const bSet = graph.get(b) || [];\n aSet.push([b, succProb[i]]), bSet.push([a, succProb[i]]);\n graph.set(a, aSet), graph.set(b, bSet);\n });\n \n const dist = new Array(n).fill(0);\n const vis = new Array(n).fill(false);\n \n dist[start] = 1;\n \n const getMaxProbNode = () => {\n let maxVal = 0, maxIndex = -1;\n for(let i = 0; i < n; i++) {\n if(maxVal < dist[i] && !vis[i]) {\n maxVal = dist[i], maxIndex = i;\n }\n }\n return maxIndex;\n }\n \n for(let i = 0; i < n - 1; i++) {\n const maxProbNode = getMaxProbNode();\n vis[maxProbNode] = true;\n \n const adjacentNodes = graph.get(maxProbNode) || [];\n const len = adjacentNodes.length;\n for(let j = 0; j < len; j++) {\n const [node, prob] = adjacentNodes[j];\n if(!vis[node] && dist[node] < dist[maxProbNode] * prob) {\n dist[node] = dist[maxProbNode] * prob;\n }\n }\n }\n \n return dist[end];\n};", "solution_java": "class Pair{\n int to;\n double prob;\n public Pair(int to,double prob){\n this.to=to;\n this.prob=prob;\n }\n}\nclass Solution {\n public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {\n List> adj=new ArrayList<>();\n for(int i=0;i());\n }\n for(int i=0;i pq=new PriorityQueue<>((p1,p2)->Double.compare(p2.prob,p1.prob));\n pq.offer(new Pair(start,1.0));\n while(!pq.isEmpty()){\n Pair curr=pq.poll();\n for(Pair x:adj.get(curr.to)){\n if(((curr.prob)*(x.prob))>probs[x.to]){\n probs[x.to]=((curr.prob)*(x.prob));\n pq.offer(new Pair(x.to,probs[x.to]));\n\n }\n else{\n continue;\n }\n }\n }\n return probs[end];\n }\n}", "solution_c": "class Solution {\npublic:\n double maxProbability(int n, vector>& edges, vector& succProb, int start, int end) {\n vector>> graph(n);\n for(int i = 0; i < edges.size(); ++i){\n graph[edges[i][0]].push_back({edges[i][1], succProb[i]});\n graph[edges[i][1]].push_back({edges[i][0], succProb[i]});\n }\n priority_queue> pq;\n pq.push({1.0, start});\n vector visited(n, false);\n vector values(n, 0.0);\n values[start] = 1.0;\n while(!pq.empty()){\n double currValue = pq.top().first, currNode = pq.top().second;\n pq.pop();\n visited[currNode] = true;\n for(int i = 0; i < graph[currNode].size(); ++i){\n double weight = graph[currNode][i].second;\n int nextNode = graph[currNode][i].first;\n if(visited[nextNode] == false){\n double nextProb = currValue * weight;\n if(nextProb > values[nextNode])\n values[nextNode] = nextProb;\n pq.push({nextProb, nextNode});\n }\n }\n }\n return values[end] == 0.0 ? 0.0 : values[end];\n }\n};" }, { "title": "Array Partition", "algo_input": "Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.\n\n \nExample 1:\n\nInput: nums = [1,4,3,2]\nOutput: 4\nExplanation: All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.\n\nExample 2:\n\nInput: nums = [6,2,6,5,1,2]\nOutput: 9\nExplanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\tnums.length == 2 * n\n\t-104 <= nums[i] <= 104\n\n", "solution_py": "class Solution(object):\n def arrayPairSum(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n \n nums = sorted(nums)\n \n summ = 0\n for i in range(0,len(nums),2):\n summ += min(nums[i],nums[i+1])\n return summ", "solution_js": "var arrayPairSum = function(nums) {\n nums.sort((a, b) => a - b);\n let total = 0;\n for (let i = 0; i < nums.length; i += 2) {\n total += Math.min(nums[i], nums[i + 1]);\n }\n return total;\n};", "solution_java": "class Solution {\n public int arrayPairSum(int[] nums) {\n Arrays.sort(nums);\n int sum = 0;\n for(int i = 0; i < nums.length; i+=2){\n sum += nums[i];\n }\n return sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int arrayPairSum(vector& nums) {\n int res=0;\n sort(nums.begin(),nums.end());\n for(int i=0;i List[List[int]]:\n if numRows == 1:\n return [[1]]\n if numRows == 2:\n return [[1], [1, 1]]\n ans = [[1], [1, 1]]\n for x in range(1, numRows - 1):\n tmp = [1]\n for k in range(len(ans[x]) - 1):\n tmp.append(ans[x][k] + ans[x][k + 1])\n tmp.append(1)\n ans.append(tmp)\n return ans", "solution_js": "var generate = function(numRows) {\n let ans = new Array(numRows)\n for (let i = 0; i < numRows; i++) {\n let row = new Uint32Array(i+1).fill(1),\n mid = i >> 1\n for (let j = 1; j <= mid; j++) {\n let val = ans[i-1][j-1] + ans[i-1][j]\n row[j] = val, row[row.length-j-1] = val\n }\n ans[i] = row\n }\n return ans\n};", "solution_java": "class Solution {\n public List> generate(int numRows) {\n List> list = new LinkedList();\n list.add(Arrays.asList(1));\n if(numRows == 1) return list;\n list.add(Arrays.asList(1,1));\n \n for(int i = 1; i < numRows - 1; i++) {\n List temp = list.get(i);\n List temp2 = new ArrayList();\n temp2.add(1);\n for(int j = 0; j < temp.size() - 1; j++) {\n temp2.add(temp.get(j) + temp.get(j+1));\n }\n temp2.add(1);\n list.add(temp2);\n }\n \n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> generate(int numRows) {\n vector> ans(numRows, vector());\n for(int i = 0; i int:\n nums = []\n curr = head\n while curr:\n nums.append(curr.val)\n curr = curr.next\n\n N = len(nums)\n res = 0\n for i in range(N // 2):\n res = max(res, nums[i] + nums[N - i - 1])\n return res", "solution_js": "var pairSum = function(head) {\n const arr = [];\n let max = 0;\n \n while (head) {\n arr.push(head.val);\n head = head.next;\n }\n \n for (let i = 0; i < arr.length / 2; i++) {\n const sum = arr[i] + arr[arr.length - 1 - i]\n max = Math.max(max, sum);\n }\n \n return max;\n};", "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int pairSum(ListNode head) {\n if (head == null) {\n return 0;\n }\n if (head.next == null) {\n return head.val;\n }\n ListNode slow = head;\n ListNode fast = head;\n while (fast != null && fast.next != null) {\n slow = slow.next;\n fast = fast.next.next;\n }\n slow = reverse(slow);\n fast = head;\n int sum = Integer.MIN_VALUE;\n while (slow != null) {\n sum = Math.max(slow.val + fast.val, sum);\n slow = slow.next;\n fast = fast.next;\n }\n return sum;\n }\n \n public ListNode reverse(ListNode node) {\n if (node == null) {\n return null;\n }\n ListNode current = node;\n ListNode previous = null;\n while (current != null) {\n ListNode next = current.next;\n current.next = previous;\n previous = current;\n current = next;\n }\n return previous;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* reverse(ListNode* head){\n ListNode* prev=NULL,*curr=head,*nextstop;\n while(curr){\n nextstop=curr->next;\n curr->next=prev;\n prev=curr;\n curr=nextstop;\n }\n return prev;\n }\n \n ListNode* findMiddleNode(ListNode* head){\n ListNode* slowptr=head,*fastptr=head->next;\n while(fastptr&&fastptr->next){\n slowptr=slowptr->next;\n fastptr=fastptr->next->next;\n }\n return slowptr;\n }\n \n int pairSum(ListNode* head) {\n int ans=0;\n \n ListNode* midNode=findMiddleNode(head);\n ListNode* head2=reverse(midNode->next);\n \n midNode->next=NULL;\n \n \n ListNode* p1=head,*p2=head2;\n while(p1&&p2){\n ans=max(ans,p1->val+p2->val);\n p1=p1->next;\n p2=p2->next;\n }\n \n midNode->next=reverse(head2);\n \n return ans;\n }\n};" }, { "title": "Check if There is a Valid Path in a Grid", "algo_input": "You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:\n\n\n\t1 which means a street connecting the left cell and the right cell.\n\t2 which means a street connecting the upper cell and the lower cell.\n\t3 which means a street connecting the left cell and the lower cell.\n\t4 which means a street connecting the right cell and the lower cell.\n\t5 which means a street connecting the left cell and the upper cell.\n\t6 which means a street connecting the right cell and the upper cell.\n\n\nYou will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.\n\nNotice that you are not allowed to change any street.\n\nReturn true if there is a valid path in the grid or false otherwise.\n\n \nExample 1:\n\nInput: grid = [[2,4,3],[6,5,2]]\nOutput: true\nExplanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\n\n\nExample 2:\n\nInput: grid = [[1,2,1],[1,2,1]]\nOutput: false\nExplanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\n\n\nExample 3:\n\nInput: grid = [[1,1,2]]\nOutput: false\nExplanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 300\n\t1 <= grid[i][j] <= 6\n\n", "solution_py": "class Solution:\n def hasValidPath(self, grid: List[List[int]]) -> bool:\n r,c=len(grid),len(grid[0])\n dic={\n 2:[(-1,0),(1,0)],\n 1:[(0,1),(0,-1)],\n 5:[(-1,0),(0,-1)],\n 3:[(1,0),(0,-1)],\n 6:[(0,1),(-1,0)],\n 4:[(0,1),(1,0)]\n \n }\n q=collections.deque([(0,0)])\n visit=set()\n while q:\n i,j=q.popleft()\n visit.add((i,j))\n if i==r-1 and j==c-1:\n return True\n for x,y in dic[grid[i][j]]:\n nx=i+x\n ny=j+y\n if nx>=0 and nx=0 and ny new Uint16Array(grid[0].length))\n\tlet y = 0, x = 0;\n\n\tfunction getNextSegment(segment, y, x) {\n\t\tlet dir = 0;\n\t\tlet ny = y + SEGMENTS[segment].dirs[dir][0];\n\t\tlet nx = x + SEGMENTS[segment].dirs[dir][1];\n\t\tif (ny < 0 || ny >= M || nx < 0 || nx >= N || path[ny][nx]) {\n\t\t\tdir = 1;\n\t\t\tny = y + SEGMENTS[segment].dirs[dir][0];\n\t\t\tnx = x + SEGMENTS[segment].dirs[dir][1];\n\t\t}\n\t\treturn {dir, ny, nx}\n\t}\n\n\tfunction isValid(y, x) {\n\t\tfor (let i = 0; i < M*N; i++) {\n\t\t\tif (y == M-1 && x == N-1) return true;\n\t\t\tpath[y][x] = i+1;\n\t\t\tlet cur = grid[y][x];\n\t\t\tlet next = getNextSegment(cur, y, x);\n\t\t\tif (next.ny >= M || next.nx >= N) return false;\n\t\t\tif (!SEGMENTS[cur].adjs[next.dir].includes(grid[next.ny][next.nx])) return false;\n\t\t\ty = next.ny;\n\t\t\tx = next.nx;\n\t\t}\n\t\treturn false\n\t}\n\n\tif (grid[0][0] !== 4) return isValid(y, x);\n\tpath[0][0] = 1;\n\treturn isValid(y, x+1) || isValid(y+1, x);\n};", "solution_java": "class Solution {\n public boolean hasValidPath(int[][] grid) {\n int m=grid.length, n=grid[0].length;\n int[][] visited=new int[m][n];\n return dfs(grid, 0, 0, m, n, visited);\n }\n public boolean dfs(int[][] grid, int i, int j, int m, int n, int[][] visited){\n if(i==m-1 && j==n-1) return true;\n if(i<0 || i>=m || j<0 || j>=n || visited[i][j]==1) return false;\n visited[i][j]=1;\n if(grid[i][j]==1){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (j0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else if(grid[i][j]==3){\n if( (j>0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i0 && (grid[i][j-1]==1 || grid[i][j-1]==4 || grid[i][j-1]==6) && dfs(grid, i, j-1, m, n, visited)) || \n\t\t\t (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited))) return true;\n }else{\n if( (i>0 && (grid[i-1][j]==2 || grid[i-1][j]==3 || grid[i-1][j]==4) && dfs(grid, i-1, j, m, n, visited)) || \n\t\t\t (j>& grid) \n {\n int m = grid.size();\n int n = grid[0].size();\n if(m==1 and n==1) return true;\n // 2D - direction vector for all streets\n // 0th based indexing 0 to 11\n \n // Let grid value g[i][j] = 4, means we need to follow \"street-4\" direction\n // First index of street-4 direction = 2*(4-1) = 6\n // Second index of street-4 direction = 2*(4-1)+1 = 7\n // dir[6] = {0, 1}\n // dir[7] = {1, 0}\n vector>dir = { // Indices \n {0,-1}, {0, 1}, // street 1 --> 0 1\n {-1,0}, {1, 0}, // street 2 --> 2 3\n {0,-1}, {1, 0}, // street 3 --> 4 5\n {0, 1}, {1, 0}, // street 4 --> 6 7\n {0,-1}, {-1,0}, // street 5 --> 8 9 \n {0, 1}, {-1,0} // street 6 --> 10 11\n };\n\n vector>vis(m, vector(n, false));\n queue>q;\n \n q.push({0, 0});\n vis[0][0] = true;\n \n while (!q.empty()) \n {\n auto cur = q.front(); q.pop();\n\n int r = cur.first;\n int c = cur.second;\n int val = grid[r][c] - 1; // grid values 1 to 6\n \n if(r==m-1 and c==n-1) return true;\n \n // 2 directions from every cell\n for(int k=0;k<2;k++) // k = 0, k = 1\n {\n int idx = 2*val+k; // get index\n int nr = r + dir[idx][0];\n int nc = c + dir[idx][1];\n if (nr < 0 or nr >= m or nc < 0 or nc >= n or vis[nr][nc]==true) continue;\n \n // for checking the back direction matches with current cell i.e forming path to next cell\n for(int x=0;x<2;x++)\n {\n int i = 2*(grid[nr][nc]-1)+x; // get index\n if(r == nr+dir[i][0] and c == nc+dir[i][1]){\n vis[nr][nc] = true;\n q.push({nr, nc});\n } \n }\n }\n }\n return false;\n }\n};" }, { "title": "Lemonade Change", "algo_input": "At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.\n\nNote that you do not have any change in hand at first.\n\nGiven an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.\n\n \nExample 1:\n\nInput: bills = [5,5,5,10,20]\nOutput: true\nExplanation: \nFrom the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.\n\n\nExample 2:\n\nInput: bills = [5,5,10,10,20]\nOutput: false\nExplanation: \nFrom the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.\n\n\n \nConstraints:\n\n\n\t1 <= bills.length <= 105\n\tbills[i] is either 5, 10, or 20.\n\n", "solution_py": "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n\n change = {5:0,10:0}\n for i in bills:\n if i==5:\n change[5]+=1\n elif i==10:\n if change[5]>0:\n change[5]-=1\n change[10]+=1\n else:\n return False\n else:\n if (change[10]>0) & (change[5]>0):\n change[10]-=1\n change[5]-=1\n elif change[5]>=3:\n change[5]-=3\n else:\n return False\n return True", "solution_js": " * @param {number[]} bills\n * @return {boolean}\n */\nvar lemonadeChange = function(bills) {\n let cashLocker = {\n \"5\": 0,\n \"10\": 0,\n \n }\n for (let i = 0; i < bills.length; i++) {\n if (bills[i] === 5) {\n cashLocker[\"5\"] += 1;\n } else if (bills[i] === 10 && cashLocker[\"5\"] > 0) {\n cashLocker[\"5\"] -= 1;\n cashLocker[\"10\"] += 1;\n\n } else if (bills[i] === 20 && cashLocker[\"5\"] >= 1 && cashLocker[\"10\"] >= 1) {\n cashLocker[\"5\"] -= 1;\n cashLocker[\"10\"] -= 1;\n \n } else if (bills[i] === 20 && cashLocker[\"5\"] >= 3) {\n\n cashLocker[\"5\"] -= 3;\n \n } else {\n return false;\n }\n }\n\n return true;\n \n};", "solution_java": "class Solution {\n public boolean lemonadeChange(int[] bills) {\n int count5 = 0, count10 = 0;\n for(int p : bills){\n if(p == 5){\n count5++;\n }\n else if(p == 10){\n if(count5 > 0){\n count5--;\n count10++;\n }\n else{\n return false;\n }\n }\n else if(p == 20){\n if(count5 > 0 && count10 > 0){\n count5--;\n count10--;\n }\n else if(count5 == 0){\n return false;\n }\n else if(count5<3){\n return false;\n }\n else{\n count5 -= 3;\n }\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool lemonadeChange(vector& bills) {\n unordered_map m;\n \n int change = 0;\n for(int i = 0 ; i < bills.size(); i++)\n {\n m[bills[i]]++;\n \n if(bills[i] > 5)\n {\n change = bills[i] - 5;\n \n if(change == 5)\n {\n if(m[5] > 0)\n {\n m[5]--;\n }\n else\n {\n return false;\n }\n }\n //change = 10\n else\n {\n if(m[10] > 0 and m[5] > 0)\n {\n m[10]--;\n m[5]--;\n }\n else if(m[5] >= 3)\n {\n m[5] -= 3;\n }\n else\n {\n return false;\n }\n }\n }\n }\n \n return true;\n }\n};" }, { "title": "Jump Game II", "algo_input": "Given an array of non-negative integers nums, you are initially positioned at the first index of the array.\n\nEach element in the array represents your maximum jump length at that position.\n\nYour goal is to reach the last index in the minimum number of jumps.\n\nYou can assume that you can always reach the last index.\n\n \nExample 1:\n\nInput: nums = [2,3,1,1,4]\nOutput: 2\nExplanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\nInput: nums = [2,3,0,1,4]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t0 <= nums[i] <= 1000\n\n", "solution_py": "class Solution(object):\n def jump(self, nums):\n ans = l = r = 0\n\n while r < len(nums) - 1:\n farthestJump = 0\n\n for i in range(l, r + 1):\n farthestJump = max(farthestJump, i + nums[i])\n\n l = r + 1\n r = farthestJump\n ans += 1\n\n return ans", "solution_js": "**//Time Complexity : O(n), Space Complexity: O(1)**\nvar jump = function(nums) {\n var jump = 0;\n var prev = 0;\n var max = 0;\n for (var i = 0; i < nums.length - 1; i++) {\n // Keep track of the maximum jump\n max = Math.max(max, i + nums[i]);\n // When we get to the index where we had our previous maximum jump, we increase our jump...\n if (i === prev) {\n jump++;\n prev = max;\n }\n }\n return jump;\n};", "solution_java": "class Solution {\n\n public int jump(int[] nums) {\n\n int result = 0;\n\n int L = 0;\n int R = 0;\n\n while (R < nums.length - 1) {\n\n int localMaxRight = 0;\n\n for (int i=L; i<=R; i++) {\n\n localMaxRight = Math.max(i + nums[i], localMaxRight);\n }\n\n L = R + 1;\n R = localMaxRight;\n result++;\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int jump(vector& nums) {\n int step=0, jump_now;\n int ans = 0, index=0, i, mx;\n if(nums.size()==1) return ans;\n while(index+step=nums.size()-1) break;\n mx = 0;\n for(i=1; i<=step; i++){\n if(i+nums[index+i]>mx){\n mx = i+nums[index+i];\n jump_now = i;\n }\n }\n step = 0;\n index += jump_now;\n }\n return ans;\n }\n};" }, { "title": "Final Value of Variable After Performing Operations", "algo_input": "There is a programming language with only four operations and one variable X:\n\n\n\t++X and X++ increments the value of the variable X by 1.\n\t--X and X-- decrements the value of the variable X by 1.\n\n\nInitially, the value of X is 0.\n\nGiven an array of strings operations containing a list of operations, return the final value of X after performing all the operations.\n\n \nExample 1:\n\nInput: operations = [\"--X\",\"X++\",\"X++\"]\nOutput: 1\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X = 0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n\n\nExample 2:\n\nInput: operations = [\"++X\",\"++X\",\"X++\"]\nOutput: 3\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.\n\n\nExample 3:\n\nInput: operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\nOutput: 0\nExplanation: The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.\n\n\n \nConstraints:\n\n\n\t1 <= operations.length <= 100\n\toperations[i] will be either \"++X\", \"X++\", \"--X\", or \"X--\".\n\n", "solution_py": "class Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n x = 0\n for o in operations:\n if '+' in o:\n x += 1\n else:\n x -= 1\n return x", "solution_js": "var finalValueAfterOperations = function(operations) {\n let count = 0;\n for(let i of operations) {\n if(i === 'X++' || i === '++X') count++;\n else count--;\n }\n return count;\n};", "solution_java": "class Solution {\n public int finalValueAfterOperations(String[] operations) {\n int val = 0;\n for(int i = 0; i& o,int c=0) {\n for(auto &i:o) if(i==\"++X\" or i==\"X++\") c++; else c--;\n return c;\n }\n};" }, { "title": "Minimum Difference Between Largest and Smallest Value in Three Moves", "algo_input": "You are given an integer array nums. In one move, you can choose one element of nums and change it by any value.\n\nReturn the minimum difference between the largest and smallest value of nums after performing at most three moves.\n\n \nExample 1:\n\nInput: nums = [5,3,2,4]\nOutput: 0\nExplanation: Change the array [5,3,2,4] to [2,2,2,2].\nThe difference between the maximum and minimum is 2-2 = 0.\n\n\nExample 2:\n\nInput: nums = [1,5,0,10,14]\nOutput: 1\nExplanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. \nThe difference between the maximum and minimum is 1-0 = 1.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def minDifference(self, nums: List[int]) -> int:\n if len(nums) <= 3:\n return 0\n\n nums.sort()\n t1 = nums[-1] - nums[3]\n t2 = nums[-4] - nums[0]\n t3 = nums[-2] - nums[2]\n t4 = nums[-3] - nums[1]\n\n return min(t1,t2,t3,t4)", "solution_js": "var minDifference = function(nums) {\n let len = nums.length;\n if (len < 5) return 0;\n\n nums.sort((a,b) => a-b)\n \n return Math.min(\n \n ( nums[len-1] - nums[3] ), // 3 elements removed from start 0 from end\n ( nums[len-4] - nums[0] ), // 3 elements removed from end 0 from start\n ( nums[len-2] - nums[2] ), // 2 elements removed from start 1 from end\n ( nums[len-3] - nums[1] ), // 2 elements removed from end 1 from start\n \n\n)\n \n \n \n \n};", "solution_java": "class Solution {\n public int minDifference(int[] nums) {\n // sort the nums\n // to gain the mini difference\n // we want to remove the three smallest or biggest \n // 0 - 3\n // 1 - 2\n // 2 - 1\n // 3 - 0\n if(nums.length <= 4){\n return 0;\n }\n \n Arrays.sort(nums);\n \n int left = 0, right = 3;\n \n int res = Integer.MAX_VALUE;\n while(left <= 3){\n int mini = nums[left];\n int max = nums[nums.length - right - 1];\n res = Math.min(res, max - mini);\n \n left++;\n right--;\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int minDifference(vector& nums) {\n\n int n =nums.size();\n\n sort( nums.begin(), nums.end());\n\n if( n<5){\n return 0;\n\n }\n else return min({nums[n-4]- nums[0],nums[n-3]- nums[1] ,nums[n-2]-nums[2], nums[n-1]-nums[3]});\n\n }\n};" }, { "title": "Maximum Nesting Depth of Two Valid Parentheses Strings", "algo_input": "A string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and:\n\n\n\tIt is the empty string, or\n\tIt can be written as AB (A concatenated with B), where A and B are VPS's, or\n\tIt can be written as (A), where A is a VPS.\n\n\nWe can similarly define the nesting depth depth(S) of any VPS S as follows:\n\n\n\tdepth(\"\") = 0\n\tdepth(A + B) = max(depth(A), depth(B)), where A and B are VPS's\n\tdepth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\n\n\nFor example,  \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n\n \n\nGiven a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).\n\nNow choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.\n\nReturn an answer array (of length seq.length) that encodes such a choice of A and B:  answer[i] = 0 if seq[i] is part of A, else answer[i] = 1.  Note that even though multiple answers may exist, you may return any of them.\n\n \nExample 1:\n\nInput: seq = \"(()())\"\nOutput: [0,1,1,1,1,0]\n\n\nExample 2:\n\nInput: seq = \"()(())()\"\nOutput: [0,0,0,1,1,0,1,1]\n\n\n \nConstraints:\n\n\n\t1 <= seq.size <= 10000\n\n", "solution_py": "class Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans = []\n last = 1\n for i in seq:\n if i == '(':\n if last == 0: ans.append(1)\n else:ans.append(0)\n else:\n ans.append(last)\n last = (last + 1) % 2\n return ans", "solution_js": "/**\n * @param {string} seq\n * @return {number[]}\n */\nvar maxDepthAfterSplit = function(seq) {\n let arr = []\n for(let i=0; i maxDepthAfterSplit(string seq) {\n //since we want the difference to be as low as possible so we will try to balance both A and B by trying to maintain the number of paranthesis as close as close as possible\n vector indexA, indexB, res(seq.length(), 0 );\n\t\t//initailly assuming all parenthesis belong to A so filling res with 0\n int i = 0;\n int addToA = 0, addToB = 0;\n while(i < seq.length()){\n if(seq[i] == '('){\n if(addToA <= addToB){\n //adding depth to A when it's depth is lesser or equal to b\n indexA.push_back(i);\n addToA ++;\n }else{\n indexB.push_back(i);\n addToB++;\n }\n }else{\n // removing depth from string whose depth is maximum as we have to keep the difference minimum\n if(addToA >= addToB){\n addToA--;\n indexA.push_back(i);\n }else{\n indexB.push_back(i);\n addToB--;\n }\n }\n i++;\n }\n for(i = 0; i < indexB.size(); i++){\n res[indexB[i]] = 1;\n }\n return res; \n }\n};" }, { "title": "Find Two Non-overlapping Sub-arrays Each With Target Sum", "algo_input": "You are given an array of integers arr and an integer target.\n\nYou have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.\n\nReturn the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.\n\n \nExample 1:\n\nInput: arr = [3,2,2,4,3], target = 3\nOutput: 2\nExplanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\n\n\nExample 2:\n\nInput: arr = [7,3,4,7], target = 7\nOutput: 2\nExplanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\n\n\nExample 3:\n\nInput: arr = [4,3,2,6,2,3,4], target = 6\nOutput: -1\nExplanation: We have only one sub-array of sum = 6.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t1 <= arr[i] <= 1000\n\t1 <= target <= 108\n\n", "solution_py": "class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float('inf')\n min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer and index of num in arr\n windowSum += num\n while windowSum > target: \n\t\t\t# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target\n windowSum -= arr[l]\n l += 1\n\t\t\t# the case when we found a new target sub-array, i.e. current window\n if windowSum == target:\n\t\t\t # length of current window\n curLen = r - l + 1\n\t\t\t\t# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window: \n\t\t\t\t# avoid overlap with cur window\n\t\t\t\t# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping\n\t\t\t\t# , if < res, update res.\n res = min(res, curLen + min_till[l - 1])\n\t\t\t\t# Everytime we found a target window, update the min_till of current right end of the window, \n\t\t\t\t# for future use when sum up to new length of sum_of_two_subarray and update the res.\n min_till[r] = min(curLen, min_till[r - 1])\n else:\n\t\t\t# If windowSum < target: window with current arr[r] as right end does not have any target subarry, \n\t\t\t# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1. \n min_till[r] = min_till[r - 1]\n return res if res < float('inf') else -1\n\t\nTime = O(n): when sliding the window, left and right pointers traverse the array once.\nSpace = O(n): we use one additional list min_till[] to record min length of target subarray till index i.", "solution_js": "var minSumOfLengths = function(arr, target) {\n let left=0;\n let curr=0;\n let res=Math.min(); // Math.min() without any args will be Infinite\n const best=new Array(arr.length).fill(Math.min());\n let bestSoFar=Math.min()\n\n for(let i=0;itarget){\n curr-=arr[left++]\n }\n if(curr===target){\n if(left>0&&best[left-1]!==Math.min()){\n res=Math.min(res,best[left-1]+i-left+1)\n }\n bestSoFar=Math.min(bestSoFar,i-left+1)\n }\n best[i]=bestSoFar;\n }\n return res===Math.min()?-1:res\n};", "solution_java": "class Solution {\n public int minSumOfLengths(int[] arr, int target) { //this fits the case when there's negative number, kind like 560\n if (arr == null || arr.length == 0) return 0;\n Map map = new HashMap<>(); //sum - index\n map.put(0, -1);\n int sum = 0;\n for (int i = 0; i < arr.length; i++) { //record preSum and index\n sum += arr[i];\n map.put(sum, i);\n }\n sum = 0;\n int size = arr.length + 1, res = arr.length + 1;//note if we set size as MAX_VALUE the line 16 may overflow\n for (int i = 0; i < arr.length; i++) {\n sum += arr[i];\n if (map.containsKey(sum - target)) size = Math.min(size, i - map.get(sum - target)); //find the subarray from the previous index to current one\n if (map.containsKey(sum + target)) res = Math.min(res, size + map.get(sum + target) - i); //from the current index to next one, this avoid overlap\n }\n return res == arr.length + 1 ? -1 : res;\n }\n}", "solution_c": "class Solution {\npublic:\n int minSumOfLengths(vector& arr, int target) {\n int n=arr.size();\n vector prefix(n,INT_MAX);\n vector suffix(n,INT_MAX);\n int sum=0;\n int start=0;\n for(int end=0;endtarget){\n sum-=arr[start++];\n }\n if(sum==target){\n prefix[end]=min(prefix[end-1>=0 ? end-1 : 0],end-start+1);\n }\n else{\n prefix[end]=prefix[end-1>=0 ? end-1 : 0];\n }\n }\n\n sum=0;\n start=n-1;\n for(int end=n-1;end>=0;end--){\n sum+=arr[end];\n while(sum>target){\n sum-=arr[start--];\n }\n if(sum==target){\n suffix[end]=min(suffix[end+1r2:\n self.parentof[p2] = p1\n else:\n self.parentof[p1]=p2\n if r1==r2: self.rankof[p2]+=1\n\nclass Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n dsu = DSU()\n nodes = set()\n smallest = [s[i] for i in range(len(s))]\n\n for i,j in pairs:\n dsu.unify(i,j)\n nodes.add(i)\n nodes.add(j)\n\n groups = {}\n for node in nodes:\n par = dsu.find(node)\n if par not in groups:\n groups[par] = [node]\n else:\n groups[par].append(node)\n \n for group in groups.values():\n letters,k = sorted([s[i] for i in group]),0\n \n for i in group:\n smallest[i] = letters[k]\n k+=1\n\n return \"\".join(smallest)", "solution_js": "var smallestStringWithSwaps = function(s, pairs) {\n const uf = new UnionFind(s.length);\n pairs.forEach(([x,y]) => uf.union(x,y))\n \n const result = [];\n for (const [root, charIndex] of Object.entries(uf.disjointSets())) {\n let chars = charIndex.map(i => s[i])\n chars.sort();\n charIndex.forEach((charIndex, i) => result[charIndex] = chars[i])\n }\n \n return result.join(\"\")\n};\n\nclass UnionFind {\n constructor(len) {\n this.roots = Array.from({length: len}).map((_, i) => i);\n this.rank = Array.from({length: len}).fill(1);\n }\n \n find(x) { \n if (x == this.roots[x]) {\n return x;\n }\n return this.roots[x] = this.find(this.roots[x])\n }\n \n union(x, y) {\n let rootX = this.find(x);\n let rootY = this.find(y);\n \n if (this.rank[rootX] > this.rank[rootY]) {\n this.roots[rootY] = rootX;\n } else if (this.rank[rootX] < this.rank[rootY]) {\n this.roots[rootX] = rootY;\n } else { // ranks equal\n this.roots[rootY] = rootX;\n this.rank[rootX]++\n }\n }\n \n disjointSets() {\n const ds = {};\n for(let i = 0; i < this.roots.length; i++) {\n let currentRoot = this.find(i);\n if (currentRoot in ds) {\n ds[currentRoot].push(i);\n } else {\n ds[currentRoot] = [i];\n }\n }\n return ds;\n }\n}", "solution_java": "class Solution {\n int[]parent;\n int[]rank;\n public String smallestStringWithSwaps(String s, List> pairs) {\n parent = new int[s.length()];\n rank = new int[s.length()];\n for(int i=0;i l : pairs){\n int i = l.get(0);\n int j = l.get(1);\n \n int il = find(i);\n int jl = find(j);\n if(il != jl){\n union(il,jl);\n }\n }\n \n //To get the Character in sorted order\n PriorityQueue[]pq = new PriorityQueue[s.length()];\n for(int i=0;i();\n }\n \n for(int i=0;i parent;\n\n int findParent(int n)\n {\n if(parent[n] == n) return n;\n return parent[n] = findParent(parent[n]);\n }\n\n string smallestStringWithSwaps(string s, vector>& pairs)\n {\n map> mp;\n parent.resize(s.size());\n string ans = s;\n\n for(int i=0; i part;\n set idx = it.second;\n\n for(auto index: idx) part.push_back(s[index]);\n\n sort(part.begin(), part.end());\n\n auto index = idx.begin();\n for(auto x: part) ans[*index] = x, ++index;\n }\n\n return ans;\n }\n};" }, { "title": "Find Pivot Index", "algo_input": "Given an array of integers nums, calculate the pivot index of this array.\n\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\n\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\n\nReturn the leftmost pivot index. If no such index exists, return -1.\n\n \nExample 1:\n\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\n\n\nExample 2:\n\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\n\nExample 3:\n\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-1000 <= nums[i] <= 1000\n\n\n \nNote: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/\n", "solution_py": "class Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n right = sum(nums)\n left = 0\n\n for i in range(len(nums)):\n right -= nums[i]\n left += nums[i - 1] if i > 0 else 0\n\n if right == left: return i\n\n return -1", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar pivotIndex = function(nums) {\n //step 1\n var tot=0;\n for (let i = 0; i < nums.length; i++) {\n tot+= nums[i]; \n }\n // Step 2\n left = 0 ;\n for (let j = 0; j < nums.length; j++) {\n right = tot - nums[j] - left;\n if (left == right){\n return j\n }\n left += nums[j];\n }\n return -1\n};", "solution_java": "class Solution {\n public int pivotIndex(int[] nums) {\n\n int leftsum = 0;\n int rightsum = 0;\n\n for(int i =1; i< nums.length; i++) rightsum += nums[i];\n\n if (leftsum == rightsum) return 0;\n\n for(int i = 1 ; i < nums.length; i++){\n leftsum += nums[i-1];\n rightsum -= nums[i];\n\n if(leftsum == rightsum) return i;\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int pivotIndex(vector& nums) {\n int sum=0, leftSum=0;\n for (int& n : nums){\n sum += n;\n }\n for(int i=0; i= target:\n # Potential answer found! Now try to minimize it iff possible.\n ans = mid\n right = mid\n else:\n left = mid + 1\n return ans\n \n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n # Sort rectangles based on the lengths\n rectangles.sort() \n # Group rectangles by their height in increasing order of their length\n lengths = {}\n for x,y in rectangles:\n if y in lengths:\n lengths[y].append(x)\n else:\n lengths[y] = [x]\n \n heights = sorted(list(lengths.keys()))\n \n count = [0] * len(points)\n \n for idx, point in enumerate(points):\n x, y = point\n # Get the min height rectangle that would accommodate the y coordinate of current point.\n minHeightRectIdx = self.binarySearch(heights, y)\n if minHeightRectIdx is not None:\n for h in heights[minHeightRectIdx:]:\n # Get the Min length rectangle that would accommodate the x coordinate of current point for all h height rectangles.\n minLenRectIdx = self.binarySearch(lengths[h], x)\n if minLenRectIdx is not None:\n count[idx] += len(lengths[h]) - minLenRectIdx\n \n return count", "solution_js": "var countRectangles = function(rectangles, points) {\n let buckets = Array(101).fill(0).map(() => []);\n for (let [x, y] of rectangles) {\n buckets[y].push(x);\n }\n for (let i = 0; i < 101; i++) buckets[i].sort((a, b) => a - b);\n\n let res = [];\n for (let point of points) {\n let sum = 0;\n for (let j = point[1]; j < 101; j++) {\n // lowest index >= point[0]\n let index = lower_bound(buckets[j], point[0]);\n sum += buckets[j].length - index;\n }\n res.push(sum);\n }\n return res;\n\n function lower_bound(arr, targ) {\n let low = 0, high = arr.length;\n while (low < high) {\n let mid = Math.floor((low + high) / 2);\n if (arr[mid] >= targ) high = mid;\n else low = mid + 1;\n }\n return low;\n }\n};", "solution_java": "class Solution {\n public int[] countRectangles(int[][] rectangles, int[][] points) {\n int max = Integer.MIN_VALUE;\n\n TreeMap> rects = new TreeMap<>();\n for(int[] rect : rectangles) {\n if (!rects.containsKey(rect[1])) {\n rects.put(rect[1], new ArrayList());\n }\n\n rects.get(rect[1]).add(rect[0]);\n max = Math.max(max, rect[1]);\n }\n\n for(int k : rects.keySet()) {\n Collections.sort(rects.get(k));\n }\n\n int[] ans = new int[points.length];\n for(int i = 0; i < points.length; i++) {\n if (points[i][1] > max) {\n continue;\n }\n\n int count = 0;\n\n for(int key : rects.subMap(points[i][1], max + 1).keySet()) {\n List y = rects.get(key);\n\n count += binarySearch(y, points[i][0]);\n }\n\n ans[i] = count;\n }\n\n return ans;\n }\n\n private int binarySearch(List vals, int val) {\n int lo = 0;\n int hi = vals.size() - 1;\n int id = -1;\n\n while(lo <= hi) {\n int mid = lo + (hi - lo) / 2;\n\n if (vals.get(mid) < val) {\n lo = mid + 1;\n } else {\n id = mid;\n hi = mid - 1;\n }\n }\n\n if (id < 0) {\n return 0;\n }\n\n return vals.size() - id;\n }\n}", "solution_c": "class Solution {\npublic:\n vector countRectangles(vector>& rectangles, vector>& points) {\n \n int i, count, ind, x, y, n = rectangles.size();\n \n vector ans;\n vector> heights(101);\n \n for(auto rect : rectangles)\n heights[rect[1]].push_back(rect[0]);\n \n for(i=0;i<101;i++)\n sort(heights[i].begin(), heights[i].end());\n \n for(auto point : points)\n {\n count = 0;\n x = point[0];\n y = point[1];\n for(i=y;i<101;i++)\n {\n ind = lower_bound(heights[i].begin(), heights[i].end(), x) - heights[i].begin();\n count += (heights[i].size() - ind);\n }\n ans.push_back(count);\n }\n return ans;\n }\n};" }, { "title": "Unique Binary Search Trees II", "algo_input": "Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.\n\n \nExample 1:\n\nInput: n = 3\nOutput: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n\n\nExample 2:\n\nInput: n = 1\nOutput: [[1]]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 8\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 def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n # define a sorted list of the numbers, for each num in that list , leftvalues\n# are left tree and right val are rightree, then for each number create a tree\n# assign the left and right to that root and append the root to the ans\n nums = list(range(1,n+1))\n def dfs(nums):\n if not nums:\n return [None]\n ans = []\n for i in range(len(nums)):\n leftTrees = dfs(nums[:i])\n rightTrees = dfs(nums[i+1:])\n\n for l in leftTrees:\n for r in rightTrees:\n root = TreeNode(nums[i])\n root.left = l\n root.right = r\n ans.append(root)\n return ans\n\n return dfs(nums)", "solution_js": "var generateTrees = function(n) {\n if(n <= 0){\n return [];\n }\n return generateRec(1, n);\n\n};\n\nfunction generateRec(start, end){\n let result = [];\n\n if(start > end){\n result.push(null);\n return result;\n }\n\n for(let i = start; i generateTrees(int n) {\n return helper(1,n);\n }\n \n public List helper(int lo, int hi){\n List res=new ArrayList<>();\n if(lo>hi){\n res.add(null);\n return res;\n }\n \n \n for(int i=lo;i<=hi;i++){\n List left=helper(lo,i-1);\n List right=helper(i+1,hi);\n \n for(TreeNode l:left){\n for(TreeNode r:right){\n TreeNode head=new TreeNode(i);\n head.left=l;\n head.right=r;\n \n res.add(head);\n }\n }\n }\n \n return res;\n }\n}", "solution_c": "class Solution \n{\n public:\n vector solve(int start, int end)\n {\n //base case\n if(start>end){\n return {NULL};\n }\n vector lChild, rChild, res;\n //forming a tree, by keeping each node as root node\n for(int i=start; i<=end; i++)\n {\n //don't create node here, bcz for each combination of subtree, node with new address has to be generated\n\n //recursive call for left,right child, they will return vector of all possible subtrees\n lChild = solve(start, i-1);\n rChild = solve(i+1, end);\n \n //for each subtree returned by lChild, forming combination with each subtree returned by rChild\n for(auto l: lChild)\n {\n for(auto r: rChild)\n {\n //generating new node for each combination\n TreeNode* node = new TreeNode(i);\n //attaching left, right childs\n node->left = l;\n node->right = r;\n res.push_back(node);\n }\n } \n }\n //returning all possible subtrees\n return res;\n }\n vector generateTrees(int n) {\n return solve(1, n);\n }\n};" }, { "title": "Design a Number Container System", "algo_input": "Design a number container system that can do the following:\n\n\n\tInsert or Replace a number at the given index in the system.\n\tReturn the smallest index for the given number in the system.\n\n\nImplement the NumberContainers class:\n\n\n\tNumberContainers() Initializes the number container system.\n\tvoid change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.\n\tint find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.\n\n\n \nExample 1:\n\nInput\n[\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]\nOutput\n[null, -1, null, null, null, null, 1, null, 2]\n\nExplanation\nNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.\n\n\n \nConstraints:\n\n\n\t1 <= index, number <= 109\n\tAt most 105 calls will be made in total to change and find.\n\n", "solution_py": "class NumberContainers:\n def __init__(self):\n self.numbersByIndex = {}\n self.numberIndexes = defaultdict(set)\n self.numberIndexesHeap = defaultdict(list)\n\n def change(self, index: int, number: int) -> None:\n if index in self.numbersByIndex:\n if number != self.numbersByIndex[index]:\n self.numberIndexes[self.numbersByIndex[index]].remove(index)\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n else:\n self.numbersByIndex[index] = number\n self.numberIndexes[number].add(index)\n heappush(self.numberIndexesHeap[number], index)\n\n def find(self, number: int) -> int:\n while self.numberIndexesHeap[number] and self.numberIndexesHeap[number][0] not in self.numberIndexes[number]:\n heappop(self.numberIndexesHeap[number]) # make sure the smallest index in heap is still an index for number\n return self.numberIndexesHeap[number][0] if self.numberIndexesHeap[number] else -1", "solution_js": "var NumberContainers = function() {\n this.obj = {}\n this.global = {}\n};\n\nNumberContainers.prototype.change = function(index, number) {\n\n if(this.global[index])\n {\n for(var key in this.obj)\n {\n let ind = this.obj[key].indexOf(index)\n if(ind != -1)\n {\n this.obj[key].splice(ind, 1);\n if(this.obj[number])\n this.obj[number].push(index);\n else\n this.obj[number] = [index];\n\n this.global[index]=1;\n return;\n }\n }\n }\n\n if(this.obj[number])\n this.obj[number].push(index);\n else\n this.obj[number] = [index];\n this.global[index]=1;\n};\n\nNumberContainers.prototype.find = function(number) {\n if(this.obj[number])\n {\n if(this.obj[number].length == 0)\n return -1\n else\n return Math.min(...this.obj[number])\n }\n return -1;\n};", "solution_java": "class NumberContainers {\n \n Map> map;\n Map m;\n public NumberContainers() {\n map=new HashMap<>();\n m=new HashMap<>();\n \n }\n public void change(int index, int number) {\n m.put(index,number);\n if(!map.containsKey(number)) map.put(number,new TreeSet<>());\n map.get(number).add(index);\n }\n \n public int find(int number) {\n if(!map.containsKey(number)) return -1;\n for(Integer a:map.get(number)){\n if(m.get(a)==number) return a;\n }\n return -1;\n }\n}", "solution_c": "class NumberContainers {\npublic:\n map indexToNumber; // stores number corresponding to an index.\n map>numberToIndex; // stores all the indexes corresponding to a number.\n NumberContainers() {}\n\n void change(int index, int number) {\n\n if (!indexToNumber.count(index)) { // if there is no number at the given index.\n numberToIndex[number].insert(index); // store index corresponding to the given number\n indexToNumber[index] = number; // store number corresponding to the index.\n }\n else { // Update both map.\n\n int num = indexToNumber[index]; // number at given index currently.\n\n // remove the index\n numberToIndex[num].erase(index);\n if (numberToIndex[num].empty()) numberToIndex.erase(num);\n\n // insert the new number at the given index and store the index corresponding to that number.\n numberToIndex[number].insert(index);\n indexToNumber[index] = number;\n }\n }\n\n int find(int number) {\n if (!numberToIndex.count(number)) return -1;\n // returning first element in the set as it will be the smallest index always.\n return *numberToIndex[number].begin();\n }\n};" }, { "title": "Reconstruct Original Digits from English", "algo_input": "Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.\n\n \nExample 1:\nInput: s = \"owoztneoer\"\nOutput: \"012\"\nExample 2:\nInput: s = \"fviefuro\"\nOutput: \"45\"\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"].\n\ts is guaranteed to be valid.\n\n", "solution_py": "class Solution:\n def originalDigits(self, s: str) -> str:\n c = dict()\n \n c[0] = s.count(\"z\")\n c[2] = s.count(\"w\")\n c[4] = s.count(\"u\")\n c[6] = s.count(\"x\")\n c[8] = s.count(\"g\")\n \n c[3] = s.count(\"h\") - c[8]\n c[5] = s.count(\"f\") - c[4]\n c[7] = s.count(\"s\") - c[6]\n \n c[9] = s.count(\"i\") - (c[8] + c[5] + c[6])\n c[1] = s.count(\"o\") - (c[0] + c[2] + c[4])\n \n c = sorted(c.items(), key = lambda x: x[0])\n ans = \"\"\n for k, v in c:\n ans += (str(k) * v)\n return ans", "solution_js": "/**\n * @param {string} s\n * @return {string}\n */\n \nvar originalDigits = function(s) {\n const numberToWord = {\n 0: 'zero',\n 1: 'one',\n 2: 'two',\n 3: 'three',\n 4: 'four',\n 5: 'five',\n 6: 'six',\n 7: 'seven',\n 8: 'eight',\n 9: 'nine'\n }\n \n const letterToDigits = {}\n \n for(const key in numberToWord) {\n const currWord = numberToWord[key]\n \n for(const letter of currWord) {\n if(!(letter in letterToDigits)) letterToDigits[letter] = new Set()\n letterToDigits[letter].add(key)\n }\n }\n \n const inputFreqs = {}\n \n for(let i = 0; i < s.length; i++) {\n const currChar = s[i]\n \n if(!(currChar in inputFreqs)) inputFreqs[currChar] = 0\n inputFreqs[currChar]++\n }\n \n const letters = Object.keys(inputFreqs)\n \n const res = dfs(letters[0])\n \n return [...res].sort().join('')\n \n function dfs(currLetter) {\n if(!isValid(inputFreqs)) return null\n if(getTotalRemaining(inputFreqs) === 0) return []\n const possibleDigits = letterToDigits[currLetter]\n \n for(const digit of [...possibleDigits]) {\n const wordRepresentation = numberToWord[digit]\n \n subtract(wordRepresentation)\n \n if(!isValid(inputFreqs)) {\n addBack(wordRepresentation)\n continue\n }\n \n const nextLetter = getNext(inputFreqs)\n const nextDigits = dfs(nextLetter)\n \n if(nextDigits !== null) return [digit] + nextDigits\n \n addBack(wordRepresentation)\n }\n \n return null\n }\n \n function isValid(inputFreqs) {\n for(const key in inputFreqs) {\n const count = inputFreqs[key]\n \n if(count < 0) return false\n }\n \n return true\n }\n \n function getTotalRemaining(inputFreqs) {\n let sum = 0\n \n for(const key in inputFreqs) {\n const count = inputFreqs[key]\n \n sum += count\n }\n \n \n return sum\n }\n \n function subtract(word) {\n for(const char of word) {\n if(!(char in inputFreqs)) inputFreqs[char] = 0\n inputFreqs[char]--\n }\n }\n \n \n function addBack(word) {\n for(const char of word) {\n inputFreqs[char]++\n }\n }\n \n function getNext(inputFreqs) {\n for(const key in inputFreqs) {\n const count = inputFreqs[key]\n \n if(count > 0) return key\n }\n \n return null\n }\n};", "solution_java": "class Solution {\n\n // First letter is unique after previous entries have been handled:\n static final String[] UNIQUES = new String[] {\n \"zero\", \"wto\", \"geiht\", \"xsi\", \"htree\",\n \"seven\", \"rfou\", \"one\", \"vfie\", \"inne\"\n };\n\n // Values corresponding to order of uniqueness checks:\n static final int[] VALS = new int[] { 0, 2, 8, 6, 3, 7, 4, 1, 5, 9 };\n \n\t// Maps for checking uniqueness more conveniently:\n static final Map> ORDERED_FREQ_MAP;\n static final Map ORDERED_DIGIT_MAP;\n \n static {\n\t // Initialize our ordered frequency map: 0-25 key to 0-25 values finishing the word:\n final LinkedHashMap> orderedFreqMap = new LinkedHashMap<>();\n\t\t// Also initialize a digit lookup map, e.g. 'g' becomes 6 maps to 8 for ei[g]ht:\n final LinkedHashMap orderedDigitMap = new LinkedHashMap<>();\n for (int i = 0; i < 10; ++i) {\n final char unique = UNIQUES[i].charAt(0);\n final int ui = convert(unique);\n orderedFreqMap.put(ui, converting(UNIQUES[i].substring(1).toCharArray()));\n orderedDigitMap.put(ui, VALS[i]);\n }\n\t\t// Let's make sure we aren't tempted to modify these since they're static.\n ORDERED_FREQ_MAP = Collections.unmodifiableMap(orderedFreqMap);\n ORDERED_DIGIT_MAP = Collections.unmodifiableMap(orderedDigitMap);\n }\n\n public String originalDigits(String s) {\n\t // count frequencies of each letter in s:\n final int[] freqs = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n freqs[convert(s.charAt(i))]++;\n }\n\t\t// Crate an array to store digit strings in order, e.g. '00000', '11, '2222222', etc.\n final String[] strings = new String[10];\n\t\t// Iterate through uniqueness checks in order:\n for (Map.Entry> entry : ORDERED_FREQ_MAP.entrySet()) {\n final int index = entry.getKey(); // unique letter in 0-25 form\n final int value = ORDERED_DIGIT_MAP.get(index); // corresponding digit, e.g. 8 for 'g', 0 for 'z', etc.\n final int count = freqs[index]; // frequency of unique letter = frequency of corresponding digit\n if (count > 0) {\n\t\t\t // update frequencies to remove the digit's word count times:\n freqs[index] -= count;\n for (int idx : entry.getValue()) {\n freqs[idx] -= count;\n }\n\t\t\t\t// now create the digit string for the unique digit: the digit count times:\n strings[value] = String.valueOf(value).repeat(count);\n } else {\n\t\t\t // count 0 - empty strring for this digit\n strings[value] = \"\";\n }\n }\n\t\t// append the digit strings in order\n final StringBuilder sb = new StringBuilder();\n for (String str : strings) {\n sb.append(str);\n }\n\t\t// and we are done!\n return sb.toString();\n }\n\n // Converts a character array into a list of 0-25 frequency values.\n private static final List converting(char... carr) {\n final List list = new ArrayList<>();\n for (char ch : carr) {\n list.add(convert(ch)); // converts each to 0-25\n }\n return Collections.unmodifiableList(list);\n }\n\n // Converts a-z to 0-26. Bitwise AND with 31 gives a=1, z=26, so then subtract one.\n private static final Integer convert(char ch) {\n return (ch & 0x1f) - 1; // a->0, z->25\n }\n\n}", "solution_c": "class Solution {\npublic:\n \n vector digits{\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\"};\n void fun(int x,string &ans,vector &m){\n for(int i = x;i<=9;i+=2){\n string t = digits[i];\n if(t.length() == 3){\n if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0){\n int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a']});\n m[t[0]-'a'] -= min_o;\n m[t[1]-'a'] -= min_o;\n m[t[2]-'a'] -= min_o;\n while(min_o--) ans += (char)(i +'0');\n }\n }else if(t.length() == 4){\n if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0){\n int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a']});\n m[t[0]-'a'] -= min_o;\n m[t[1]-'a'] -= min_o;\n m[t[2]-'a'] -= min_o;\n m[t[3]-'a'] -= min_o;\n while(min_o--) ans += (char)(i +'0');\n }\n }else if(t.length() == 5){\n if(m[t[0]-'a'] > 0 && m[t[1]-'a'] > 0 && m[t[2]-'a'] > 0 && m[t[3]-'a'] > 0 && m[t[4]-'a'] > 0){\n int min_o = min({m[t[0]-'a'] ,m[t[1]-'a'] , m[t[2]-'a'], m[t[3]-'a'], m[t[4]-'a']});\n m[t[0]-'a'] -= min_o;\n m[t[1]-'a'] -= min_o;\n m[t[2]-'a'] -= min_o;\n m[t[3]-'a'] -= min_o;\n m[t[4]-'a'] -= min_o;\n while(min_o--) ans += (char)(i +'0');\n }\n }\n }\n }\n \n string originalDigits(string s) {\n string ans;\n vector m(26,0);\n for(auto x:s) m[x-'a']++;\n fun(0,ans,m);\n fun(1,ans,m);\n sort(ans.begin(),ans.end());\n return ans;\n }\n};" }, { "title": "Even Odd Tree", "algo_input": "A binary tree is named Even-Odd if it meets the following conditions:\n\n\n\tThe root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.\n\tFor every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).\n\tFor every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).\n\n\nGiven the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.\n\n \nExample 1:\n\nInput: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput: true\nExplanation: The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\n\n\nExample 2:\n\nInput: root = [5,4,2,3,3,7]\nOutput: false\nExplanation: The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\n\n\nExample 3:\n\nInput: root = [5,9,1,3,5,7]\nOutput: false\nExplanation: Node values in the level 1 should be even integers.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 105].\n\t1 <= Node.val <= 106\n\n", "solution_py": "from collections import deque\n# O(n) || O(h); where h is the height of the tree\n\nclass Solution:\n def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return False\n\n level = 0\n evenOddLevel = {0:1, 1:0}\n queue = deque([root])\n\n while queue:\n prev = 0\n for _ in range(len(queue)):\n currNode = queue.popleft()\n comparison = {0:prev < currNode.val, 1:prev > currNode.val}\n if currNode.val % 2 != evenOddLevel[level % 2]:\n return False\n else:\n if prev != 0 and comparison[level % 2]:\n prev = currNode.val\n elif prev == 0:\n prev = currNode.val\n else:\n return False\n\n if currNode.left:\n queue.append(currNode.left)\n\n if currNode.right:\n queue.append(currNode.right)\n\n level += 1\n\n return True", "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 {boolean}\n */\nvar isEvenOddTree = function(root) {\n let queue = [root];\n let steps = 0;\n\n while(queue.length>0){\n const currLength = queue.length;\n let nextQueue=[];\n\n for(let i=0; i=queue[i+1].val)|| node.val%2 === 0){\n return false;\n }\n if(node.left) nextQueue.push(node.left);\n if(node.right) nextQueue.push(node.right);\n }\n queue = nextQueue;\n steps++;\n }\n\n return true;\n};", "solution_java": "class Solution {\n public boolean isEvenOddTree(TreeNode root) {\n Queue qu = new LinkedList<>();\n qu.add(root);\n boolean even = true; // maintain check for levels\n while(qu.size()>0){\n int size = qu.size();\n int prev = (even)?0:Integer.MAX_VALUE; // start prev with 0 to check strictly increasing and Integer_MAX_VALUE to check strictly decreasing \n while(size-->0){\n TreeNode rem = qu.remove();\n if(even){\n if(rem.val%2==0 || rem.val<=prev){ // false if value at even level is even or not strictly increasing \n return false;\n }\n }else{\n if(rem.val%2!=0 || rem.val>=prev){// false if value at odd level is odd or not strictly decreasing\n return false;\n }\n }\n if(rem.left!=null){\n qu.add(rem.left); \n }\n if(rem.right!=null){\n qu.add(rem.right);\n }\n prev=rem.val; //update previous\n \n }\n even = !even; //change level\n } \n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isEvenOddTree(TreeNode* root) {\n queueq;\n vector>ans;\n if(root==NULL) return true;\n q.push(root);\n int j=0;\n while(q.empty()!=true)\n { vectorv;\n int n=q.size();\n for(int i=0;ival);\n if(t->left) q.push(t->left);\n if(t->right) q.push(t->right);\n }\n if(j%2==0)\n {\n for(int k=0;k=v[k+1])\n return false;\n }\n if(v[v.size()-1]%2==0)\n return false;\n }\n else\n {\n for(int k=0;k int:\n prime_nums = len(primes)\n index = [1]*prime_nums\n ret = [1]*(n+1)\n for i in range(2,n+1):\n ret[i] = min(primes[j]*ret[index[j]] for j in range(prime_nums))\n for k in range(prime_nums):\n if ret[i] == primes[k]*ret[index[k]]:\n index[k]+= 1\n \n return ret[-1]", "solution_js": "var nthSuperUglyNumber = function(n, primes) {\n const table = Array(primes.length).fill(0);\n const res = Array(n);\n res[0] = 1;\n for(let j=1;j pq=new PriorityQueue<>();\n \n for(int i=0;i0){\n pq.add(new Pair(curr.prime, curr.ptr+1,newval));\n }\n }\n \n return dp[n];\n }\n}\n\nclass Pair implements Comparable{\n int prime;\n int ptr;\n int val;\n \n public Pair(int prime, int ptr, int val){\n this.prime=prime;\n this.ptr=ptr;\n this.val=val;\n }\n \n public int compareTo(Pair o){\n return this.val-o.val;\n }\n}\n\n//-----------------------O(nk)---------------------------\n\n// class Solution {\n// public int nthSuperUglyNumber(int n, int[] primes) {\n// int []dp=new int[n+1];\n// dp[1]=1;\n \n// int []ptr=new int[primes.length];\n \n// Arrays.fill(ptr,1);\n \n// for(int i=2;i<=n;i++){\n \n// int min=Integer.MAX_VALUE;\n \n// for(int j=0;j0){\n// min=Math.min(min,val);\n// }\n \n// }\n \n// dp[i]=min;\n \n// for(int j=0;j0 && min==val){\n// ptr[j]++;\n// }\n// }\n// }\n \n// return dp[n];\n// }\n// }", "solution_c": "Time: O(n*n1) Space: O(n)\n\nclass Solution {\npublic:\n int nthSuperUglyNumber(int n, vector& primes) {\n if(n==1)\n return 1;\n vector dp(n);\n dp[0]=1;\n int n1=size(primes);\n vector p(n1);\n for(int i=1;i map = new HashMap<>();\n for (int i = 0; i& nums, string target) {\n unordered_map freq;\n for (auto num : nums) if (num.size() < target.size()) freq[num]++;\n \n int res = 0;\n for (auto [s, frq] : freq) {\n \n if (target.find(s) == 0) {\n \n if (s + s == target) \n res += frq*(frq-1);\n \n else \n res += frq * freq[target.substr(s.size())];\n }\n }\n \n return res;\n }\n};" }, { "title": "Pancake Sorting", "algo_input": "Given an array of integers arr, sort the array by performing a series of pancake flips.\n\nIn one pancake flip we do the following steps:\n\n\n\tChoose an integer k where 1 <= k <= arr.length.\n\tReverse the sub-array arr[0...k-1] (0-indexed).\n\n\nFor example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.\n\nReturn an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.\n\n \nExample 1:\n\nInput: arr = [3,2,4,1]\nOutput: [4,2,4,3]\nExplanation: \nWe perform 4 pancake flips, with k values 4, 2, 4, and 3.\nStarting state: arr = [3, 2, 4, 1]\nAfter 1st flip (k = 4): arr = [1, 4, 2, 3]\nAfter 2nd flip (k = 2): arr = [4, 1, 2, 3]\nAfter 3rd flip (k = 4): arr = [3, 2, 1, 4]\nAfter 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\n\n\nExample 2:\n\nInput: arr = [1,2,3]\nOutput: []\nExplanation: The input is already sorted, so there is no need to flip anything.\nNote that other answers, such as [3, 3], would also be accepted.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 100\n\t1 <= arr[i] <= arr.length\n\tAll integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length).\n\n", "solution_py": "class Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n #helper function to flip the numbers in the array\n\t\tdef flip(i, j):\n while i < j:\n arr[i], arr[j] = arr[j], arr[i]\n j -= 1\n i += 1\n \n #sort from 0 to i\n def sort(i):\n\t\t\t#base case where all the numbers are sorted, thus no more recursive calls\n if i < 0:\n return []\n ret = []\n\t\t\t#find the biggest number, which always will be the len(arr), or i + 1\n idx = arr.index(i + 1)\n\t\t\t# if the biggest number is in the right place, as in idx == i, then we don't change anything, but just move to sort the next biggest number\n if idx == i:\n return sort(i - 1)\n \n\t\t\t#we flip it with the first element (even if the biggest number is the first element, it will flip itself (k = 1) and does not affect the result\n ret.append(idx + 1)\n flip(0, idx)\n\t\t\t#we know the biggest number is the first element of the array. Flip the whole array in the boundary so that the biggest number would be in the last of the subarray (notice not len(arr) - 1 because that will flip the already-sorted elements as well)\n ret.append(i + 1)\n flip(0, i)\n\t\t\t#sort the next biggest number by setting a new boundary i - 1\n return ret + sort(i - 1)\n \n \n return sort(len(arr) - 1)\n ", "solution_js": "var pancakeSort = function(arr) {\nlet res = [];\n\nfor(let i=arr.length; i>0; i--){//search the array for all values from 1 to n\n let idx = arr.indexOf(i);\n if(idx!=i-1){// if value is not present at its desired index\n let pancake = arr.slice(0,idx+1).reverse();//flip the array with k=index of value i to put it in front of the array\n res.push(idx+1);\n arr = arr.slice(idx+1);\n arr = pancake.concat(arr);//value i is now at index 0\n pancake = arr.slice(0,i).reverse();//flip the array with k = i-1 to put the value at its place\n res.push(i);\n arr = arr.slice(i);\n arr = pancake.concat(arr);//now the array is sorted from i to n\n }\n}\nreturn res;\n};", "solution_java": "// BruteForce Approach!\n// Author - Nikhil Sharma\n// LinkedIn - https://www.linkedin.com/in/nikhil-sharma-41a287226/\n// Twitter - https://twitter.com/Sharma_Nikh12\n\nclass Solution {\n public List pancakeSort(int[] arr) {\n List list = new ArrayList<>();\n int n = arr.length;\n while(n!=1) {\n int maxIndex = findIndex(arr,n);\n reverse(arr, maxIndex);\n reverse(arr, n-1);\n list.add(maxIndex+1);\n list.add(n);\n n--;\n }\n return list;\n }\n\n static int findIndex(int[] arr, int value) {\n for(int i=0; i&arr,int start,int end){\n while(start pancakeSort(vector& arr) {\n vectorcopy=arr;\n sort(copy.begin(),copy.end());\n int end=copy.size()-1;\n vectorans;\n while(end>0){\n if(arr[end]!=copy[end]){\n int pos=end-1;\n while(arr[pos]!=copy[end]){\n pos--;\n }\n reverse(arr,0,pos);\n if(pos!=0){\n ans.push_back(pos+1);\n }\n reverse(arr,0,end);\n ans.push_back(end+1);\n }\n end--;\n }\n return ans;\n }\n};" }, { "title": "Maximum Product of Word Lengths", "algo_input": "Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.\n\n \nExample 1:\n\nInput: words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\nOutput: 16\nExplanation: The two words can be \"abcw\", \"xtfn\".\n\n\nExample 2:\n\nInput: words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\nOutput: 4\nExplanation: The two words can be \"ab\", \"cd\".\n\n\nExample 3:\n\nInput: words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: 0\nExplanation: No such pair of words.\n\n\n \nConstraints:\n\n\n\t2 <= words.length <= 1000\n\t1 <= words[i].length <= 1000\n\twords[i] consists only of lowercase English letters.\n\n", "solution_py": "class Solution:\n def maxProduct(self, words: List[str]) -> int:\n def check(w1, w2):\n for i in w1:\n if i in w2: \n return False\n return True\n \n n = len(words) \n Max = 0\n for i in range(n):\n for j in range(i+1, n):\n if check(words[i], words[j]):\n Max = max(Max, len(words[i])*len(words[j])) \n return Max", "solution_js": "/**\n * @param {string[]} words\n * @return {number}\n */\nvar maxProduct = function(words) {\n words.sort((a, b) => b.length - a.length);\n \n const m = new Map();\n for(let word of words) {\n if(m.has(word)) continue;\n const alpha = new Array(26).fill(0);\n for(let w of word) {\n let idx = w.charCodeAt(0) - 'a'.charCodeAt(0);\n alpha[idx] = 1;\n }\n m.set(word, parseInt(alpha.join(''), 2));\n }\n \n const hasCommonLetters = (a, b) => {\n const sb = m.get(b);\n const sa = m.get(a);\n return (sa & sb) != 0;\n }\n let ans = 0, len = words.length;\n for(let i = 0; i < len; i++) {\n for(let j = i + 1; j < len; j++) {\n if(!hasCommonLetters(words[i], words[j])) {\n ans = Math.max(ans, words[i].length * words[j].length);\n }\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int maxProduct(String[] words) {\n int n = words.length;\n int[] masks = new int[n];\n\n for (int i=0; i& words) {\n vector> st;\n int res =0;\n for(string s : words){\n unordered_set temp;\n for(char c : s){\n temp.insert(c);\n }\n st.push_back(temp);\n }\n for(int i = 0;i int:\n temp1=temp2=float(inf)\n from collections import deque\n a=deque([root])\n while a:\n node=a.popleft()\n if node.valtemp1:\n if node.val", "solution_js": "var findSecondMinimumValue = function(root) {\n \n let firstMin=Math.min()\n let secondMin=Math.min()\n \n const que=[root]\n \n while(que.length){\n const node=que.shift()\n if(node.val<=firstMin){\n if(node.valq;\n q.push(root);\n vectorv;\n while(!q.empty()){\n v.push_back(q.front()->val);\n if(q.front()->left){\n q.push(q.front()->left);\n }\n if(q.front()->right){\n q.push(q.front()->right);\n }\n q.pop();\n }\n sort(v.begin(),v.end());\n int ans=-1;\n for(int i=1;i bool:\n if not p and not q:\n return True\n elif not p or not q:\n return False\n else:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)", "solution_js": "var isSameTree = function(p, q) {\n \n const stack = [p, q];\n \n while (stack.length) {\n const node2 = stack.pop();\n const node1 = stack.pop();\n \n if (!node1 && !node2) continue;\n\n if (!node1 && node2 || node1 && !node2 || node1.val !== node2.val) {\n return false;\n }\n \n stack.push(node1.left, node2.left, node1.right, node2.right);\n }\n \n return true;\n};", "solution_java": "class Solution {\n public boolean isSameTree(TreeNode p, TreeNode q) {\n // Base case: if both trees are null, they are identical\n if (p == null && q == null) {\n return true;\n }\n // If only one tree is null or the values are different, they are not identical\n if (p == null || q == null || p.val != q.val) {\n return false;\n }\n // Recursively check if the left and right subtrees are identical\n return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n }\n}", "solution_c": "class Solution {\npublic:\n bool isSameTree(TreeNode* p, TreeNode* q) {\n if(p == NULL || q == NULL) return q == p;\n if(p->val != q->val) return false;\n \n return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n }\n};" }, { "title": "Magnetic Force Between Two Balls", "algo_input": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.\n\nRick stated that magnetic force between two different balls at positions x and y is |x - y|.\n\nGiven the integer array position and the integer m. Return the required force.\n\n \nExample 1:\n\nInput: position = [1,2,3,4,7], m = 3\nOutput: 3\nExplanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n\n\nExample 2:\n\nInput: position = [5,4,3,2,1,1000000000], m = 2\nOutput: 999999999\nExplanation: We can use baskets 1 and 1000000000.\n\n\n \nConstraints:\n\n\n\tn == position.length\n\t2 <= n <= 105\n\t1 <= position[i] <= 109\n\tAll integers in position are distinct.\n\t2 <= m <= position.length\n\n", "solution_py": "class Solution:\n def possible (self,distance,positions,M):\n ball = 1 \n lastPos = positions[0] \n for pos in positions:\n if pos-lastPos >= distance:\n ball+=1 \n if ball == M: return True \n lastPos=pos \n \n return False \n \n \n \n def maxDistance(self, positions,M):\n positions.sort()\n low = 0 \n high = positions [-1] \n ans = 0\n while low<=high:\n distance = low+(high-low)//2 \n \n if self.possible(distance,positions,M):\n ans = distance\n low=distance+1 \n else:\n high=distance-1 \n return ans ", "solution_js": "var maxDistance = function(position, m) {\n position = position.sort((a, b) => a - b);\n\n function canDistribute(n) {\n let count = 1;\n let dist = 0;\n \n for(let i = 1; i < position.length; i++) {\n dist += position[i] - position[i - 1];\n \n if (dist >= n) {\n count++;\n dist = 0;\n }\n }\n \n return count >= m;\n }\n \n let left = 1;\n let right = position[position.length - 1] - position[0];\n let ans;\n \n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n\n if (canDistribute(mid)) {\n ans = mid;\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int maxDistance(int[] position, int m) {\n Arrays.sort(position);\n int low=Integer.MAX_VALUE;\n int high=0;\n for(int i=1;i=maxPossibleDist){\n prevballplace=position[i];\n balls++;\n }\n }\n if(balls>=m){\n return true;\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPossible(vector& position, int m,int mid){\n long long int basketCount=1;\n int lastPos=position[0];\n for(int i=0;i=mid){\n basketCount++;\n lastPos=position[i];\n }\n }\n return basketCount>=m;\n }\n int maxDistance(vector& position, int m) {\n sort(position.begin(),position.end());\n int n=position.size();\n long long int start=1;\n long long int end=position[n-1]-position[0];\n int ans=0;\n int mid= start+(end-start)/2;\n while(start<=end){\n if(isPossible(position,m,mid)){\n ans=mid;\n start=mid+1;\n }\n else\n end=mid-1;\n mid= start+(end-start)/2; \n }\n return ans;\n }\n};" }, { "title": "Flatten Nested List Iterator", "algo_input": "You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.\n\nImplement the NestedIterator class:\n\n\n\tNestedIterator(List<NestedInteger> nestedList) Initializes the iterator with the nested list nestedList.\n\tint next() Returns the next integer in the nested list.\n\tboolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.\n\n\nYour code will be tested with the following pseudocode:\n\ninitialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res\n\n\nIf res matches the expected flattened list, then your code will be judged as correct.\n\n \nExample 1:\n\nInput: nestedList = [[1,1],2,[1,1]]\nOutput: [1,1,2,1,1]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n\n\nExample 2:\n\nInput: nestedList = [1,[4,[6]]]\nOutput: [1,4,6]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n\n\n \nConstraints:\n\n\n\t1 <= nestedList.length <= 500\n\tThe values of the integers in the nested list is in the range [-106, 106].\n\n", "solution_py": "class NestedIterator:\n def __init__(self, nestedList: [NestedInteger]):\n self.flattened_lst = self.flattenList(nestedList)\n self.idx = 0\n \n def next(self) -> int:\n if self.idx >= len(self.flattened_lst):\n raise Exception(\"Index out of bound\")\n self.idx += 1\n return self.flattened_lst[self.idx-1]\n \n def hasNext(self) -> bool:\n return self.idx < len(self.flattened_lst)\n \n def flattenList(self, lst):\n flattened_lst = []\n for ele in lst:\n if ele.isInteger():\n flattened_lst.append(ele.getInteger())\n else:\n flattened_lst.extend(self.flattenList(ele.getList()))\n return flattened_lst", "solution_js": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * function NestedInteger() {\n *\n * Return true if this NestedInteger holds a single integer, rather than a nested list.\n * @return {boolean}\n * this.isInteger = function() {\n * ...\n * };\n *\n * Return the single integer that this NestedInteger holds, if it holds a single integer\n * Return null if this NestedInteger holds a nested list\n * @return {integer}\n * this.getInteger = function() {\n * ...\n * };\n *\n * Return the nested list that this NestedInteger holds, if it holds a nested list\n * Return null if this NestedInteger holds a single integer\n * @return {NestedInteger[]}\n * this.getList = function() {\n * ...\n * };\n * };\n */\n/**\n * @constructor\n * @param {NestedInteger[]} nestedList\n */\nvar NestedIterator = function(nestedList) {\n this.nestedList = []\n this.ptr = 0\n const dfs = (elem) => {\n if(!elem.isInteger()) {\n let list = elem.getList()\n for(let i = 0;i {\n List list=new ArrayList();\n void flatten(List nestedList){\n for(NestedInteger nested:nestedList){\n if(nested.isInteger())\n list.add(nested.getInteger());\n else\n flatten(nested.getList());\n }\n }\n public NestedIterator(List nestedList) {\n flatten(nestedList);\n }\n int index=0;\n @Override\n public Integer next() {\n return list.get(index++);\n }\n\n @Override\n public boolean hasNext() {\n return index v;\n int index;\n void helper(vector &nestedList, vector& v)\n {\n for (int i = 0; i < nestedList.size(); i++)\n {\n if (nestedList[i].isInteger())\n {\n v.push_back(nestedList[i].getInteger());\n }\n else\n {\n helper(nestedList[i].getList(), v);\n }\n }\n }\npublic:\n NestedIterator(vector &nestedList) {\n helper(nestedList, v);\n index = 0;\n }\n \n int next() {\n return v[index++];\n }\n \n bool hasNext() {\n if (v.size() <= index)\n {\n return false;\n }\n return true;\n }\n};" }, { "title": "Find All Numbers Disappeared in an Array", "algo_input": "Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.\n\n \nExample 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [5,6]\nExample 2:\nInput: nums = [1,1]\nOutput: [2]\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t1 <= nums[i] <= n\n\n\n \nFollow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.\n", "solution_py": "class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n return set(nums) ^ set(range(1,len(nums)+1))", "solution_js": "var findDisappearedNumbers = function(nums) {\n let result = [];\n for(let i = 0; i < nums.length; i++) {\n let id = Math.abs(nums[i]) - 1;\n nums[id] = - Math.abs(nums[id]);\n }\n for(let i = 0; i < nums.length; i++) {\n if(nums[i] > 0) result.push(i + 1);\n }\n return result;\n};", "solution_java": "class Solution {\n public List findDisappearedNumbers(int[] nums) {\n List res = new ArrayList<>();\n // 0 1 2 3 4 5 6 7 <- indx\n // 4 3 2 7 8 2 3 1 <- nums[i]\n for(int i=0;i0) {\n nums[indx] = nums[indx]*-1;\n }\n }\n // 0 1 2 3 4 5 6 7 <- indx\n // -4 -3 -2 -7 8 2 -3 -1 <- nums[i]\n for(int i=0;i0) {\n res.add(i+1);\n }else {\n nums[i] *= -1;\n }\n }\n // [ 5, 6]\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector findDisappearedNumbers(vector& nums) {\n vector res;\n int n = nums.size();\n for (int i = 0; i < n; i++) {\n if (nums[abs(nums[i]) - 1] > 0) {\n nums[abs(nums[i]) - 1] *= -1;\n }\n }\n for (int i = 0; i < n; i++) {\n if (nums[i] > 0)\n res.push_back(i + 1);\n }\n return res;\n }\n};" }, { "title": "Total Appeal of A String", "algo_input": "The appeal of a string is the number of distinct characters found in the string.\n\n\n\tFor example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.\n\n\nGiven a string s, return the total appeal of all of its substrings.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"abbca\"\nOutput: 28\nExplanation: The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.\n\n\nExample 2:\n\nInput: s = \"code\"\nOutput: 20\nExplanation: The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def appealSum(self, s: str) -> int:\n res, cur, prev = 0, 0, defaultdict(lambda: -1)\n for i, ch in enumerate(s):\n cur += i - prev[ch]\n prev[ch] = i\n res += cur\n return res ", "solution_js": "var appealSum = function(s) {\n let ans = 0, n = s.length;\n let lastIndex = Array(26).fill(-1);\n for (let i = 0; i < n; i++) {\n let charcode = s.charCodeAt(i) - 97;\n let lastIdx = lastIndex[charcode];\n ans += (n - i) * (i - lastIdx);\n lastIndex[charcode] = i;\n } \n return ans;\n};", "solution_java": "class Solution {\n public long appealSum(String s) {\n long res = 0;\n char[] cs = s.toCharArray();\n int n = cs.length;\n int[] pos = new int[26];\n Arrays.fill(pos, -1);\n for (int i = 0; i < n; ++i) {\n int j = cs[i] - 'a', prev = pos[j]; \n res += (i - prev) * (long) (n - i);\n pos[j] = i;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n\tlong long appealSum(string s) {\n\t\tint n = s.size();\n\t\tlong long ans = 0;\n\t\tfor(char ch='a';ch<='z';ch++) // we are finding the number of substrings containing at least 1 occurence of ch\n\t\t{\n\t\t\tint prev = 0; // prev will store the previous index of the charcter ch\n\t\t\tfor(int i=0;i List[int]:\n n = len(nums)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n return [] # No solution found", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nvar twoSum = function(nums, target) {\n var sol = [];\n var found = 0;\n for(let i = 0; i < nums.length; i ++) {\n for(let j = i + 1; j < nums.length; j ++) {\n if(nums[i] + nums[j] === target) {\n sol.push(i, j);\n found = 1;\n break;\n }\n }\n if(found == 1) return sol;\n }\n return sol;\n};", "solution_java": "class Solution {\n public int[] twoSum(int[] nums, int target) {\n int[] answer = new int[2];\n\t\t// Two for loops for selecting two numbers and check sum equal to target or not\n\t\t\n for(int i = 0; i < nums.length; i++){\n for(int j = i+1; j < nums.length; j++) {\n\t\t\t // j = i + 1; no need to check back elements it covers in i;\n if(nums[i] + nums[j] == target) {\n\t\t\t\t// Check sum == target or not\n answer[0] = i;\n answer[1] = j;\n return answer;\n }\n } \n }\n return null;\n }\n}", "solution_c": "class Solution {\npublic:\n vector twoSum(vector& nums, int target) {\n int n = nums.size();\n for (int i = 0; i < n - 1; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] + nums[j] == target) {\n return {i, j};\n }\n }\n }\n return {}; // No solution found\n }\n};" }, { "title": "Total Hamming Distance", "algo_input": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nGiven an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.\n\n \nExample 1:\n\nInput: nums = [4,14,2]\nOutput: 6\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n\n\nExample 2:\n\nInput: nums = [4,14,4]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t0 <= nums[i] <= 109\n\tThe answer for the given input will fit in a 32-bit integer.\n\n", "solution_py": "class Solution:\n def totalHammingDistance(self, arr: List[int]) -> int:\n\n total = 0\n for i in range(0,31):\n count = 0\n for j in arr :\n count+= (j >> i) & 1\n total += count*(len(arr)-count)\n return total", "solution_js": "var totalHammingDistance = function(nums) {\n let n = nums.length, ans = 0;\n for(let bit = 0; bit < 32; bit++) {\n let zeros = 0, ones = 0;\n for(let i = 0; i < n; i++) {\n ((nums[i] >> bit) & 1) ? ones++ : zeros++;\n }\n ans += zeros * ones;\n }\n return ans;\n};", "solution_java": "class Solution {\n public int totalHammingDistance(int[] nums) {\n int total = 0;\n int[][] cnt = new int[2][32];\n for (int i = 0; i < nums.length; i++) {\n for (int j = 0; j < 32; j++) {\n int idx = (nums[i] >> j) & 1;\n total += cnt[idx ^ 1][j];\n cnt[idx][j]++;\n }\n }\n return total;\n }\n}", "solution_c": "/*\nSo in the question we want to find out the \nnumber of difference of bits between each pair \nso in the brute force we will iterate over the vector \nand for every pair we will calculate the Hamming distance \nthe Hamming distance will be calculated by taking XOR between the two elements\nand then finding out the number of ones in the XOR of those two elements \nthe intuition behind this method is that XOR will contain 1's at those places \nwhere the corresponding bits of elements x & y are different \ntherefore we will add this count\nto our answer\n*/\nclass Solution {\npublic:\n int hammingDistance(int x, int y) {\n int XOR=x^y;\n \n int count=0;\n while(XOR){\n if(XOR&1)\n count++;\n \n XOR=XOR>>1;\n }\n return count;\n }\n \n int totalHammingDistance(vector& nums) {\n int ans=0;\n for(int i=0;i ListNode:\n head = list1\n for _ in range(a-1):\n head = head.next\n cur = head.next\n for _ in range(b-a):\n cur = cur.next\n head.next = list2\n while head.next:\n head = head.next\n if cur.next:\n head.next = cur.next\n return list1", "solution_js": "var mergeInBetween = function(list1, a, b, list2) {\n let start = list1;\n let end = list1;\n\n for (let i = 0; i <= b && start != null && end != null; i++) {\n if (i < a - 1) start = start.next;\n if (i <= b) end = end.next;\n }\n\n let tail = list2;\n\n while (tail.next != null) {\n tail = tail.next;\n }\n\n start.next = list2;\n tail.next = end;\n\n return list1;\n};", "solution_java": "class Solution {\n public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n ListNode left = list1;\n for (int i = 1; i < a; i++)\n left = left.next;\n \n ListNode middle = left;\n for (int i = a; i <= b; i++)\n middle = middle.next;\n \n\t\tleft.next = list2;\n while (list2.next != null)\n list2 = list2.next;\n \n list2.next = middle.next;\n return list1;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {\n \n int jump1 = 1;\n ListNode *temp1 = list1;\n while (jump1 < a){\n temp1 = temp1->next;\n jump1++;\n } //Gets the pointer to a\n \n\t\tint jump2 = 1;\n ListNode *temp2 = list1;\n while(jump2 <= b){\n temp2 = temp2->next;\n jump2++;\n } //Gets the pointer to b\n \n\t\tListNode *temp3=list2;\n while(temp3->next != NULL){\n temp3=temp3->next;\n } //Gets the pointer to the tail of list2\n \n\t\t\n\t\ttemp1->next=list2; //set the next pointer of a to the head of list2\n \n\t\ttemp3->next = temp2->next; //set next of tail of list2 to the pointer to b\n \n\t\treturn list1; //return the original list i.e. list1\n \n }\n};" }, { "title": "IPO", "algo_input": "Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.\n\nYou are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.\n\nInitially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.\n\nPick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.\n\nThe answer is guaranteed to fit in a 32-bit signed integer.\n\n \nExample 1:\n\nInput: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput: 4\nExplanation: Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n\n\nExample 2:\n\nInput: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput: 6\n\n\n \nConstraints:\n\n\n\t1 <= k <= 105\n\t0 <= w <= 109\n\tn == profits.length\n\tn == capital.length\n\t1 <= n <= 105\n\t0 <= profits[i] <= 104\n\t0 <= capital[i] <= 109\n\n", "solution_py": "from heapq import heappush, heappop, nlargest\nclass Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n if w >= max(capital):\n return w + sum(nlargest(k, profits))\n \n projects = [[capital[i],profits[i]] for i in range(len(profits))]\n projects.sort(key=lambda x: x[0])\n \n heap = []\n \n for i in range(k):\n while projects and projects[0][0] <= w:\n heappush(heap, -1*projects.pop(0)[1])\n \n if not heap:\n break\n p = -heappop(heap)\n w += p\n return w", "solution_js": "var findMaximizedCapital = function(k, w, profits, capital) {\n let capitals_asc_queue = new MinPriorityQueue();\n let profits_desc_queue = new MaxPriorityQueue();\n for (let i = 0; i < capital.length; i++)\n capitals_asc_queue.enqueue([capital[i], profits[i]], capital[i]);\n \n\tfor (let i = 0; i < k; i++) {\n while (!capitals_asc_queue.isEmpty() && capitals_asc_queue.front().element[0] <=w ) {\n let el = capitals_asc_queue.dequeue().element;\n profits_desc_queue.enqueue(el, el[1]);\n }\n if (profits_desc_queue.isEmpty()) return w;\n w += profits_desc_queue.dequeue().element[1];\n }\n return w;\n}", "solution_java": "class Solution {\n\tstatic int[][] dp;\n\n\tpublic int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {\n\t\tdp = new int[k + 1][profits.length + 1];\n\t\tfor (int[] row : dp) {\n\t\t\tArrays.fill(row, -1);\n\t\t}\n\t\treturn w + help(k, w, 0, profits, capital);\n\t}\n\n\tpublic int help(int k, int w, int i, int[] profits, int[] capital) {\n\t\tif (k == 0 || i >= profits.length)\n\t\t\treturn 0;\n\t\tif (dp[k][i] != -1)\n\t\t\treturn dp[k][i];\n\t\tint res = Integer.MIN_VALUE;\n\t\tif (capital[i] <= w) {\n\t\t\tres = Math.max(res, Math.max(profits[i] + help(k - 1, w + profits[i], i + 1, profits, capital),\n\t\t\t\t\thelp(k, w, i + 1, profits, capital)));\n\t\t} else {\n\t\t\tres = Math.max(res, help(k, w, i + 1, profits, capital));\n\t\t}\n\t\treturn dp[k][i] = res;\n\t}\n}", "solution_c": "class Solution {\npublic:\n int findMaximizedCapital(int k, int w, vector& profits, vector& capital) {\n priority_queue, vector>, greater>> pqsg;\n priority_queue> pqgs;\n int n = capital.size();\n for(int i = 0; i < n; i++)\n {\n //int val = profit[i]-capital[i];\n if(capital[i] <= w)\n {\n pqgs.push({profits[i],capital[i]});\n }\n else if(capital[i] > w)\n {\n pqsg.push({capital[i],profits[i]});\n }\n }\n while(k-- && !pqgs.empty())\n {\n pair tmp = pqgs.top();\n w += tmp.first;\n pqgs.pop();\n while(!pqsg.empty() && pqsg.top().first <= w)\n {\n pqgs.push({pqsg.top().second,pqsg.top().first});\n pqsg.pop();\n }\n }\n return w;\n }\n};" }, { "title": "Design an ATM Machine", "algo_input": "There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.\n\nWhen withdrawing, the machine prioritizes using banknotes of larger values.\n\n\n\tFor example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.\n\tHowever, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.\n\n\nImplement the ATM class:\n\n\n\tATM() Initializes the ATM object.\n\tvoid deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.\n\tint[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).\n\n\n \nExample 1:\n\nInput\n[\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]\nOutput\n[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]\n\nExplanation\nATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.\n\n \nConstraints:\n\n\n\tbanknotesCount.length == 5\n\t0 <= banknotesCount[i] <= 109\n\t1 <= amount <= 109\n\tAt most 5000 calls in total will be made to withdraw and deposit.\n\tAt least one call will be made to each function withdraw and deposit.\n\n", "solution_py": "class ATM:\n def __init__(self):\n self.cash = [0] * 5\n self.values = [20, 50, 100, 200, 500]\n\n def deposit(self, banknotes_count: List[int]) -> None:\n for i, n in enumerate(banknotes_count):\n self.cash[i] += n\n\n def withdraw(self, amount: int) -> List[int]:\n res = []\n for val, n in zip(self.values[::-1], self.cash[::-1]):\n need = min(n, amount // val)\n res = [need] + res\n amount -= (need * val)\n if amount == 0:\n self.deposit([-x for x in res])\n return res\n else:\n return [-1]", "solution_js": "var ATM = function() {\n this.bankNotes = new Array(5).fill(0)\n this.banksNotesValue = [20, 50, 100, 200, 500]\n};\n\n/**\n * @param {number[]} banknotesCount\n * @return {void}\n */\nATM.prototype.deposit = function(banknotesCount) {\n for (let i = 0; i < 5; i++) {\n this.bankNotes[i] += banknotesCount[i]\n }\n return this.bankNotes\n};\n\n/**\n * @param {number} amount\n * @return {number[]}\n */\nATM.prototype.withdraw = function(amount) {\n let remain = amount\n let usedBankNotes = new Array(5).fill(0)\n let temp = [...this.bankNotes]\n for (let i = 4; i >= 0; i--) {\n if (temp[i] > 0 && remain >= this.banksNotesValue[i]) {\n const bankNote = Math.floor(remain / this.banksNotesValue[i])\n const maxCanUse = Math.min(temp[i], bankNote)\n usedBankNotes[i] = maxCanUse\n temp[i] -= maxCanUse\n\n remain -= maxCanUse * this.banksNotesValue[i]\n }\n }\n\n if (remain > 0) {\n return [-1]\n } else {\n this.bankNotes = temp\n return usedBankNotes\n }\n};\n\n/**\n * Your ATM object will be instantiated and called as such:\n * var obj = new ATM()\n * obj.deposit(banknotesCount)\n * var param_2 = obj.withdraw(amount)\n */", "solution_java": "class ATM {\n\tlong[] notes = new long[5]; // Note: use long[] instead of int[] to avoid getting error in large testcases\n\tint[] denoms;\n\tpublic ATM() {\n\t\tdenoms = new int[]{ 20,50,100,200,500 }; // create an array to represent money value.\n\t}\n\n\tpublic void deposit(int[] banknotesCount) {\n\t\tfor(int i = 0; i < banknotesCount.length; i++){\n\t\t\tnotes[i] += banknotesCount[i]; // add new deposit money to existing\n\t\t}\n\t}\n\n\tpublic int[] withdraw(int amount) { \n\t\tint[] result = new int[5]; // create result array to store quantity of each notes we will be using to withdraw \"amount\"\n\t\tfor(int i = 4; i >= 0; i--){\n\t\t\tif(amount >= denoms[i] ){ \n\t\t\t\tint quantity = (int) Math.min(notes[i], amount / denoms[i]); // pick the minimum quanity. because if say, amount/denoms[i] gives 3 but you only have 1 note. so you have to use 1 only instead of 3 \n\t\t\t\tamount -= denoms[i] * quantity; // amount left = 100\n\t\t\t\tresult[i] = quantity;\n\t\t\t}\n\t\t}\n\t\tif(amount != 0){ return new int[]{-1}; }\n\t\tfor(int i = 0; i < 5; i++){ notes[i] -= result[i]; } // deduct the quantity we have used.\n\t\treturn result;\n\t}\n}", "solution_c": "class ATM {\npublic:\n long long bank[5] = {}, val[5] = {20, 50, 100, 200, 500};\n void deposit(vector banknotesCount) {\n for (int i = 0; i < 5; ++i)\n bank[i] += banknotesCount[i];\n }\n vector withdraw(int amount) {\n vector take(5);\n for (int i = 4; i >= 0; --i) {\n take[i] = min(bank[i], amount / val[i]);\n amount -= take[i] * val[i];\n }\n if (amount)\n return { -1 };\n for (int i = 0; i < 5; ++i)\n bank[i] -= take[i]; \n return take;\n }\n};" }, { "title": "Number of Enclaves", "algo_input": "You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.\n\nA move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.\n\nReturn the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.\n\n \nExample 1:\n\nInput: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput: 3\nExplanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.\n\n\nExample 2:\n\nInput: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput: 0\nExplanation: All 1s are either on the boundary or can reach the boundary.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 500\n\tgrid[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def recursion(self, grid, row, col, m, n):\n if 0<=row int:\n m, n = len(grid), len(grid[0])\n if not m or not n:\n return 0\n # mark all boundary lands and neighbors with 0\n for row in range(m):\n self.recursion(grid, row, 0, m, n)\n self.recursion(grid, row, n-1, m, n)\n \n for col in range(n):\n self.recursion(grid, 0, col, m, m)\n self.recursion(grid, m-1, col, m, n)\n \n result = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n result += 1\n \n \n return result", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar numEnclaves = function(grid) {\n\n let count = 0, rowLength = grid.length, colLength = grid[0].length\n\n const updateBoundaryLand = (row,col) => {\n if(grid?.[row]?.[col]){\n grid[row][col] = 0\n updateBoundaryLand(row + 1,col)\n updateBoundaryLand(row - 1,col)\n updateBoundaryLand(row,col + 1)\n updateBoundaryLand(row,col - 1)\n\n }\n }\n\n for(let i=0;i=grid.length||coldash>=grid[0].length||\n grid[rowdash][coldash]==0)\n {\n continue;\n }\n\n if(grid[rowdash][coldash]==1)\n {\n dfs(grid,rowdash,coldash);\n }\n\n }\n\n }\n}", "solution_c": "class Solution {\npublic:\n int numEnclaves(vector>& grid) {\n for(int i=0;i> q;\n q.push({i,j});\n while(!q.empty())\n {\n vector a;\n a=q.front();\n q.pop();\n grid[a[0]][a[1]]=0;\n if(a[0]+1=0 && grid[a[0]-1][a[1]]==1)\n {\n q.push({a[0]-1,a[1]});\n grid[a[0]-1][a[1]]=0;\n }\n if(a[1]-1>=0 && grid[a[0]][a[1]-1]==1)\n {\n q.push({a[0],a[1]-1});\n grid[a[0]][a[1]-1]=0;\n }\n }\n }\n }\n }\n int m=0;\n for(int i=0;i bool:\n directions = [False] * 8\n moves = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),\n (-1, -1), (0, -1), (1, -1)]\n opposite_color = \"W\" if color == \"B\" else \"B\"\n\n for d in range(8):\n r, c = rMove + moves[d][0], cMove + moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8 and board[r][c] == opposite_color:\n directions[d] = True\n\n for step in range(2, 8):\n if not any(d for d in directions):\n return False\n for d in range(8):\n if directions[d]:\n r, c = rMove + step * moves[d][0], cMove + step * moves[d][1]\n if 0 <= r < 8 and 0 <= c < 8:\n if board[r][c] == color:\n return True\n elif board[r][c] == \".\":\n directions[d] = False\n else:\n directions[d] = False\n return False", "solution_js": "var checkMove = function(board, rMove, cMove, color) {\n const moves = [-1, 0, 1];\n \n let count = 0;\n \n for (let i = 0; i < 3; ++i) {\n for (let j = 0; j < 3; ++j) {\n if (i === 1 && j === 1) continue;\n \n const rowDir = moves[i];\n const colDir = moves[j];\n \n if (isLegal(rMove, cMove, rowDir, colDir, color, 1)) return true;\n }\n }\n \n return false;\n \n function withinBound(row, col) {\n return row >= 0 && col >= 0 && row < 8 && col < 8;\n }\n \n function isLegal(currRow, currCol, rowDir, colDir, startColor, length) {\n if (!withinBound(currRow, currCol)) return false; // we went passed the boundaries\n if (board[currRow][currCol] === startColor) return length >= 3; // we seen another start color\n if (board[currRow][currCol] === \".\" && length > 1) return false;\n\n return isLegal(currRow + rowDir, currCol + colDir, rowDir, colDir, startColor, length + 1);\n }\n};", "solution_java": "class Solution {\n public boolean checkMove(char[][] board, int rMove, int cMove, char color) {\n\n int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};\n\n for(int[] d : direction)\n {\n if(dfs(board,rMove,cMove,color,d,1))\n return true;\n }\n return false;\n }\n\n public boolean dfs(char[][] board, int r, int c, char color,int[] direcn,int len)\n {\n\n int nr = r + direcn[0];\n int nc = c + direcn[1];\n\n if( nr<0 || nc<0 || nr>7 || nc>7) return false;\n\n if(board[nr][nc] == color)\n {\n if(len>=2) return true;\n else\n return false;\n }\n else\n {\n if(board[nr][nc] == '.')\n { \n return false;\n }\n return dfs(board,nr,nc,color,direcn,len+1);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n bool inBoard(vector>& board, int x, int y) {\n return x >= 0 && x < board.size() && y >= 0 && y < board[0].size();\n }\n \n bool isLegal(vector>& board, int x, int y, char color) {\n if (color == 'B') return board[x][y] == 'W';\n if (color == 'W') return board[x][y] == 'B';\n return false;\n }\n \n bool checkMove(vector>& board, int rMove, int cMove, char color) {\n vector dir_x = {0, 0, 1, 1, 1, -1, -1, -1}, dir_y = {1, -1, 1, -1, 0, 1, -1, 0};\n for (int i = 0; i < 8; i++) {\n int x = rMove + dir_x[i], y = cMove + dir_y[i], count = 0;\n while (inBoard(board, x, y) && isLegal(board, x, y, color)) {\n x += dir_x[i], y += dir_y[i];\n count++;\n }\n if (inBoard(board, x, y) && board[x][y] == color && count > 0) return true;\n }\n return false;\n }\n};" }, { "title": "Russian Doll Envelopes", "algo_input": "You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.\n\nOne envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.\n\nReturn the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\n\nNote: You cannot rotate an envelope.\n\n \nExample 1:\n\nInput: envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput: 3\nExplanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).\n\n\nExample 2:\n\nInput: envelopes = [[1,1],[1,1],[1,1]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= envelopes.length <= 105\n\tenvelopes[i].length == 2\n\t1 <= wi, hi <= 105\n\n", "solution_py": "from bisect import bisect_left\nclass Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n envelopes = sorted(envelopes, key= lambda x:(x[0],-x[1]))\n rst = []\n for _,h in envelopes:\n i = bisect_left(rst,h)\n if i == len(rst):\n rst.append(h)\n else:\n rst[i] = h\n return len(rst)", "solution_js": "const binarySearch = (arr, target) => {\n let left = 0;\n let right = arr.length - 1;\n \n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n if (arr[mid] === target) {\n return mid;\n }\n if (arr[mid] < target) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n \n return left;\n}\n\nvar maxEnvelopes = function(envelopes) {\n envelopes.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]);\n const sub = [envelopes[0][1]];\n \n for (let envelope of envelopes) {\n if (envelope[1] > sub[sub.length - 1]) {\n sub.push(envelope[1]);\n } else {\n const replaceIndex = binarySearch(sub, envelope[1]);\n sub[replaceIndex] = envelope[1];\n }\n }\n \n return sub.length;\n};", "solution_java": "class Solution {\n public int maxEnvelopes(int[][] envelopes) {\n\t\t//sort the envelopes considering only width\n Arrays.sort(envelopes, new sortEnvelopes());\n\t\t\n\t\t//Now this is a Longest Increasing Subsequence problem on heights\n\t\t//tempList to store the temporary elements, size of this list will be the length of LIS \n ArrayList tempList = new ArrayList<>();\n tempList.add(envelopes[0][1]);\n\t\t\n for(int i=1; itempList.get(tempList.size()-1)){\n tempList.add(envelopes[i][1]);\n } else{\n\t\t\t//if the element is smaller than the largest(last because it is sorted) element of tempList, replace the largest smaller element of tempList with it..\n\t\t\t//ex->(assume if envelopes[i][1] is 4), then >>[1,7,8] will become [1,4,8]<<\n int index = lowerBound(tempList, envelopes[i][1]);\n tempList.set(index, envelopes[i][1]);\n }\n }\n return tempList.size();\n }\n \n\t//finding the index of greatest smaller element \n public int lowerBound(ArrayList list, int search){\n int start = 0;\n int end = list.size()-1;\n while(start {\n public int compare(int[] a, int[] b){\n if(a[0] == b[0]){\n\t\t//to ignore the duplicates, we are sorting such that, for same width-> element with \n\t\t//largest height would be considered first, in this way all the other smaller heights would\n\t\t//be ignored\n return b[1] - a[1];\n } else{\n return a[0] - b[0];\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int maxEnvelopes(vector>& envelopes) {\n int n = envelopes.size();\n sort(envelopes.begin(), envelopes.end(), [](auto &l, auto &r)\n {\n return l[0] == r[0] ? l[1] > r[1] : l[0] < r[0];\n });\n int len = 0;\n for(auto& cur: envelopes)\n {\n if(len==0 || envelopes[len-1][1] < cur[1])\n envelopes[len++] = cur;\n else\n *lower_bound(envelopes.begin(), envelopes.begin()+ len, cur, [](auto &l, auto &r)\n {\n return l[1] < r[1];\n }) = cur;\n }\n return len;\n }\n};" }, { "title": "Maximum Binary String After Change", "algo_input": "You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:\n\n\n\tOperation 1: If the number contains the substring \"00\", you can replace it with \"10\".\n\n\t\n\t\tFor example, \"00010\" -> \"10010\"\n\t\n\t\n\tOperation 2: If the number contains the substring \"10\", you can replace it with \"01\".\n\t\n\t\tFor example, \"00010\" -> \"00001\"\n\t\n\t\n\n\nReturn the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.\n\n \nExample 1:\n\nInput: binary = \"000110\"\nOutput: \"111011\"\nExplanation: A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"\n\n\nExample 2:\n\nInput: binary = \"01\"\nOutput: \"01\"\nExplanation: \"01\" cannot be transformed any further.\n\n\n \nConstraints:\n\n\n\t1 <= binary.length <= 105\n\tbinary consist of '0' and '1'.\n\n", "solution_py": "class Solution:\n def maximumBinaryString(self, binary: str) -> str:\n zero = binary.count('0') # count number of '0'\n zero_idx = binary.index('0') if zero > 0 else 0 # find the index of fist '0' if exists\n one = len(binary) - zero_idx - zero # count number of '1' (not including leading '1's)\n return f\"{binary[:zero_idx]}{'1'*(zero-1)}{'0'*min(zero, 1)}{'1'*one}\"", "solution_js": "/**\n * @param {string} binary\n * @return {string}\n */\nvar maximumBinaryString = function(binary) {\n /*\n 10 -> 01 allows us to move any zero to left by one position\n 00 -> 10 allows us to convert any consicutive 00 to 10\n So we can collect all the zeros together then convert them in 1 except for the rightmost 0\n We will club all the zeros togegher on the rightmost possition, to achieve the biggest value, then covert them into 1 except for the rightmost 0\n So we need to choose indexOfFirstZero as the starting possition of the group of zeros\n If there is no 0 then given string is the maximum possible string\n If there are 1 or more zeros\n Then there will be only 1 zero in the answer\n Position of this will be indexOfFirstZero in given string + countOfZeros - 1\n */\n let firstZeroIndex=-1,zeroCount=0,ans=\"\";\n for(let i=0;i=0;i--) {\n if(binary[i]=='0') {\n z_count++;\n z_index = i;\n binary[i] = '1'; //changing all occurances to 1\n }\n }\n if(z_index!=-1) //to check if there is atleast 1 zero\n {\n binary[z_index+z_count-1] = '0'; //this is the only zero present\n // -1 because the only zero is also included in zero count \n }\n return binary;\n }\n};" }, { "title": "Jump Game III", "algo_input": "Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0.\n\nNotice that you can not jump outside of the array at any time.\n\n \nExample 1:\n\nInput: arr = [4,2,3,0,3,1,2], start = 5\nOutput: true\nExplanation: \nAll possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3 \n\n\nExample 2:\n\nInput: arr = [4,2,3,0,3,1,2], start = 0\nOutput: true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3\n\n\nExample 3:\n\nInput: arr = [3,0,2,1,2], start = 2\nOutput: false\nExplanation: There is no way to reach at index 1 with value 0.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 5 * 104\n\t0 <= arr[i] < arr.length\n\t0 <= start < arr.length\n\n", "solution_py": "class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n vis = [0]*len(arr)\n q = deque() \n q.append(start) \n while q:\n cur = q.popleft() \n print(cur)\n vis[cur] = 1\n if arr[cur] == 0:\n return True\n if cur+arr[cur]=0 and vis[cur-arr[cur]] == 0: \n q.append(cur-arr[cur]) \n return False\n\n ", "solution_js": "/**\n * @param {number[]} arr\n * @param {number} start\n * @return {boolean}\n */\nvar canReach = function(arr, start) {\n let queue = [start];\n while(queue.length) {\n let index = queue.shift();\n if(index >= 0 && index < arr.length && arr[index] >=0 ){\n if(arr[index] === 0)return true;\n let move = arr[index]\n arr[index] = -1 \n queue.push(index +move , index-move)\n }\n }\n return false;\n};", "solution_java": "class Solution {\n public boolean canReach(int[] arr, int start) {\n int n = arr.length;\n boolean[] vis = new boolean[n];\n Queue q = new LinkedList<>();\n q.add(start);\n while(!q.isEmpty()){\n int size = q.size();\n while(size-- > 0){\n int curr = q.poll();\n if(vis[curr])\n continue;\n if(arr[curr] == 0)\n return true;\n if(curr+arr[curr] < n)\n q.add(curr+arr[curr]);\n if(curr-arr[curr] >= 0)\n q.add(curr-arr[curr]);\n vis[curr] = true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool dfs(int curr, vector& arr, vector& visited, int size) {\n\t\t// edge cases - we can't go outside the array size and if the curr index is alredy visited it will repeat same recursion all over again so we can return false in that case too.\n if(curr < 0 || curr >= size || visited[curr])\n return false;\n\t\t// If we reach zero we can return true\n if(arr[curr] == 0)\n return true;\n visited[curr] = true;\n\t\t// do dfs in left and right and return two if any of the two paths end up reaching to zero\n return dfs(curr - arr[curr], arr, visited, size) || \n dfs(curr + arr[curr], arr, visited, size);\n }\n \n bool canReach(vector& arr, int start) {\n int size = arr.size();\n vector visited(size, false);\n return dfs(start, arr, visited, size);\n }\n};" }, { "title": "Delete Nodes And Return Forest", "algo_input": "Given the root of a binary tree, each node in the tree has a distinct value.\n\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\n\nReturn the roots of the trees in the remaining forest. You may return the result in any order.\n\n \nExample 1:\n\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\n\nExample 2:\n\nInput: root = [1,2,4,null,3], to_delete = [3]\nOutput: [[1,2,4]]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the given tree is at most 1000.\n\tEach node has a distinct value between 1 and 1000.\n\tto_delete.length <= 1000\n\tto_delete contains distinct values between 1 and 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 def traverse(self,node,par):\n if node:\n self.parent[node.val] = par\n self.traverse(node.left,node)\n self.traverse(node.right,node)\n \n def deleteNode(self,toDelete):\n node = None\n par = self.parent[toDelete]\n if par.val == toDelete:\n node = par\n elif par.left and par.left.val == toDelete:\n node = par.left\n elif par.right and par.right.val == toDelete:\n node = par.right\n if node.left: \n self.unique[node.left] = True\n if node.right: \n self.unique[node.right] = True\n \n if node in self.unique: self.unique.pop(node)\n if node != self.parent[toDelete]:\n if par.left == node: par.left = None\n else: par.right = None\n\n \n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n self.parent = {}\n self.traverse(root,root)\n self.unique = {root:True}\n for node in to_delete:\n self.deleteNode(node)\n return self.unique", "solution_js": "var delNodes = function(root, to_delete) {\n if(!root) return [];\n\n to_delete = new Set(to_delete);\n // know how to delete\n // while deleting add new nodes to same algo\n const ans = [];\n const traverse = (r = root, p = null, d = 0) => {\n if(!r) return null;\n if(to_delete.has(r.val)) {\n if(p != null) {\n p[d == -1 ? 'left' : 'right'] = null;\n }\n traverse(r.left, null, 0);\n traverse(r.right, null, 0);\n } else {\n if(p == null) ans.push(r);\n traverse(r.left, r, -1);\n traverse(r.right, r, 1);\n }\n }\n traverse();\n return ans;\n};", "solution_java": "class Solution {\n\n HashMap> parent_val_child_nodes_map;\n HashMap child_val_parent_node_map;\n\n public List delNodes(TreeNode root, int[] to_delete) {\n\n // initialize map\n parent_val_child_nodes_map = new HashMap<> ();\n child_val_parent_node_map = new HashMap<> ();\n\n // fill map\n dfsFillMap(root);\n\n // traverse to_delete to find those that do not have parent after deleting it\n List res = new ArrayList<> ();\n\n // actually deleting nodes\n for (int delete_val : to_delete) {\n\n // if the node has parent\n if (child_val_parent_node_map.containsKey(delete_val)) {\n TreeNode parent_node = child_val_parent_node_map.get(delete_val);\n if (parent_node.left != null && parent_node.left.val == delete_val) {\n parent_node.left = null;\n }\n\n if (parent_node.right != null && parent_node.right.val == delete_val) {\n parent_node.right = null;\n }\n }\n }\n\n // add root to the list first because root has no parent\n // only if root.val is not in to_delete\n if (!Arrays.stream(to_delete).anyMatch(j -> j == root.val)) {\n res.add(root);\n }\n\n // add other nodes that do not have parent\n for (int delete_val : to_delete) {\n if (parent_val_child_nodes_map.containsKey(delete_val)) {\n for (int i = 0; i < parent_val_child_nodes_map.get(delete_val).size(); i++) {\n\n // make sure the add node is not in to_delete\n int child_node_val = parent_val_child_nodes_map.get(delete_val).get(i).val;\n if (!Arrays.stream(to_delete).anyMatch(j -> j == child_node_val)) {\n res.add(parent_val_child_nodes_map.get(delete_val).get(i));\n }\n }\n }\n }\n\n return res;\n }\n\n public void dfsFillMap(TreeNode root) {\n\n if (root == null) {\n return;\n }\n\n if (root.left != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.left);\n\n child_val_parent_node_map.putIfAbsent(root.left.val, root);\n dfsFillMap(root.left);\n }\n\n if (root.right != null) {\n parent_val_child_nodes_map.putIfAbsent(root.val, new ArrayList<> ());\n parent_val_child_nodes_map.get(root.val).add(root.right);\n\n child_val_parent_node_map.putIfAbsent(root.right.val, root);\n dfsFillMap(root.right);\n }\n\n return;\n }\n}", "solution_c": "class Solution {\n void solve(TreeNode* root,TreeNode* prev,unordered_map& mp,int left,vector& ans){\n if(root==NULL)\n return;\n\n int f=0;\n\n solve(root->left,root,mp,1,ans);\n solve(root->right,root,mp,0,ans);\n\n if(mp.find(root->val)!=mp.end()){\n f=1;\n if(root->right)\n ans.push_back(root->right);\n // cout<left->val<<\" \";}\n if(root->left)\n ans.push_back(root->left);\n // cout<right->val<<\" \";}\n }\n\n if(f==1){\n if(left)\n prev->left=NULL;\n else\n prev->right=NULL;\n }\n }\n\npublic:\n vector delNodes(TreeNode* root, vector& to_delete) {\n if(root==NULL)\n return {};\n\n unordered_map mp;\n for(int i=0;i ans;\n\n TreeNode* dummy=new TreeNode(-1);\n dummy->left=root;\n\n solve(dummy->left,dummy,mp,1,ans);\n if(dummy->left)\n ans.push_back(root);\n\n return ans;\n }\n};\n ```" }, { "title": "Count Good Numbers", "algo_input": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).\n\n\n\tFor example, \"2582\" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even.\n\n\nGiven an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.\n\nA digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\n\n\nExample 2:\n\nInput: n = 4\nOutput: 400\n\n\nExample 3:\n\nInput: n = 50\nOutput: 564908303\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1015\n\n", "solution_py": "class Solution:\n def countGoodNumbers(self, n: int) -> int:\n ans = 1\n rem = n % 2\n n -= rem\n ans = pow(20, n//2, 10**9 + 7)\n if rem == 1:\n ans *= 5\n return ans % (10**9 + 7)", "solution_js": "class Math1 {\n\n // https://en.wikipedia.org/wiki/Modular_exponentiation\n static modular_pow(base, exponent, modulus) {\n if (modulus === 1n)\n return 0n\n let result = 1n\n base = base % modulus\n while (exponent > 0n) {\n if (exponent % 2n == 1n)\n result = (result * base) % modulus\n exponent = exponent >> 1n\n base = (base * base) % modulus\n }\n return result\n }\n\n}\n\nvar countGoodNumbers = function(n) {\n // NOTE: 0n, 1n, 2n, 3n, 4n, 5n are numbers in BigInt\n\n n = BigInt(n); // convert to BigInt, to avoid no rounding issues\n\n const odds = n / 2n,\n evens = n - odds,\n MOD = BigInt(Math.pow(10, 9) + 7)\n\n // from wikipedia\n return (Math1.modular_pow(4n, odds, MOD) * Math1.modular_pow(5n, evens, MOD)) % MOD;\n};", "solution_java": "class Solution {\n int mod=(int)1e9+7;\n public int countGoodNumbers(long n) {\n long first=(n%2==0?(n/2):(n/2)+1);//deciding n/2 or n/2+1 depending on n is even or odd\n long second=n/2;//second power would be n/2 only irrespective of even or odd\n long mul1=power(5,first)%mod;//5 power n/2\n long mul2=power(4,second)%mod;//4 power n/2\n long ans=1;\n ans=(ans*mul1)%mod;//computing total product\n ans=(second!=0)?(ans*mul2)%mod:ans;//computing total product\n return (int)(ans%mod);\n }\n public long power(long x,long y){// this method computes pow(x,y) in O(logn) using divide & conquer\n long temp;\n if(y==0) return 1;//base case (x power 0 = 1)\n temp=power(x,y/2);//computing power for pow(x,y/2) -> divide & conquer step\n if(y%2==0) return (temp*temp)%mod; //using that result of subproblem (2 power 2 = 2 power 1 * 2 power 1)\n else return (x*temp*temp)%mod;//using that result of subproblem (2 power 3 = 2 power 1 * 2 power 1 * 2)\n\t\t// if y is odd, x power y = x power y/2 * x power y/2 * x\n\t\t// if y is even, x power y = x power y/2 * x power y/2\n }\n}", "solution_c": "// Approach :-> This is question of combination\n// if n as large no....\n// 0 1 2 3 4 5 6 7 8 9 10 11 . . . . . n\n// 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 * 5 * 4 . . . . . n/4 times of 4 and n/4 times of 5;\n//so calculate 5*4 = 20 -------> 20 * 20 * 20 * . . . . .. n/2 times\n//so calcultae pow(20,n/2)\n// if n is even return pow(20,n/2)\n// if n is odd return 5*pow(20,n/2) beacause if n is odd then one 5 is left out\n// we can easily calculate pow(x,y) in log(y) times\n// durign calculation take care about mod\nclass Solution {\npublic:\n int mod = 1000000007;\n long long solve(long long val,long long pow){ // calculatin pow in log(n) time\n if(pow==0) return 1;\n\n if(pow%2==0){\n return solve((val*val)%mod,pow/2)%mod;\n }\n else\n return (val*solve((val*val)%mod,pow/2))%mod;\n\n }\n int countGoodNumbers(long long n) {\n // even means 5 options\n // odd means 4 option\n\n long long pow = n/2; // calculate no of times 5*4 means 20 occurs\n\n long long ans = solve(20,pow); // calculate power(20,pow)\n\n if(n%2==0){ // if n is even then 5 and 4 occur same no of time n/2\n return ans;\n }\n return ((5*ans) % mod); // if n is odd then 5 occurs n/2+1 times means one extra times so return ans*5 and don't forgot to mod\n }\n};" }, { "title": "Smallest Sufficient Team", "algo_input": "In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.\n\nConsider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n\n\n\tFor example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].\n\n\nReturn any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n\nIt is guaranteed an answer exists.\n\n \nExample 1:\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\nExample 2:\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n\n \nConstraints:\n\n\n\t1 <= req_skills.length <= 16\n\t1 <= req_skills[i].length <= 16\n\treq_skills[i] consists of lowercase English letters.\n\tAll the strings of req_skills are unique.\n\t1 <= people.length <= 60\n\t0 <= people[i].length <= 16\n\t1 <= people[i][j].length <= 16\n\tpeople[i][j] consists of lowercase English letters.\n\tAll the strings of people[i] are unique.\n\tEvery skill in people[i] is a skill in req_skills.\n\tIt is guaranteed a sufficient team exists.\n\n", "solution_py": "from collections import defaultdict\nfrom functools import lru_cache\n\nclass Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n N = len(req_skills)\n skills = {skill: i for i, skill in enumerate(req_skills)}\n people_mask = defaultdict(int)\n for i, cur_skills in enumerate(people):\n mask = 0\n for skill in cur_skills:\n mask |= 1<= self.res:\n return\n dfs(i+1, l, mask)\n self.path.append(i)\n if mask & people_mask[i] != people_mask[i]: dfs(i+1, l+1, mask | people_mask[i])\n self.path.pop()\n dfs(0,0,0)\n return self.respath", "solution_js": "/**\n * @param {string[]} req_skills\n * @param {string[][]} people\n * @return {number[]}\n */\nvar smallestSufficientTeam = function(req_skills, people) {\n \n const skillIndexMap = new Map();\n \n req_skills.forEach((skill, index) => skillIndexMap.set(skill,index) );\n \n const skillTeamMap = new Map([[0, []]]);\n \n people.forEach( (skills, index) => {\n \n let hisSkills = 0;\n \n for (const skill of skills) {\n hisSkills |= 1 << skillIndexMap.get(skill);\n }\n \n for (const [currSkill, team] of skillTeamMap) {\n \n const totalSkills = currSkill | hisSkills;\n \n if (totalSkills === currSkill) {\n continue;\n }\n \n if ( \n !skillTeamMap.has(totalSkills) || \n team.length + 1 < skillTeamMap.get(totalSkills).length\n ) { \n skillTeamMap.set(totalSkills, [...team, index])\n } \n }\n });\n \n return skillTeamMap.get( (1<> people) {\n int N = 1 << req_skills.length, INF = (int)1e9;\n int[] parent = new int[N];\n int[] who = new int[N];\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0] = 0;\n for (int i = 0; i < N; i++){\n if (dp[i]!=INF){ // valid state \n for (int k = 0; k < people.size(); k++){\n int cur = i;\n for (int j = 0; j < req_skills.length; j++){\n for (String skill : people.get(k)){\n if (req_skills[j].equals(skill)){\n cur |= 1<dp[i]+1){ // replace if better\n dp[cur]=dp[i]+1;\n parent[cur]=i;\n who[cur]=k;\n }\n }\n }\n }\n int[] ans = new int[dp[N-1]];\n for (int i = 0,cur=N-1; i < ans.length; i++){\n ans[i]=who[cur];\n cur=parent[cur];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector smallestSufficientTeam(vector& req_skills, vector>& people) {\n vector mask(people.size(), 0);\n for(int i=0; i dp(1<> save(1< int:\n\t\tcounter=Counter(nums)\n\t\t# values=set(nums)\n\t\tres=0\n\t\t# if len(values)==1:return 0\n\t\tfor num in nums:\n\t\t\tif num+1 in counter or num-1 in counter:\n\t\t\t\tres=max(res,counter[num]+counter.get(num+1,0))\n\t\t\t\tres=max(res,counter[num]+counter.get(num-1,0))\n\n\t\treturn res\n\"\"", "solution_js": "var findLHS = function(nums) {\n let countNumber = {};\n let result = [];\n for (let i=0; imaxLen)\n maxLen=b-a+1;\n }\n }\n return maxLen;\n }\n}", "solution_c": "class Solution {\npublic:\n int findLHS(vector& nums)\n {\n map m;\n for(int i=0;ifirst-x==1)\n {\n ans=max(ans,y+i->second);\n }\n x=i->first;\n y=i->second;\n }\n return ans;\n\n }\n};\n//if you like the solution plz upvote." }, { "title": "Maximum XOR After Operations", "algo_input": "You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).\n\nNote that AND is the bitwise AND operation and XOR is the bitwise XOR operation.\n\nReturn the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.\n\n \nExample 1:\n\nInput: nums = [3,2,4,6]\nOutput: 7\nExplanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.\n\nExample 2:\n\nInput: nums = [1,2,3,9,2]\nOutput: 11\nExplanation: Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 108\n\n", "solution_py": "class Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n res=0\n for i in nums:\n res |= i\n return res", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumXOR = function(nums) {\n return nums.reduce((acc, cur) => acc |= cur, 0);\n};", "solution_java": "class Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int i=0; i& nums) {\n int res = 0;\n for (int i=0; i int:\n d=dict()\n for i in dominoes:\n i.sort() #Just to make everything equal and comparable\n if(tuple(i) in d.keys()): #In python, lists are unhashable so converted the list into tuples\n d[tuple(i)]+=1\n else:\n d[tuple(i)]=1\n count=0\n for x,y in d.items():\n if(y>1):\n\t\t\t\tcount+=y*(y-1)//2 #To check the number of pairs, if 2 elements pairs is 1,if 3 pair is 3 and so on.....formula is n*n-1/2\n return count\n ", "solution_js": "var numEquivDominoPairs = function(dominoes) {\n let map = {};\n let count = 0;\n for (let [a, b] of dominoes) {\n if (b > a) {\n [a, b] = [b, a];\n }\n let key = `${a}-${b}`;\n if (map.hasOwnProperty(key)) {\n map[key]++;\n count += map[key];\n } else {\n map[key] = 0;\n }\n }\n return count;\n};", "solution_java": "class Solution {\n /** Algorithm\n 1. Brute force cannot be used because of the set size.\n 2. Traverse the dominos and group & count them by min-max value.\n As pieces can be from 1 to 9, means their groups will be from 11 to 99.\n eg: [1,2] will be the same as [2,1]. Their value is 10 * (min(1,2)) + max(1,2)\n => 10 * 1 + 2 = 12.\n so pieces[12]++;\n 3. After finishing traversing, iterate over the counted pieces and if the count is\n > 1, calculate the combinations of X by 2.\n 4. The formula is n!/ (k! * (n-k)!)\n As n! can be very large, use the short version of it; (n * (n-1)) / 2. EG n= 40\n Eg: 40! simplify this(divide by 38!) 39 * 40\n -------- --------- \n 2! * (38!) 2\n 5. Return the total result \n */\n public int numEquivDominoPairs(int[][] dominoes) {\n int[] pieces = new int[100];\n for (int[] domino : dominoes) {\n pieces[10 * Math.min(domino[0], domino[1]) + Math.max(domino[0], domino[1])]++;\n }\n int pairs = 0;\n for (int i = 11; i <= 99; i++) {\n if (pieces[i] > 1) {\n pairs += getCombinations(pieces[i]);\n }\n }\n \n return pairs; \n }\n \n private int getCombinations(int n) {\n return (n * (n-1)) / 2;\n }\n}", "solution_c": "class Solution {\npublic:\n int numEquivDominoPairs(vector>& dominoes)\n {\n map,int> m;\n int ans=0;\n for(auto &d:dominoes)\n {\n int a=min(d[0],d[1]),b=max(d[0],d[1]);\n m[{a,b}]++;\n }\n for(auto &p:m)\n {\n int n=p.second;\n ans+=((n-1)*n)/2;\n }\n return ans;\n\n }\n};\n//if you like the solution plz upvote." }, { "title": "Divide Two Integers", "algo_input": "Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.\n\nThe integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.\n\nReturn the quotient after dividing dividend by divisor.\n\nNote: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.\n\n \nExample 1:\n\nInput: dividend = 10, divisor = 3\nOutput: 3\nExplanation: 10/3 = 3.33333.. which is truncated to 3.\n\n\nExample 2:\n\nInput: dividend = 7, divisor = -3\nOutput: -2\nExplanation: 7/-3 = -2.33333.. which is truncated to -2.\n\n\n \nConstraints:\n\n\n\t-231 <= dividend, divisor <= 231 - 1\n\tdivisor != 0\n\n", "solution_py": "class Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n # Solution 1 - bitwise operator << \n \"\"\"\n positive = (dividend < 0) is (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor)\n\t\tif divisor == 1:\n quotient = dividend\n else: \n\t\t\tquotient = 0\n\t\t\twhile dividend >= divisor:\n\t\t\t\ttemp, i = divisor, 1\n\t\t\t\twhile dividend >= temp:\n\t\t\t\t\tdividend -= temp\n\t\t\t\t\tquotient += i\n\t\t\t\t\ti <<= 1\n\t\t\t\t\ttemp <<= 1\n\n\t\tif not positive:\n\t\t\treturn max(-2147483648, -quotient)\n\t\telse:\n\t\t\treturn min(quotient, 2147483647) \n \"\"\"\n # Solution 2 - cumulative sum - faster than bitwise \n positive = (dividend < 0) == (divisor < 0)\n dividend, divisor = abs(dividend), abs(divisor) \n if divisor == 1:\n quotient = dividend\n else: \n quotient = 0\n _sum = divisor\n\n while _sum <= dividend:\n current_quotient = 1\n while (_sum + _sum) <= dividend:\n _sum += _sum\n current_quotient += current_quotient\n dividend -= _sum\n _sum = divisor\n quotient += current_quotient \n if not positive:\n return max(-2147483648, -quotient)\n else:\n return min(quotient, 2147483647) ", "solution_js": "var divide = function(dividend, divisor) {\n if (dividend == -2147483648 && divisor == -1) return 2147483647;\n let subdividend = Math.abs(dividend)\n let subdivisor = Math.abs(divisor)\n let string_dividend = subdividend.toString()\n let i = 0\n let ans=0\n let remainder = 0\n while(i0 && divisor <0) || (dividend <0 && divisor >0)) return 0-ans\n return ans\n};", "solution_java": "class Solution {\n public int divide(int dividend, int divisor) {\n if(dividend == 1<<31 && divisor == -1){\n return Integer.MAX_VALUE;\n }\n boolean sign = (dividend >= 0) == (divisor >= 0) ? true : false;\n \n dividend = Math.abs(dividend);\n divisor = Math.abs(divisor);\n \n int result = 0;\n while(dividend - divisor >= 0){\n int count = 0;\n while(dividend - (divisor << 1 << count) >= 0){\n count++;\n }\n result += 1 < 0 ^ divisor > 0 ? -1 : 1;\n while (dvd >= dvs) {\n long temp = dvs, m = 1;\n while (temp << 1 <= dvd) {\n temp <<= 1;\n m <<= 1;\n }\n dvd -= temp;\n ans += m;\n }\n return sign * ans;\n }\n};" }, { "title": "Trapping Rain Water", "algo_input": "Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n\n \nExample 1:\n\nInput: height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\nExplanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n\n\nExample 2:\n\nInput: height = [4,2,0,3,2,5]\nOutput: 9\n\n\n \nConstraints:\n\n\n\tn == height.length\n\t1 <= n <= 2 * 104\n\t0 <= height[i] <= 105\n\n", "solution_py": "class Solution:\n def trap(self, a: List[int]) -> int:\n l=0\n r=len(a)-1\n maxl=0\n maxr=0\n res=0\n\n while (l<=r):\n if a[l]<=a[r]:\n if a[l]>=maxl: maxl=a[l] #update maxl if a[l] is >=\n else: res+=maxl-a[l] #adding captured water when maxl>a[l]\n l+=1\n else:\n if a[r]>=maxr: maxr=a[r]\n else: res+=maxr-a[r]\n r-=1\n return res", "solution_js": "var trap = function(height) {\n let left = 0, right = height.length - 1;\n let hiLevel = 0, water = 0;\n while(left <= right) {\n let loLevel = height[height[left] < height[right] ? left++ : right--];\n hiLevel = Math.max(hiLevel, loLevel);\n water += hiLevel - loLevel ;\n }\n return water;\n};", "solution_java": "class Solution {\n public int trap(int[] height) {\n int left = 0;\n int right = height.length - 1;\n \n int l_max = height[left];\n int r_max = height[right];\n int res = 0;\n \n while(left < right) {\n if(l_max < r_max) {\n left+=1;\n l_max = Math.max(l_max, height[left]);\n res += l_max - height[left];\n }\n else{\n right-=1;\n r_max = Math.max(r_max, height[right]);\n res += r_max - height[right];\n }\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int trap(vector& height) {\n int left=0,right=height.size()-1;\n int maxleft=0,maxright=0;\n int res=0;\n while(left<=right){\n if(height[left]<=height[right]){\n if(height[left]>=maxleft)maxleft=height[left];\n else res += maxleft-height[left];\n left++;\n }else{\n if(height[right]>=maxright)maxright=height[right];\n else res += maxright-height[right];\n right--;\n }\n }\n return res;\n }\n};" }, { "title": "Calculate Digit Sum of a String", "algo_input": "You are given a string s consisting of digits and an integer k.\n\nA round can be completed if the length of s is greater than k. In one round, do the following:\n\n\n\tDivide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.\n\tReplace each group of s with a string representing the sum of all its digits. For example, \"346\" is replaced with \"13\" because 3 + 4 + 6 = 13.\n\tMerge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.\n\n\nReturn s after all rounds have been completed.\n\n \nExample 1:\n\nInput: s = \"11111222223\", k = 3\nOutput: \"135\"\nExplanation: \n- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n ​​​​​Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.\n\n\nExample 2:\n\nInput: s = \"00000000\", k = 3\nOutput: \"000\"\nExplanation: \nWe divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\t2 <= k <= 100\n\ts consists of digits only.\n\n", "solution_py": "class Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n s = ''\n for e in set_3:\n val = 0\n for n in e:\n val += int(n)\n s += str(val)\n return s", "solution_js": "var digitSum = function(s, k) {\n while (s.length > k) {\n let newString = \"\";\n for (let i = 0; i < s.length; i += k)\n newString += s.substring(i, i + k).split(\"\").reduce((acc, val) => acc + (+val), 0);\n\n s = newString;\n }\n\n return s;\n};", "solution_java": "class Solution {\n public String digitSum(String s, int k) {\n while(s.length() > k) s = gen(s,k);\n return s;\n }\n public String gen(String s,int k){\n String res = \"\";\n for(int i=0;i < s.length();){\n int count = 0,num=0;\n while(i < s.length() && count++ < k) num += Character.getNumericValue(s.charAt(i++));\n res+=num;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n string digitSum(string s, int k) {\n \n if(s.length()<=k)\n return s;\n \n string ans=\"\";\n int sum=0,temp=k;\n int len = s.length();\n for(int i=0;ik)\n ans = digitSum(ans,k);\n return ans;\n }\n};" }, { "title": "Best Time to Buy and Sell Stock II", "algo_input": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day.\n\nOn each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.\n\nFind and return the maximum profit you can achieve.\n\n \nExample 1:\n\nInput: prices = [7,1,5,3,6,4]\nOutput: 7\nExplanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.\n\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.\nTotal profit is 4.\n\n\nExample 3:\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n\n\n \nConstraints:\n\n\n\t1 <= prices.length <= 3 * 104\n\t0 <= prices[i] <= 104\n\n", "solution_py": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n=len(prices)\n ans=0\n want=\"valley\"\n for i in range(n-1):\n if want==\"valley\" and prices[i]prices[i+1]:\n ans+=prices[i]\n want=\"valley\"\n if want==\"hill\":\n ans+=prices[-1]\n return ans", "solution_js": "/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n let lowestNum = prices[0];\n let highestNum = prices[0];\n let profit = highestNum - lowestNum;\n\n for(var indexI=1; indexI lowestNum) {\n lowestNum = prices[indexI - 1];\n profit = profit + prices[indexI] - lowestNum;\n highestNum = prices[indexI];\n }\n }\n\n return profit;\n};", "solution_java": "class Solution {\n public int maxProfit(int[] prices) {\n int n = prices.length,profit = 0;\n for(int i=0;iprices[i]){\n profit += prices[i+1]-prices[i];\n }\n }\n return profit;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxProfit(vector& prices) {\n int n=prices.size();\n int ans=0,currMin=prices[0];\n for(int i=1;iprices[i-1]){\n i++;\n }\n ans+=(prices[i-1]-currMin);\n currMin=prices[i];\n }\n return ans;\n }\n};" }, { "title": "Count Common Words With One Occurrence", "algo_input": "Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.\n\n \nExample 1:\n\nInput: words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\nOutput: 2\nExplanation:\n- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.\n\n\nExample 2:\n\nInput: words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\nOutput: 0\nExplanation: There are no strings that appear in each of the two arrays.\n\n\nExample 3:\n\nInput: words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\nOutput: 1\nExplanation: The only string that appears exactly once in each of the two arrays is \"ab\".\n\n\n \nConstraints:\n\n\n\t1 <= words1.length, words2.length <= 1000\n\t1 <= words1[i].length, words2[j].length <= 30\n\twords1[i] and words2[j] consists only of lowercase English letters.\n\n", "solution_py": "class Solution:\n\tdef countWords(self, words1: List[str], words2: List[str]) -> int:\n\t\tcount = Counter(words1 + words2)\n\t\treturn len([word for word in count if count[word] == 2 and word in words1 and word in words2])", "solution_js": "var countWords = function(words1, words2) {\n const map1 = new Map();\n const map2 = new Map();\n let count = 0;\n\n for (const word of words1) {\n map1.set(word, map1.get(word) + 1 || 1);\n }\n for (const word of words2) {\n map2.set(word, map2.get(word) + 1 || 1);\n }\n for (const word of words1) {\n if (map1.get(word) === 1 && map2.get(word) === 1) count++;\n }\n\n return count;\n};", "solution_java": "class Solution\n{\n public int countWords(String[] words1, String[] words2)\n {\n HashMap map1 = new HashMap<>();\n HashMap map2 = new HashMap<>();\n\t\t\n for(String word : words1)\n map1.put(word,map1.getOrDefault(word,0)+1);\n for(String word : words2)\n map2.put(word,map2.getOrDefault(word,0)+1);\n\t\t\t\n int count = 0;\n for(String word : words1)\n if(map1.get(word) == 1 && map2.getOrDefault(word,0) == 1)\n count++;\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countWords(vector& words1, vector& words2) {\n unordered_map freq1, freq2;\n for (auto& s : words1) ++freq1[s];\n for (auto& s : words2) ++freq2[s];\n int ans = 0;\n for (auto& [s, v] : freq1)\n if (v == 1 && freq2[s] == 1) ++ans;\n return ans;\n }\n};" }, { "title": "Minimum Absolute Difference", "algo_input": "Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.\n\nReturn a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\n\n\n\ta, b are from arr\n\ta < b\n\tb - a equals to the minimum absolute difference of any two elements in arr\n\n\n \nExample 1:\n\nInput: arr = [4,2,1,3]\nOutput: [[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\n\nExample 2:\n\nInput: arr = [1,3,6,10,15]\nOutput: [[1,3]]\n\n\nExample 3:\n\nInput: arr = [3,8,-10,23,19,-4,-14,27]\nOutput: [[-14,-10],[19,23],[23,27]]\n\n\n \nConstraints:\n\n\n\t2 <= arr.length <= 105\n\t-106 <= arr[i] <= 106\n\n", "solution_py": "class Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n diff=float(inf)\n for i in range(0,len(arr)-1):\n if arr[i+1]-arr[i] a - b)\n let minDif = Infinity\n let res = []\n\n for (let i = 0; i < arr.length - 1; i++) {\n let currDif = Math.abs(arr[i + 1] - arr[i])\n if (currDif < minDif) minDif = currDif\n }\n\n for (let i = 0; i < arr.length - 1; i++) {\n let dif = Math.abs(arr[i + 1] - arr[i])\n if (dif === minDif) {\n res.push([arr[i], arr[i + 1]])\n }\n }\n return res\n};", "solution_java": "class Solution {\n public List> minimumAbsDifference(int[] arr) {\n List> ans=new ArrayList<>();\n Arrays.sort(arr);\n int min=Integer.MAX_VALUE;\n for(int i=0;i pair=new ArrayList<>(2);\n pair.add(arr[i]);\n pair.add(arr[i+1]);\n ans.add(pair);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> minimumAbsDifference(vector& arr) {\n sort(arr.begin(),arr.end());\n int diff=INT_MAX;\n for(int i=1;i>v;\n for(int i=1;i List[bool]:\n parent = list(range(n+1))\n def find(i):\n if parent[i] != i:\n parent[i] = find(parent[i])\n return parent[i]\n def union(i,j):\n parent[find(i)] = find(j)\n if not threshold: return [True]*len(queries)\n for i in range(1, n+1):\n for j in range(2*i, n+1, i):\n if i > threshold: union(i,j)\n return [find(i) == find(j) for i,j in queries]", "solution_js": "var areConnected = function(n, threshold, queries) {\n\n // if(gcd(a,b)>threshold), a and b are connected\n\n // 2 is connected with : 2, 4,6,8,10,12,14,16, (gcd(2,y)=2)\n // 3 is connected with : 3,6,9,12,... (gcd(3,y)=3)\n // 4 is connected with : 4,8,12,16,20,24,28, (gcd(4,y)=4)\n // 6 is connected with : 6,12,18...,cos (gcd(6,y)=6)\n // 5 is connected with : 10,15,20,25,...n cos (gcd(5,y)=6)\n // etc\n\n let dsu=new UnionFind(n+1) //to map n=>n (no node 0 on my question)\n\n for (let node = threshold+1; node <=n; node++) //basically this ensures that the road exists\n //cos gcd(node,secondnode)==node >threshold\n for (let secondnode = node+node; secondnode <=n; secondnode+=node)\n dsu.union(node,secondnode)\n\n return queries.map(([a,b])=>dsu.sameGroup(a,b))\n};\nclass UnionFind {\n\n constructor(size){\n //the total count of different elements(not groups) in this union find\n this.count=size\n //tracks the sizes of each of the components(groups/sets)\n //groupsize[a] returns how many elements the component with root a has\n this.groupSize=[...Array(size)]\n //number of components(groups) in the union find\n this.numComponents=size\n //points to the parent of i, if parent[i]=i, i is a root node\n this.parent=[...Array(size)] //which is also the index of the group\n\n //put every element into its own group\n // rooted at itself\n for (let i = 0; i < size; i++) {\n this.groupSize[i]=i\n this.parent[i]=i\n }\n }\n\n //returns to which component (group) my element belongs to\n // (n) --Amortized constant time\n // Update: Also compresses the paths so that each child points to its\n // parent\n find(element){\n let root=element\n //find the parent of the group the elemnt belongs to\n // When root===parent[root] is always the parent of that group (root)\n while(root!=this.parent[root])\n root=this.parent[root]\n\n // Compression, point the element to its parent if its not already pointed\n // Tldr: Not only do I point my element to its actual root, i point any\n // inbetween elements to that root aswell\n while(element!=root){\n let next=this.parent[element]\n this.parent[element]=root\n element=next\n }\n\n return root\n }\n\n //Unifies the sets containing A and B\n // if not already unified\n // (n) --Amortized constant time\n union(A,B){\n let root1=this.find(A) //parent of A\n ,root2=this.find(B) //parent of B\n if(root1===root2) //already unified\n return\n // I want to put the set with fewer elements\n // to the one with more elemenets\n if(this.groupSize[root1]samegroup\n sameGroup=(A,B)=>this.find(A)==this.find(B)\n\n //essentially the groupSize of its parent's group\n sizeOfGroup=(A)=>this.groupSize[this.find(A)]\n\n}", "solution_java": "//Solving the problem using Disjoint Set Union Find approach\n\nclass Solution {\n\n public int find(int x){\n\n if(parent[x] == x)\n return x;\n\n //Optimising by placing the same parent for all the elements to reduce reduntant calls\n return parent[x] = find(parent[x]);\n }\n\n public void union(int a, int b){\n\n a = find(a);\n b = find(b);\n\n //Using Rank optimisation\n if(rank[a] > rank[b]){\n parent[b] = a;\n rank[a] += rank[b];\n }\n\n else{\n parent[a] = b;\n rank[b] += rank[a];\n }\n\n //parent[b] = a;\n }\n\n int parent[];\n int rank[];\n public List areConnected(int n, int threshold, int[][] queries) {\n\n List ans = new ArrayList();\n parent = new int[n+1];\n rank = new int[n+1];\n\n for(int i=1; i<=n; i++){\n //Each element is its own parent\n parent[i] = i;\n //At beginning each element has rank 1\n rank[i] = 1;\n }\n\n // Finding the possible divisors with pairs above given threshold\n for(int th = threshold+1; th<=n; th++){\n\n int mul = 1;\n while(mul * th <= n){\n //If possible pair then making a union of those paired element\n union(th, mul*th);\n mul++;\n }\n }\n\n //Generating ans for all possible queries\n for(int[] query : queries){\n ans.add((find(query[0]) == find(query[1])));\n }\n return ans;\n }\n}", "solution_c": "// DSU Class Template\nclass DSU {\n vector parent, size;\npublic:\n\n DSU(int n) {\n for(int i=0; i<=n; i++) {\n parent.push_back(i);\n size.push_back(1);\n }\n }\n\n int findParent(int num) {\n if(parent[num] == num) return num;\n return parent[num] = findParent(parent[num]);\n }\n\n void unionBySize(int u, int v) {\n int parU = findParent(u);\n int parV = findParent(v);\n\n if(parU == parV) return;\n\n if(size[parU] < size[parV]) {\n parent[parU] = parV;\n size[parV] += size[parU];\n }\n else {\n parent[parV] = parU;\n size[parU] += size[parV];\n }\n }\n};\n\nclass Solution {\npublic:\n vector areConnected(int n, int threshold, vector>& queries) {\n\n DSU dsu(n);\n\n // Make connections with its multiple\n for(int i=threshold+1; i<=n; i++) {\n int j = 1;\n while(i*j <= n) {\n dsu.unionBySize(i, i*j);\n j++;\n }\n }\n\n vector res;\n for(auto& query : queries) {\n int u = query[0];\n int v = query[1];\n\n // Check if both cities belong to same component or not\n if(dsu.findParent(u) == dsu.findParent(v)) res.push_back(true);\n else res.push_back(false);\n }\n\n return res;\n }\n};" }, { "title": "Counting Bits", "algo_input": "Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.\n\n \nExample 1:\n\nInput: n = 2\nOutput: [0,1,1]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\n\n\nExample 2:\n\nInput: n = 5\nOutput: [0,1,1,2,1,2]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101\n\n\n \nConstraints:\n\n\n\t0 <= n <= 105\n\n\n \nFollow up:\n\n\n\tIt is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?\n\tCan you do it without using any built-in function (i.e., like __builtin_popcount in C++)?\n\n", "solution_py": "class Solution:\n def countBits(self, n: int) -> List[int]:\n # We know that all exponential values of two have 1 bit turned on, the rest are turned off.\n # Now, we can find a relation with following numbers after 2, where the numbers can be decomposed \n # into smaller numbers where we already have found the # of 1s, for example.\n # F(3) = F(2^1) + F(1) = 1 + 1 = 3\n # F(4) = F(2^2) + F(0) = 1 + 0. ( Even thought we havent defined F(4) = F(2^2), by the previous established)\n # comment, we can safely say that all F(2^X) has only 1 bit so thats where F(4) would be = 1\n # F(5) = F(2^2) + F(1) = 1 + 1 = 2\n # F(6) = F(2^2) + F(2) = F(4) + F(2) = 1 + 1\n # The relation countinues for all following numbers\n \n # This solution is O(N)\n # With O(1) extra space ( considering dp is the returned answer )\n \n dp = [0]\n\t\t\n for i in range(1, n + 1):\n exponent = int(math.log(i) / math.log(2))\n num = 2**exponent\n decimal = i % (num)\n if num == i:\n dp.append(1)\n else:\n dp.append(dp[num] + dp[decimal])\n return(dp)", "solution_js": "var countBits = function(n) {\n if (n === 0) return [0];\n\n const ans = new Array(n + 1).fill(0);\n\n let currRoot = 0;\n for (let idx = 1; idx <= n; idx++) {\n if ((idx & (idx - 1)) === 0) {\n ans[idx] = 1;\n currRoot = idx;\n continue;\n }\n\n ans[idx] = 1 + ans[idx - currRoot];\n }\n\n return ans;\n};", "solution_java": "class Solution {\n\n public void count(int n, int[] a, int k)\n {\n int i;\n for(i=k ; i countBits(int n) {\n vector ans;\n for( int i = 0; i <= n; i++ ){\n int x = countones(i);\n ans.push_back(x);\n }\n return ans;\n }\n};" }, { "title": "Minimum Incompatibility", "algo_input": "You are given an integer array nums​​​ and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.\n\nA subset's incompatibility is the difference between the maximum and minimum elements in that array.\n\nReturn the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.\n\nA subset is a group integers that appear in the array with no particular order.\n\n \nExample 1:\n\nInput: nums = [1,2,1,4], k = 2\nOutput: 4\nExplanation: The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n\nExample 2:\n\nInput: nums = [6,3,8,1,3,1,2,2], k = 4\nOutput: 6\nExplanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n\n\nExample 3:\n\nInput: nums = [5,3,3,6,3,3], k = 3\nOutput: -1\nExplanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n\n\n \nConstraints:\n\n\n\t1 <= k <= nums.length <= 16\n\tnums.length is divisible by k\n\t1 <= nums[i] <= nums.length\n\n", "solution_py": "class Solution(object):\n def minimumIncompatibility(self, nums, k):\n nums.sort(reverse = True)\n upperbound = len(nums) // k\n arr = [[] for _ in range(k)]\n self.res = float('inf')\n def assign(i):\n if i == len(nums):\n self.res = min(self.res, sum(arr[i][0]-arr[i][-1] for i in range(k)))\n return True\n flag = 0\n for j in range(k):\n if not arr[j] or (len(arr[j]) < upperbound and arr[j][-1] != nums[i]):\n arr[j].append(nums[i])\n if assign(i+1):\n flag += 1\n arr[j].pop()\n if flag >= 2: break\n return flag != 0\n if max(collections.Counter(nums).values()) > k: return -1\n assign(0)\n return self.res", "solution_js": "////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////////////////\n\n\nvar minimumIncompatibility = function(nums, k) {\n\t////// FROM HERE TO\n if (nums.length === k) return 0;\n \n const maxInBucket = nums.length / k;\n const freqCount = {};\n for (const n of nums) {\n if (freqCount[n]) {\n if (freqCount[n] === k) {\n return -1\n } else {\n freqCount[n]++\n }\n } else {\n freqCount[n] = 1\n }\n }\n\t/////// HERE is just saving time\n \n\t// create a cache (aka memo, dp, dynamic programming, momoization)\n const cache = {}\n\t// create a mask to know when all the indicies are used\n const allIndiciesUsedMask = 2 ** nums.length - 1;\n \n const dfs = (usedIndicesBitMask) => {\n\t // if we have used all the indicies then we return 0\n if (usedIndicesBitMask === allIndiciesUsedMask) {\n return 0;\n }\n\t\t// if we have seen this combination before, return the\n\t\t// result that was calculated before\n\t\t// otherwise do the hard work LOL\n if (cache[usedIndicesBitMask]) {\n return cache[usedIndicesBitMask];\n }\n \n\t\t// find all the indicies that are available to be used\n\t\t// skip duplicate values\n const valsToIndices = {};\n for (let i = 0; i < nums.length; i++) {\n const indexMask = 1 << i;\n if (usedIndicesBitMask & indexMask) continue;\n const value = nums[i];\n if (!valsToIndices.hasOwnProperty(value)) {\n valsToIndices[value] = i;\n }\n }\n const indicesAvailable = Object.values(valsToIndices);\n\n // this is hard to explain but it's basically calculating the minimum\n\t\t// cost while marking the indicies that are going to be used for each\n\t\t// combination\n let minIncompatibilityCost = Infinity;\n const combinations = createCombinations(indicesAvailable, maxInBucket);\n for (const indices of combinations) {\n let nextMask = usedIndicesBitMask;\n let minVal = Infinity;\n let maxVal = -Infinity;\n for (const index of indices) {\n minVal = Math.min(minVal, nums[index]);\n maxVal = Math.max(maxVal, nums[index]);\n nextMask = nextMask | (1 << index);\n }\n const incompatibilityCost = maxVal - minVal;\n minIncompatibilityCost = \n Math.min(minIncompatibilityCost, dfs(nextMask) + incompatibilityCost);\n }\n return cache[usedIndicesBitMask] = minIncompatibilityCost;\n }\n return dfs(0);\n};\n\nfunction createCombinations(indices, len) {\n const combinations = [];\n \n if (indices.length < len) {\n return combinations;\n }\n \n const stack = [[[], 0]];\n while (stack.length > 0) {\n let [combi, i] = stack.pop();\n for (; i < indices.length; i++) {\n const combination = [...combi, indices[i]];\n if (combination.length === len) {\n combinations.push(combination);\n } else {\n stack.push([combination, i + 1]);\n }\n }\n }\n \n return combinations;\n}", "solution_java": "class Solution {\n public int minimumIncompatibility(int[] nums, int k) {\n Arrays.sort(nums);\n k=nums.length/k;\n int n = nums.length,INF=100;\n int[][] dp = new int[1<0;w++){\n if ((i&1<0;w++){\n if ((i&1<& nums, int k) {\n int i, n = nums.size(), subset_size = n / k;\n sort(nums.begin(), nums.end());\n\n // Pre-calculate the range (max - min) for each subset of nums\n // Note that there are (1 << n) subsets (i.e. 2 ^ n subsets) of an array of size n\n vector range(1 << n, INF);\n\n // Each mask represents every possible subset of elements in num (so, \"mask\" == \"subset\")\n // Specifically, if the bit at position i of mask is set to 1, then we include that number in the subset\n for(int mask = 1; mask < (1 << n); mask++) {\n int small = -1, big = -1;\n bool dup = false;\n\n // Identify elements that belong to this subset, find the largest & smallest, check for duplicates\n // Recall that this array was sorted in the beginning of the function\n for(i=0; i dp(1 << n, INF);\n dp[0] = 0;\n\n // Iterate over every mask (i.e. subset) and calculate its minimum sum\n for(int mask = 1; mask < (1 << n); mask++) {\n\n // Iterate over every submask for current mask\n for(int submask = mask; submask; submask = (submask - 1) & mask) {\n\n // Check that submask has the right number of elements\n if(__builtin_popcount(submask) == subset_size)\n // Note that mask = submask + (mask ^ submask)\n // ==> i.e., mask ^ submask = mask - submask\n // In other words, (mask ^ submask) represents those elements in mask that are not in submask\n dp[mask] = min(dp[mask], range[submask] + dp[mask ^ submask]);\n }\n }\n // dp.back() == dp[(1 << n) - 1];\n return dp.back() >= INF ? -1 : dp.back();\n }\n};" }, { "title": "Sum of Nodes with Even-Valued Grandparent", "algo_input": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.\n\nA grandparent of a node is the parent of its parent if it exists.\n\n \nExample 1:\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 18\nExplanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\n\n\nExample 2:\n\nInput: root = [1]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n\tdef sumEvenGrandparent(self, root: TreeNode) -> int:\n\n\t\tdef dfs(root, p, gp):\n\t\t\tif not root: return 0\n\t\t\tif gp and gp.val%2==0:\n\t\t\t\treturn root.val + dfs(root.left,root,p)+dfs(root.right,root,p)\n\t\t\treturn 0 + dfs(root.left,root,p)+dfs(root.right,root,p)\n\n\t\treturn dfs(root,None,None)", "solution_js": "const dfs = function(node, evenParent) {\n if (!node) return 0;\n \n const isEvenNode = node.val % 2 === 0;\n \n const left = dfs(node.left, isEvenNode);\n const right = dfs(node.right, isEvenNode);\n \n if (!evenParent) return left + right;\n return left + right + (node.left ? node.left.val : 0) + (node.right ? node.right.val : 0);\n}\n\nvar sumEvenGrandparent = function(root) {\n if (!root) return 0;\n return dfs(root, false);\n};", "solution_java": "class Solution {\n int sum=0;\n public int sumEvenGrandparent(TreeNode root) {\n dfs(root,null,null);\n return sum;\n }\n void dfs(TreeNode current, TreeNode parent, TreeNode grandParent) {\n if (current == null) return; // base case \n if (grandParent != null && grandParent.val % 2 == 0) {\n sum += current.val;\n }\n\t\t\t\t//cur->cur.left ||cur.right , parent=cur,grandPrarent=parent\n dfs(current.left, current, parent)\n dfs(current.right, current, parent);\n }\n }", "solution_c": "class Solution {\npublic:\n void sumGparent(TreeNode* child, int& sum, TreeNode* parent, TreeNode* Gparent){\n if(!child) return;\n if(Gparent) if(Gparent->val % 2 ==0) sum += child->val;\n sumGparent(child->left, sum, child, parent);\n sumGparent(child->right, sum, child, parent);\n }\n\n int sumEvenGrandparent(TreeNode* root) {\n if(!root) return 0;\n int sum=0;\n sumGparent(root, sum, NULL, NULL); // (child, sum, parent, grand-parent)\n return sum;\n }\n};" }, { "title": "Range Sum Query 2D - Immutable", "algo_input": "Given a 2D matrix matrix, handle multiple queries of the following type:\n\n\n\tCalculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n\n\nImplement the NumMatrix class:\n\n\n\tNumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.\n\tint sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n\n\nYou must design an algorithm where sumRegion works on O(1) time complexity.\n\n \nExample 1:\n\nInput\n[\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\nOutput\n[null, 8, 11, 12]\n\nExplanation\nNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 200\n\t-104 <= matrix[i][j] <= 104\n\t0 <= row1 <= row2 < m\n\t0 <= col1 <= col2 < n\n\tAt most 104 calls will be made to sumRegion.\n\n", "solution_py": "class NumMatrix:\n\n def __init__(self, matrix: List[List[int]]):\n m, n = len(matrix), len(matrix[0])\n # Understand why we need to create a new matrix with extra one row/column\n self.sum = [[0 for row in range(n + 1)] for column in range(m + 1)]\n for r in range(1, m + 1):\n for c in range(1, n + 1):\n self.sum[r][c] = self.sum[r - 1][c] + self.sum[r][c - 1] - self.sum[r - 1][c - 1] + matrix[r - 1][c - 1]\n\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n r1, c1, r2, c2 = row1 + 1, col1 + 1, row2 + 1, col2 + 1\n return self.sum[r2][c2] - self.sum[r1 - 1][c2] - self.sum[r2][c1 - 1] + self.sum[r1 - 1][c1 - 1]\n\n# Your NumMatrix object will be instantiated and called as such:\n# obj = NumMatrix(matrix)\n# param_1 = obj.sumRegion(row1,col1,row2,col2)", "solution_js": "/**\n * @param {number[][]} matrix\n */\nvar NumMatrix = function(matrix) {\n const n = matrix.length, m = matrix[0].length;\n // n * m filled with 0\n this.prefix = Array.from({ length: n}, (_, i) => {\n return new Array(m).fill(0);\n });\n const prefix = this.prefix;\n // precompute\n for(let i = 0; i < m; i++) {\n if(i == 0) prefix[0][i] = matrix[0][i];\n else prefix[0][i] = prefix[0][i-1] + matrix[0][i];\n }\n for(let i = 0; i < n; i++) {\n if(i == 0) continue;\n else prefix[i][0] = prefix[i-1][0] + matrix[i][0];\n }\n \n for(let i = 1; i < n; i++) {\n for(let j = 1; j < m; j++) {\n prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] + matrix[i][j];\n }\n }\n};\n\n/** \n * @param {number} row1 \n * @param {number} col1 \n * @param {number} row2 \n * @param {number} col2\n * @return {number}\n */\nNumMatrix.prototype.sumRegion = function(row1, col1, row2, col2) {\n const prefix = this.prefix;\n const biggerRectSum = prefix[row2][col2];\n if(row1 == col1 && row1 == 0) return biggerRectSum;\n if(row1 == 0 || col1 == 0) {\n let subtractRegion = 0;\n if(row1 == 0) subtractRegion = prefix[row2][col1 - 1];\n else subtractRegion = prefix[row1 - 1][col2];\n return biggerRectSum - subtractRegion;\n }\n return biggerRectSum - prefix[row1-1][col2] - prefix[row2][col1 - 1] + prefix[row1-1][col1-1];\n};\n\n/** \n * Your NumMatrix object will be instantiated and called as such:\n * var obj = new NumMatrix(matrix)\n * var param_1 = obj.sumRegion(row1,col1,row2,col2)\n */", "solution_java": "class NumMatrix {\n\n int mat[][];\n public NumMatrix(int[][] matrix) {\n mat = matrix;\n int rows = mat.length;\n int cols = mat[0].length;\n \n for(int i = 0; i< rows; i++)\n {\n for(int j = 0; j < cols; j++) \n {\n if(i > 0) mat[i][j] += mat[i-1][j];\n if(j > 0) mat[i][j] += mat[i][j-1];\n if(i>0 && j > 0) mat[i][j] -= mat[i-1][j-1];\n }\n }\n \n }\n \n public int sumRegion(int row1, int col1, int row2, int col2) {\n int res = mat[row2][col2];\n if(row1 > 0) res -= mat[row1-1][col2];\n if(col1 > 0) res -= mat[row2][col1-1];\n if(row1> 0 && col1 > 0) res += mat[row1-1][col1-1];\n \n return res;\n }\n}", "solution_c": "//Using row prefix sum O(m)\nclass NumMatrix {\n vector> prefix;\npublic:\n NumMatrix(vector>& matrix) {\n int m = matrix.size(), n = matrix[0].size();\n for(int i = 0;i row(n);\n row[0] = matrix[i][0];\n for(int j = 1;j0) sum -= prefix[i][col1-1];\n }\n return sum;\n }\n};\n\n//Using mat prefix sum O(1)\nclass NumMatrix {\n vector> prefix;\npublic:\n NumMatrix(vector>& matrix) {\n int m = matrix.size(), n = matrix[0].size();\n prefix = vector>(m+1,vector(n+1,0));\n prefix[1][1] = matrix[0][0];\n for(int i = 1;i<=m;i++){\n for(int j = 1;j<=n;j++){\n prefix[i][j] = prefix[i-1][j] + prefix[i][j-1] + matrix[i-1][j-1] - prefix[i-1][j-1];\n }\n }\n }\n \n int sumRegion(int row1, int col1, int row2, int col2) {\n int sum = 0;\n sum += prefix[row2+1][col2+1];\n sum -= prefix[row1][col2+1];\n sum -= prefix[row2+1][col1];\n sum += prefix[row1][col1];\n return sum;\n }\n};" }, { "title": "K Radius Subarray Averages", "algo_input": "You are given a 0-indexed array nums of n integers, and an integer k.\n\nThe k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1.\n\nBuild and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.\n\nThe average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.\n\n\n\tFor example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.\n\n\n \nExample 1:\n\nInput: nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput: [-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:\n- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.\n\n\nExample 2:\n\nInput: nums = [100000], k = 0\nOutput: [100000]\nExplanation:\n- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.\n\n\nExample 3:\n\nInput: nums = [8], k = 100000\nOutput: [-1]\nExplanation: \n- avg[0] is -1 because there are less than k elements before and after index 0.\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t0 <= nums[i], k <= 105\n\n", "solution_py": "class Solution:\n def getAverages(self, nums: list[int], k: int) -> list[int]:\n\n n, diam = len(nums), 2*k+1\n if n < diam: return [-1]*n\n\n ans = [-1]*k\n\n arr = list(accumulate(nums, initial = 0))\n\n for i in range(n-diam+1):\n ans.append((arr[i+diam]-arr[i])//diam)\n\n return ans + [-1]*k", "solution_js": "var getAverages = function(nums, k) {\n const twoK = 2 * k;\n const windowSize = twoK + 1;\n\n const result = [...nums].fill(-1);\n let sum = 0;\n for (let i = 0; i < nums.length; i++) {\n sum += nums[i];\n if (i >= twoK) {\n result[i - k] = Math.floor(sum / windowSize)\n sum -= nums[i - twoK];\n }\n }\n return result;\n};", "solution_java": "class Solution\n{\n public int[] getAverages(int[] nums, int k)\n {\n if(k == 0)\n return nums;\n\n int N = nums.length;\n long[] sum = new long[N];\n sum[0] = nums[0];\n\n for(int i = 1; i < N; i++)\n sum[i] = sum[i-1]+nums[i]; // Sum of 0 - ith element at sum[i]\n\n int[] ret = new int[N];\n Arrays.fill(ret,-1);\n\n for(int i = k; i < N-k; i++) // Beyond this range, there are less than k elements so -1\n {\n long temp = (sum[i+k]-sum[i-k]+nums[i-k])/(k*2+1);\n ret[i] = (int)temp;\n }\n return ret;\n }\n}", "solution_c": "class Solution {\npublic:\n vector getAverages(vector& nums, int k) {\n\n int n = nums.size();\n vector ans(n , -1);\n\n if(2 * k + 1 > n) return ans;\n\n // Simple Sliding Window\n\n long long int sum = 0;\n\n // Take a window of size 2 * k + 1\n for(int i =0 ; i < 2 * k + 1 ; i++) {\n sum += nums[i];\n }\n\n ans[k] = sum / (2 * k + 1);\n\n // Then slide it untill the end of the window reaches at the end\n\n for(int i = 2 * k + 1 , j = k + 1, s = 0; i < n ; i++ , j++, s++) {\n\n sum += nums[i];\n sum -= nums[s];\n ans[j] = sum /(2 * k + 1);\n\n }\n\n return ans;\n }\n};" }, { "title": "Valid Perfect Square", "algo_input": "Given a positive integer num, write a function which returns True if num is a perfect square else False.\n\nFollow up: Do not use any built-in library function such as sqrt.\n\n \nExample 1:\nInput: num = 16\nOutput: true\nExample 2:\nInput: num = 14\nOutput: false\n\n \nConstraints:\n\n\n\t1 <= num <= 2^31 - 1\n\n", "solution_py": "class Solution:\n def isPerfectSquare(self, num: int) -> bool:\n if num == 1:\n return True\n lo = 2\n hi = num // 2\n while lo <= hi:\n mid = lo + (hi - lo) //2\n print(mid)\n if mid * mid == num:\n return True\n if mid * mid > num:\n hi = mid - 1\n else:\n lo = mid + 1\n return False", "solution_js": "var isPerfectSquare = function(num) {\n let low = 1;\n let high = 100000;\n while(low <= high){\n let mid = (low + high) >> 1;\n let sqrt = mid * mid\n if( sqrt == num) {\n return true;\n \n }else if(num > sqrt ){\n low = mid + 1\n }else {\n high = mid - 1\n }\n }\n return false;\n};", "solution_java": "class Solution {\n public boolean isPerfectSquare(int num) {\n long start = 1;\n long end = num;\n\n while(start<=end){\n long mid = start +(end - start)/2;\n\n if(mid*mid==num){\n return true;\n }\n else if(mid*mid& nums) {\n unordered_map mp;\n int ans= 0;\n for(auto i: nums){\n mp[i]++;\n }\n for(auto j: mp){\n if(j.second == 1){\n ans = j.first;\n break;\n }\n }\n return ans;\n \n }\n};" }, { "title": "Build Array from Permutation", "algo_input": "Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.\n\nA zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).\n\n \nExample 1:\n\nInput: nums = [0,2,1,5,3,4]\nOutput: [0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]\n\nExample 2:\n\nInput: nums = [5,0,1,2,3,4]\nOutput: [4,5,0,1,2,3]\nExplanation: The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t0 <= nums[i] < nums.length\n\tThe elements in nums are distinct.\n\n\n \nFollow-up: Can you solve it without using an extra space (i.e., O(1) memory)?\n", "solution_py": "class Solution:\n\t#As maximum value of the array element is 1000, this solution would work\n def buildArray(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)): \n if nums[nums[i]] <= len(nums):\n nums[i] = nums[nums[i]] * 1000 + nums[i]\n else:\n nums[i] = mod(nums[nums[i]],1000) * 1000 + nums[i]\n \n for i in range(len(nums)):\n nums[i] = nums[i] // 1000\n \n return nums", "solution_js": "var buildArray = function(nums) {\n return nums.map(a=>nums[a]);\n};", "solution_java": "class Solution {\n public int[] buildArray(int[] nums) {\n int n=nums.length;\n for(int i=0;i buildArray(vector& nums) {\n int n=nums.size();\n vector ans(n);\n for(int i=0;i bool:\n reachable = defaultdict(set)\n for a, b in mappings:\n reachable[a].add(b)\n for c in sub:\n reachable[c].add(c)\n regex = \"\"\n for c in sub:\n if len(reachable[c]) > 1:\n regex += \"(\"\n regex += \"|\".join(reachable[c])\n regex += \")\"\n else:\n regex += c\n return re.compile(regex).search(s)", "solution_js": "var matchReplacement = function(s, sub, mappings) {\n let n= s.length;\n let m = sub.length;\n let map = new Array(36).fill().map(_=>new Array(36).fill(0));\n for(let i=0;i> m = new HashMap<>();\n for(char[] carr: mappings) {\n if (!m.containsKey(carr[0])){\n m.put(carr[0], new HashSet());\n }\n m.get(carr[0]).add(carr[1]);\n }\n int len_s = s.length();\n int len_sub = sub.length();\n for (int pos = 0; pos < s.length(); pos++ ){\n int i = pos;\n int j = 0;\n boolean cont = false; \n while (j <= sub.length()) {\n if ( j == sub.length()) return true;\n int lenlefts = len_s - i;\n int lenleftsub = len_sub - j;\n if (lenlefts < lenleftsub) {\n break;\n } else if ((s.charAt(i) == sub.charAt(j)) || \n\t\t\t\t (m.containsKey(sub.charAt(j)) && m.get(sub.charAt(j)).contains( s.charAt(i)))) {\n i += 1;\n j += 1;\n } else {\n break;\n }\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool matchReplacement(string s, string sub, vector>& mappings) {\n\n int m(size(s)), n(size(sub));\n unordered_map> mp;\n\n auto doit = [&](int ind) {\n\n for (int i=ind, j=0; i int:\n def ets(email):\n s, domain = email[:email.index('@')], email[email.index('@'):]\n s = s.replace(\".\", \"\")\n s = s[:s.index('+')] if '+' in s else s\n return s+domain\n dict = {}\n for i in emails:\n dict[ets(i)] = 1\n return len(dict)", "solution_js": "var numUniqueEmails = function(emails) {\n let set = new Set();\n \n for (let email of emails) {\n let curr = email.split('@');\n let currEmail = '';\n \n for (let char of curr[0]) {\n if (char === '.') continue;\n if (char === '+') break;\n currEmail += char;\n }\n \n currEmail += '@' + curr[1];\n set.add(currEmail)\n }\n \n return set.size\n};", "solution_java": "class Solution {\n public int numUniqueEmails(String[] emails) {\n\n Set finalEmails = new HashSet<>();\n for(String email: emails){\n StringBuilder name = new StringBuilder();\n boolean ignore = false;\n for(int i=0;i& emails)\n {\n unordered_set st;\n for(auto &e:emails)\n {\n string clean_email=\"\";\n for(auto &ch:e)\n {\n if(ch=='+'||ch=='@')\n break;\n if(ch=='.')\n continue;\n clean_email+=ch;\n }\n clean_email+=e.substr(e.find('@'));\n st.insert(clean_email);\n }\n return st.size();\n\n }\n};\n//if you like the solution plz upvote." }, { "title": "Merge Triplets to Form Target Triplet", "algo_input": "A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.\n\nTo obtain target, you may apply the following operation on triplets any number of times (possibly zero):\n\n\n\tChoose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].\n\n\t\n\t\tFor example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].\n\t\n\t\n\n\nReturn true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.\n\n \nExample 1:\n\nInput: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\nThe target triplet [2,7,5] is now an element of triplets.\n\n\nExample 2:\n\nInput: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\nOutput: false\nExplanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\n\n\nExample 3:\n\nInput: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\nThe target triplet [5,5,5] is now an element of triplets.\n\n\n \nConstraints:\n\n\n\t1 <= triplets.length <= 105\n\ttriplets[i].length == target.length == 3\n\t1 <= ai, bi, ci, x, y, z <= 1000\n\n", "solution_py": "class Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n\n i=0\n while True:\n if i==len(triplets):\n break\n for j in range(3):\n if triplets[i][j]>target[j]:\n triplets.pop(i)\n i-=1\n break\n i+=1\n\n a = [x[0] for x in triplets]\n b = [x[1] for x in triplets]\n c = [x[2] for x in triplets]\n\n if target[0] not in a:\n return False\n if target[1] not in b:\n return False\n if target[2] not in c:\n return False\n return True", "solution_js": "var mergeTriplets = function(triplets, target) {\n\n let fst = false, snd = false, thrd = false;\n\n const [t1, t2, t3] = target;\n\n for(let i = 0; i < triplets.length; i++) {\n\n const [a, b, c] = triplets[i];\n\n if(a === t1 && b <= t2 && c <= t3) fst = true;\n\n if(b === t2 && a <= t1 && c <= t3) snd = true;\n\n if(c === t3 && a <= t1 && b <= t2) thrd = true;\n\n if(fst && snd && thrd) return true;\n }\n return false;\n};", "solution_java": "class Solution {\n public boolean mergeTriplets(int[][] triplets, int[] target) {\n\n boolean xFound = false, yFound = false, zFound = false;\n \n for(int[] triplet : triplets){\n\t\t\n //Current Triplet is target\n if(triplet[0] == target[0] && triplet[1] == target[1] && triplet[2] == target[2])return true;\n \n if(triplet[0] == target[0]){\n if(triplet[1] <= target[1] && triplet[2] <= target[2])\n if(yFound && zFound)return true;\n else xFound = true;\n }\n if(triplet[1] == target[1]){\n if(triplet[0] <= target[0] && triplet[2] <= target[2])\n if(xFound && zFound)return true;\n else yFound = true;\n }\n if(triplet[2] == target[2]){\n if(triplet[1] <= target[1] && triplet[0] <= target[0])\n if(yFound && xFound)return true;\n else zFound = true;\n } \n }\n return xFound && yFound && zFound;\n }\n}", "solution_c": "class Solution {\npublic:\n bool mergeTriplets(vector>& triplets, vector& target) {\n int first = 0, second = 0, third = 0;\n for (auto tr : triplets) {\n if (tr[0] == target[0] && tr[1] <= target[1] && tr[2] <= target[2]) first = 1;\n if (tr[0] <= target[0] && tr[1] == target[1] && tr[2] <= target[2]) second = 1;\n if (tr[0] <= target[0] && tr[1] <= target[1] && tr[2] == target[2]) third = 1;\n }\n return first && second && third;\n }\n};" }, { "title": "Implement Queue using Stacks", "algo_input": "Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).\n\nImplement the MyQueue class:\n\n\n\tvoid push(int x) Pushes element x to the back of the queue.\n\tint pop() Removes the element from the front of the queue and returns it.\n\tint peek() Returns the element at the front of the queue.\n\tboolean empty() Returns true if the queue is empty, false otherwise.\n\n\nNotes:\n\n\n\tYou must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.\n\tDepending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.\n\n\n \nExample 1:\n\nInput\n[\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 1, 1, false]\n\nExplanation\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n\n\n \nConstraints:\n\n\n\t1 <= x <= 9\n\tAt most 100 calls will be made to push, pop, peek, and empty.\n\tAll the calls to pop and peek are valid.\n\n\n \nFollow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.\n", "solution_py": "class MyStack:\n def __init__(self):\n self.stack = []\n\n def push(self, x):\n self.stack.append(x)\n\n def top(self):\n return self.stack[-1]\n\n def pop(self):\n return self.stack.pop()\n\n def size(self):\n return len(self.stack)\n\n def isEmpty(self):\n return len(self.stack) == 0\n\nclass MyQueue:\n\n def __init__(self):\n self.stack1 = MyStack()\n self.stack2 = MyStack()\n\n def push(self, x: int) -> None:\n self.stack1.push(x)\n\n def pop(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.pop()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def peek(self) -> int:\n while not self.stack1.isEmpty():\n self.stack2.push(self.stack1.pop())\n out = self.stack2.top()\n while not self.stack2.isEmpty():\n self.stack1.push(self.stack2.pop())\n return out\n\n def empty(self) -> bool:\n return self.stack1.isEmpty()\n\n# Your MyQueue object will be instantiated and called as such:\n# obj = MyQueue()\n# obj.push(x)\n# param_2 = obj.pop()\n# param_3 = obj.peek()\n# param_4 = obj.empty()", "solution_js": "var MyQueue = function() {\n this.queue = [];\n};\n\n/** \n * @param {number} x\n * @return {void}\n */\nMyQueue.prototype.push = function(x) {\n this.queue.push(x);\n};\n\n/**\n * @return {number}\n */\nMyQueue.prototype.pop = function() {\n return this.queue.splice(0, 1);\n};\n\n/**\n * @return {number}\n */\nMyQueue.prototype.peek = function() {\n return this.queue[0]\n};\n\n/**\n * @return {boolean}\n */\nMyQueue.prototype.empty = function() {\n return this.queue.length === 0;\n};\n\n/** \n * Your MyQueue object will be instantiated and called as such:\n * var obj = new MyQueue()\n * obj.push(x)\n * var param_2 = obj.pop()\n * var param_3 = obj.peek()\n * var param_4 = obj.empty()\n */", "solution_java": "class MyQueue {\n\n private final Deque stack = new ArrayDeque<>();\n private final Deque temp = new ArrayDeque<>();\n\n /**\n * Initialize your data structure here.\n */\n public MyQueue() {}\n\n /**\n * Pushes element x to the back of the queue.\n */\n public void push(int x) {\n stack.push(x);\n }\n\n /**\n * @return the element at the front of the queue and remove it.\n */\n public int pop() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.pop();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return the element at the front of the queue.\n */\n public int peek() {\n while (stack.size() > 1)\n temp.push(stack.pop());\n\n var val = stack.peek();\n while (!temp.isEmpty())\n stack.push(temp.pop());\n\n return val;\n }\n\n /**\n * @return true if the queue is empty, false otherwise.\n */\n public boolean empty() {\n return stack.isEmpty();\n }\n}", "solution_c": "class MyQueue {\npublic:\n stacks1;\n stacks2;\n\n MyQueue() {\n \n }\n \n void push(int x) {\n s1.push(x);\n }\n \n int pop() {\n if(s1.empty() && s2.empty()) return -1;\n while(s2.empty()){\n while(!s1.empty()){\n s2.push(s1.top());\n s1.pop();\n }\n }\n int x = s2.top();\n s2.pop();\n return x;\n }\n \n int peek() {\n if(!s2.empty()){\n return s2.top();\n }\n else{\n while(!s1.empty()){\n int val = s1.top();\n s2.push(val);\n s1.pop();\n }\n return s2.top();\n }\n }\n \n bool empty() {\n if(s1.empty() && s2.empty()){\n return true;\n }\n return false;\n }\n};\n\n/**\n * Your MyQueue object will be instantiated and called as such:\n * MyQueue* obj = new MyQueue();\n * obj->push(x);\n * int param_2 = obj->pop();\n * int param_3 = obj->peek();\n * bool param_4 = obj->empty();\n */" }, { "title": "Maximum of Absolute Value Expression", "algo_input": "Given two arrays of integers with equal lengths, return the maximum value of:\n\n|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\n\nwhere the maximum is taken over all 0 <= i, j < arr1.length.\n\n \nExample 1:\n\nInput: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput: 13\n\n\nExample 2:\n\nInput: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput: 20\n\n\n \nConstraints:\n\n\n\t2 <= arr1.length == arr2.length <= 40000\n\t-10^6 <= arr1[i], arr2[i] <= 10^6\n\n", "solution_py": "class Solution(object):\n def maxAbsValExpr(self, arr1, arr2):\n \"\"\"\n :type arr1: List[int]\n :type arr2: List[int]\n :rtype: int\n \"\"\"\n max_ppp,max_ppm,max_pmp,max_pmm=float('-inf'),float('-inf'),float('-inf'),float('-inf')\n min_ppp,min_ppm,min_pmp,min_pmm=float('inf'),float('inf'),float('inf'),float('inf')\n for i,(a,b) in enumerate(zip(arr1,arr2)):\n ppp=a+b+i\n if ppp>max_ppp:max_ppp=ppp\n if pppmax_ppm:max_ppm=ppm\n if ppmmax_pmp:max_pmp=pmp\n if pmpmax_pmm:max_pmm=pmm\n if pmmX\n // (B[j] - A[j] - j) -> y\n // X - Y;\n //to get max value X should be max & Y should min\n\n // Possible cases (Since both arrays have same number of indexes, we can use single for loop & i as index)\n //A[i] + B[i] + i ->1\n //A[i] - B[i] + i ->2\n //A[i] + B[i] - i ->3\n //A[i] - B[i] - i ->4\n\n // Find out max of all response\n\n int arrayLength =arr1.length;\n int v1[] = new int [arrayLength];\n int v2[] = new int [arrayLength] ;\n int v3[] = new int [arrayLength] ;\n int v4[] = new int [arrayLength] ;\n int res = 0;\n for(int i = 0 ; i< arrayLength; i++)\n {\n v1[i] = i + arr1[i] + arr2[i];\n v2[i] = i + arr1[i] - arr2[i];\n v3[i] = i - arr1[i] + arr2[i];\n v4[i] = i - arr1[i] - arr2[i];\n }\nres = Math.max(res,Arrays.stream(v1).max().getAsInt()-Arrays.stream(v1).min().getAsInt());\n res = Math.max(res,Arrays.stream(v2).max().getAsInt()-Arrays.stream(v2).min().getAsInt());\n res = Math.max(res,Arrays.stream(v3).max().getAsInt()-Arrays.stream(v3).min().getAsInt());\n res = Math.max(res,Arrays.stream(v4).max().getAsInt()-Arrays.stream(v4).min().getAsInt());\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxAbsValExpr(vector& arr1, vector& arr2) {\n int res=0;\n int n = arr1.size();\n vectorv1;\n vectorv2;\n vectorv3;\n vectorv4;\n for(int i=0;i int:\n \n def dfs(root):\n if not root:\n return 0,0\n \n net_left,left_walk = dfs(root.left)\n net_right,right_walk = dfs(root.right)\n \n\t\t\t# if any node has extra or deficiency in both cases there has to be a walk of abs(extra) or abs(deficiency)\n\t\t\t\n return net_left+net_right+(root.val-1), left_walk+right_walk+abs(net_left)+abs(net_right)\n return dfs(root)[1]", "solution_js": "var distributeCoins = function(root) {\n var moves = 0;\n postorder(root);\n return moves;\n\n function postorder(node){\n if(!node)\n return 0;\n\n const subTotal = postorder(node.left) + postorder(node.right);\n const result = node.val - 1 + subTotal;\n moves += Math.abs(result);\n\n return result;\n\n }\n};", "solution_java": "class Solution {\n int count = 0;\n public int helper(TreeNode root)\n {\n if(root == null)\n return 0;\n int left = helper(root.left);\n int right = helper(root.right);\n count+= Math.abs(left)+Math.abs(right);\n return (left+right+root.val-1);\n }\n public int distributeCoins(TreeNode root) {\n helper(root);\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int ans = 0;\n int recr(TreeNode *root)\n {\n if(!root) return 0;\n int left = recr(root->left);\n int right = recr(root->right);\n int curr = root->val + left + right;\n ans += abs(curr-1);\n return curr-1;\n }\n int distributeCoins(TreeNode* root) {\n recr(root);\n return ans;\n }\n};" }, { "title": "Special Array With X Elements Greater Than or Equal X", "algo_input": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.\n\nNotice that x does not have to be an element in nums.\n\nReturn x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.\n\n \nExample 1:\n\nInput: nums = [3,5]\nOutput: 2\nExplanation: There are 2 values (3 and 5) that are greater than or equal to 2.\n\n\nExample 2:\n\nInput: nums = [0,0]\nOutput: -1\nExplanation: No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.\n\n\nExample 3:\n\nInput: nums = [0,4,3,0,4]\nOutput: 3\nExplanation: There are 3 values that are greater than or equal to 3.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t0 <= nums[i] <= 1000\n\n", "solution_py": "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n for i in range(max(nums)+1):\n y=len(nums)-bisect.bisect_left(nums,i)\n if y==i:\n return i\n return -1\n\n \n ", "solution_js": "var specialArray = function(nums) {\n const freq = new Array(1001).fill(0);\n for(let n of nums)\n freq[n]++;\n \n for(let i=1000, cnt=0; i>=0; i--){\n cnt += freq[i];\n if(i==cnt) return i;\n }\n \n return -1;\n};", "solution_java": "class Solution {\n public int specialArray(int[] nums) {\n int x = nums.length;\n int[] counts = new int[x+1];\n\n for(int elem : nums)\n if(elem >= x)\n counts[x]++;\n else\n counts[elem]++;\n\n int res = 0;\n for(int i = counts.length-1; i > 0; i--) {\n res += counts[i];\n if(res == i)\n return i;\n }\n\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int specialArray(vector& nums) {\n int v[102];\n memset(v, 0, sizeof v);\n for (const auto &n : nums) {\n ++v[n > 100 ? 100 : n];\n }\n for (int i = 100; i > 0; --i) {\n v[i] = v[i + 1] + v[i];\n if (v[i] == i)\n return i;\n }\n return -1;\n }\n};" }, { "title": "Sort Integers by The Power Value", "algo_input": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:\n\n\n\tif x is even then x = x / 2\n\tif x is odd then x = 3 * x + 1\n\n\nFor example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).\n\nGiven three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.\n\nReturn the kth integer in the range [lo, hi] sorted by the power value.\n\nNotice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.\n\n \nExample 1:\n\nInput: lo = 12, hi = 15, k = 2\nOutput: 13\nExplanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\n\n\nExample 2:\n\nInput: lo = 7, hi = 11, k = 4\nOutput: 7\nExplanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.\n\n\n \nConstraints:\n\n\n\t1 <= lo <= hi <= 1000\n\t1 <= k <= hi - lo + 1\n\n", "solution_py": "import heapq\nclass Solution:\n def power(self,n):\n if n in self.dic:\n return self.dic[n]\n if n % 2:\n self.dic[n] = self.power(3 * n + 1) + 1\n else:\n self.dic[n] = self.power(n // 2) + 1\n return self.dic[n] \n def getKth(self, lo: int, hi: int, k: int) -> int:\n self.dic = {1:0}\n for i in range(lo,hi+1):\n self.power(i)\n \n lst = [(self.dic[i],i) for i in range(lo,hi+1)]\n heapq.heapify(lst)\n \n for i in range(k):\n ans = heapq.heappop(lst)\n \n return ans[1] ", "solution_js": "var getKth = function(lo, hi, k) {\n const dp = new Map();\n dp.set(1, 0);\n const powerVals = [];\n for(let num = lo; num <= hi; ++num) {\n powerVals.push([num, findPowerVal(num, dp)]);\n }\n const heap = new MinHeap();\n heap.build(powerVals);\n let top;\n while(k--) { // O(klogn)\n top = heap.removeTop();\n }\n return top[0];\n};\n\nfunction findPowerVal(num, dp) {\n if(dp.has(num)) {\n return dp.get(num);\n }\n let powerVal;\n if(num % 2 === 0) {\n powerVal = findPowerVal(num/2, dp) + 1;\n } else {\n powerVal = findPowerVal(3 * num + 1, dp) + 1;\n }\n dp.set(num, powerVal);\n return dp.get(num);\n}\n\nclass Heap {\n constructor(property) {\n this.data = [];\n }\n size() {\n return this.data.length;\n }\n build(arr) { // O(n)\n this.data = [...arr];\n for(let i = Math.floor((this.size() - 1)/2); i >= 0; --i) {\n this.heapify(i);\n }\n }\n heapify(i) { // O(logn)\n const left = 2 * i + 1, right = 2 * i + 2;\n let p = i;\n if(left < this.size() && this.compare(left, p)) {\n p = left;\n }\n if(right < this.size() && this.compare(right, p)) {\n p = right;\n }\n if(p !== i) {\n [this.data[p], this.data[i]] = [this.data[i], this.data[p]];\n this.heapify(p);\n }\n }\n removeTop() { // O(logn)\n if(this.size() === 1) {\n return this.data.pop();\n }\n const top = this.data[0];\n [this.data[0], this.data[this.size() - 1]] = [this.data[this.size() - 1], this.data[0]];\n this.data.pop();\n this.heapify(0);\n return top;\n }\n}\n\nclass MinHeap extends Heap {\n constructor() {\n super();\n }\n compare(a, b) {\n return this.data[a][1] < this.data[b][1] || (this.data[a][1] === this.data[b][1] && this.data[a][0] < this.data[b][0]);\n }\n}", "solution_java": "class Solution {\n public int getKth(int lo, int hi, int k) {\n\n int p = 0;\n int[][] powerArr = new int[hi - lo + 1][2];\n\n Map memo = new HashMap<>();\n for (int i = lo; i <= hi; i++)\n powerArr[p++] = new int[]{i, getPower(i, memo)};\n\n Arrays.sort(powerArr, (a1, a2) -> a1[1] - a2[1] == 0 ? a1[0] - a2[0] : a1[1] - a2[1]);\n\n return powerArr[k - 1][0];\n }\n\n private int getPower(int i, Map memo) {\n if (memo.containsKey(i)) return memo.get(i);\n\n if (i == 1) return 0;\n\n int power = 1 + (i % 2 == 0 ? getPower(i / 2, memo) : getPower(i * 3 + 1, memo));\n\n memo.put(i, power);\n return power;\n }\n}", "solution_c": "class Solution {\npublic:\n int getPower(int num) {\n if (num == 1)\n return 0;\n\n int res = 0;\n if (num %2 == 0)\n res += getPower(num/2);\n else\n res += getPower(3*num + 1);\n res++;\n return res;\n }\n\n int getKth(int lo, int hi, int k) {\n multimap um;\n for (int i = lo; i <= hi; i++) {\n um.insert({getPower(i), i});\n }\n int cnt = 1;\n int res = 0;\n for (auto iter = um.begin(); iter != um.end(); iter++) {\n if (cnt == k) {\n res = iter->second;\n }\n cnt++;\n }\n return res;\n }\n};" }, { "title": "Evaluate Boolean Binary Tree", "algo_input": "You are given the root of a full binary tree with the following properties:\n\n\n\tLeaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.\n\tNon-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.\n\n\nThe evaluation of a node is as follows:\n\n\n\tIf the node is a leaf node, the evaluation is the value of the node, i.e. True or False.\n\tOtherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.\n\n\nReturn the boolean result of evaluating the root node.\n\nA full binary tree is a binary tree where each node has either 0 or 2 children.\n\nA leaf node is a node that has zero children.\n\n \nExample 1:\n\nInput: root = [2,1,3,null,null,0,1]\nOutput: true\nExplanation: The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.\n\nExample 2:\n\nInput: root = [0]\nOutput: false\nExplanation: The root node is a leaf node and it evaluates to false, so we return false.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 <= Node.val <= 3\n\tEvery node has either 0 or 2 children.\n\tLeaf nodes have a value of 0 or 1.\n\tNon-leaf nodes have a value of 2 or 3.\n\n", "solution_py": "class Solution:\n def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n def recur(node):\n if not node.left and not node.right: #leaf node\n return True if node.val == 1 else False\n left = recur(node.left)\n right = recur(node.right)\n if node.val == 2: #if node is or\n return left or right\n if node.val == 3: #if node is and\n return left and right\n return recur(root)", "solution_js": "/**\n * @param {TreeNode} root\n * @return {boolean}\n */\nvar evaluateTree = function(root) {\n return root.val === 3 ? evaluateTree(root.left) && evaluateTree(root.right) :\n root.val === 2 ? evaluateTree(root.left) || evaluateTree(root.right) :\n root.val;\n};", "solution_java": "class Solution {\n public boolean evaluateTree(TreeNode root) {\n if(root.val == 1)\n return true;\n if(root.val == 0)\n return false;\n if(root.val == 2)\n return evaluateTree(root.left) || evaluateTree(root.right);\n return evaluateTree(root.left) && evaluateTree(root.right);\n }\n}", "solution_c": "class Solution {\npublic:\n bool evaluateTree(TreeNode* root) {\n\n if (!root->left and !root->right) return root->val;\n int l = evaluateTree(root->left);\n int r = evaluateTree(root->right);\n return (root->val == 2) ? l or r : l and r;\n }\n};" }, { "title": "All O`one Data Structure", "algo_input": "Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.\n\nImplement the AllOne class:\n\n\n\tAllOne() Initializes the object of the data structure.\n\tinc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1.\n\tdec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.\n\tgetMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\".\n\tgetMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\".\n\n\nNote that each function must run in O(1) average time complexity.\n\n \nExample 1:\n\nInput\n[\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n[[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\nOutput\n[null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]\n\nExplanation\nAllOne allOne = new AllOne();\nallOne.inc(\"hello\");\nallOne.inc(\"hello\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"hello\"\nallOne.inc(\"leet\");\nallOne.getMaxKey(); // return \"hello\"\nallOne.getMinKey(); // return \"leet\"\n\n\n \nConstraints:\n\n\n\t1 <= key.length <= 10\n\tkey consists of lowercase English letters.\n\tIt is guaranteed that for each call to dec, key is existing in the data structure.\n\tAt most 5 * 104 calls will be made to inc, dec, getMaxKey, and getMinKey.\n\n", "solution_py": "from collections import defaultdict\n\n\nclass Set(object):\n\n def __init__(self):\n self._dict = {}\n self._list = []\n self._len = 0\n\n def add(self, v):\n if v in self._dict:\n pass\n else:\n self._list.append(v)\n self._dict[v] = self._len\n self._len += 1\n\n def __contains__(self, item):\n return item in self._dict\n\n def remove(self, v):\n if v not in self._dict:\n pass\n else:\n idx = self._dict[v]\n\n if idx < self._len - 1:\n self._list[idx] = self._list[-1]\n self._dict[self._list[idx]] = idx\n\n del self._dict[v]\n self._list.pop()\n self._len -= 1\n\n def __iter__(self):\n return iter(self._list)\n\n def check(self):\n assert len(self._dict) == len(self._list)\n for idx, key in enumerate(self._list):\n assert self._dict[key] == idx\n\n def __len__(self):\n return self._len\n\n def __repr__(self):\n return f\"{self._dict}\\n{self._list}\"\n\n\nclass Node(object):\n\n def __init__(self, value):\n self.value = value\n self.prev = None\n self.next = None\n\n def set_prev(self, other_node):\n self.prev = other_node\n if other_node is not None:\n other_node.next = self\n\n def set_next(self, other_node):\n self.next = other_node\n if other_node is not None:\n other_node.prev = self\n\n def __repr__(self):\n return str(self.value)\n\n\nclass SortedKeyList(object):\n\n def __init__(self):\n self.head = Node(value=0)\n self.tail = Node(value=float(\"inf\"))\n self.head.set_next(self.tail)\n\n def is_empty(self):\n return self.head.next is self.tail\n\n def min_key(self):\n if self.is_empty():\n return None\n else:\n return self.head.next.value\n\n def max_key(self):\n if self.is_empty():\n return None\n else:\n return self.tail.prev.value\n\n def incr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value + 1\n next_node = orig_node.next\n if next_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_prev(orig_node)\n new_node.set_next(next_node)\n return self\n\n def decr_key(self, orig_node):\n orig_value = orig_node.value\n new_value = orig_value - 1\n prev_node = orig_node.prev\n if prev_node.value == new_value:\n return self\n else:\n new_node = Node(new_value)\n new_node.set_next(orig_node)\n new_node.set_prev(prev_node)\n return self\n\n def delete_node(self, node):\n prev_node = node.prev\n next_node = node.next\n prev_node.set_next(next_node)\n return self\n\n def __repr__(self):\n a = []\n node = self.head.next\n while True:\n if node is self.tail:\n break\n\n assert node.next.prev is node\n assert node.prev.next is node\n\n a.append(node.value)\n node = node.next\n return str(a)\n\n\nclass AllOne:\n\n def __init__(self):\n self.count_list = SortedKeyList()\n self.counter = defaultdict(lambda: self.count_list.head)\n self.keyed_by_count = defaultdict(set)\n\n def __repr__(self):\n return f\"count_list={self.count_list}\\ncounter={dict(self.counter)}\\nkeyed_by_count={dict(self.keyed_by_count)}\"\n\n def inc(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.incr_key(orig_count_node)\n new_count_node = orig_count_node.next\n new_count = new_count_node.value\n assert new_count == orig_count + 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n if orig_count_node.value > 0:\n self.count_list.delete_node(orig_count_node)\n\n def dec(self, key: str) -> None:\n orig_count_node = self.counter[key]\n orig_count = orig_count_node.value\n\n self.count_list.decr_key(orig_count_node)\n new_count_node = orig_count_node.prev\n new_count = new_count_node.value\n assert new_count == orig_count - 1\n\n self.counter[key] = new_count_node\n\n if key in self.keyed_by_count[orig_count]:\n self.keyed_by_count[orig_count].remove(key)\n self.keyed_by_count[new_count].add(key)\n\n if new_count == 0:\n del self.counter[key]\n\n if len(self.keyed_by_count[orig_count]) == 0:\n del self.keyed_by_count[orig_count]\n self.count_list.delete_node(orig_count_node)\n\n def getMaxKey(self) -> str:\n max_count = self.count_list.max_key()\n if max_count is not None:\n return next(iter(self.keyed_by_count[max_count]))\n else:\n return \"\"\n\n def getMinKey(self) -> str:\n min_count = self.count_list.min_key()\n if min_count is not None:\n return next(iter(self.keyed_by_count[min_count]))\n else:\n return \"\"\n\n\ndef drive(m, p):\n s = AllOne()\n\n naive_counter = defaultdict(int)\n\n for method, param in zip(m, p):\n if method in (\"inc\", \"dec\"):\n word = param[0]\n\n if method == \"inc\":\n s.inc(word)\n naive_counter[word] += 1\n\n elif method == 'dec':\n s.dec(word)\n naive_counter[word] -= 1\n\n if naive_counter[word] == 0:\n del naive_counter[word]\n\n tmp_counter = defaultdict(set)\n for k, v in naive_counter.items():\n tmp_counter[v].add(k)\n\n sorted_keys = sorted(tmp_counter.keys())\n min_key = sorted_keys[0]\n max_key = sorted_keys[-1]\n\n if s.getMaxKey() not in tmp_counter[max_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n if s.getMinKey() not in tmp_counter[min_key]:\n print(\"Oh No!!!\")\n return s, naive_counter, tmp_counter\n\n return None, None, None\n\n\nif __name__ == '__main__':\n m = [\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n p = [[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\n s, naive_counter, tmp_counter = drive(m, p)", "solution_js": "var AllOne = function() {\n this.map = new Map();\n this.pre = '';\n};\n\n/** \n * @param {set} map\n * @param {function} handler\n * @return {map}\n */\nAllOne.prototype.sort = function(map, handler) {\n return new Map([...map].sort(handler));\n};\n\n/** \n * @param {string} key\n * @return {void}\n */\nAllOne.prototype.inc = function(key) {\n this.map.set(key, this.map.get(key) + 1 || 1);\n this.pre = 'inc';\n};\n\n/** \n * @param {string} key\n * @return {void}\n */\nAllOne.prototype.dec = function(key) {\n this.map.get(key) == 1 ? this.map.delete(key) : this.map.set(key, this.map.get(key) - 1);\n this.pre = 'dec';\n};\n\n/**\n * @return {string}\n */\nAllOne.prototype.getMaxKey = function() {\n if (this.pre != 'max') {\n this.map = this.sort(this.map, (a, b) => b[1] - a[1]);\n }\n this.pre = 'max';\n return this.map.keys().next().value || '';\n};\n\n/**\n * @return {string}\n */\nAllOne.prototype.getMinKey = function() {\n if (this.pre != 'min') {\n this.map = this.sort(this.map, (a, b) => a[1] - b[1]);\n }\n this.pre = 'min';\n return this.map.keys().next().value || '';\n};", "solution_java": "//Intuitions get from the top answer by @AaronLin1992\nclass AllOne {\n //Thoughts\n //inc() and dec() can be done with a Simple Map, but how do we getMaxKey() and getMinKey() in O(1)?\n //in order to get max and/or min on the fly, we need to maintain some kind of ordering so that we can always access max and min\n //to maintain some kind of ordering, the first thing we think about is arrays/lists, however, arrays/lists when insert and delete in the middle, it is O(N) operation\n //so instead, a linked list might work\n //as a result, we considering using Map(s) and LinkedList for our supporting data structures, details below\n \n private Map stringToBucket; //maps a string to bucket\n private Map countToBucket; //maps string count to bucket, note that because when we design this we can have multiple strings in a bucket, that makes it convenient so that for each count, we only need 1 bucket, thus the map data structure\n private BucketList bucketList;\n \n //first, we need to create a class for the LinkedList elements\n class Bucket {\n private Bucket prev;\n private Bucket next;\n \n private int count; //recording the count of instances\n private Set keys; //note that we are using Set of Strings. The reason is because multiple Strings can have the same count and we want to put them in one bucket. This makes the problem easier to solve instead of putting them into different buckets.\n \n Bucket() {\n this.keys = new HashSet<>();\n }\n \n Bucket(String key) {\n this();\n this.count = 1;\n this.keys.add(key);\n }\n \n }\n \n //second, we need to create a linked list data structure of buckets\n class BucketList {\n private Bucket dummyHead; //the fake head before the real head //useful for getMinKey()\n private Bucket dummyTail; //the fake tail before the real tail //useful for getMaxKey()\n \n public BucketList() {\n dummyHead = new Bucket();\n dummyTail = new Bucket();\n dummyHead.next = dummyTail;\n dummyTail.prev = dummyHead;\n }\n \n public Bucket createNewBucket(String key) {\n Bucket bucket = new Bucket(key);\n \n Bucket nextBucket = dummyHead.next;\n dummyHead.next = bucket;\n bucket.prev = dummyHead;\n nextBucket.prev = bucket;\n bucket.next = nextBucket;\n \n return bucket;\n }\n \n public Bucket createBucketToTheRight(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket nextBucket = fromBucket.next;\n fromBucket.next = toBucket;\n toBucket.prev = fromBucket;\n nextBucket.prev = toBucket;\n toBucket.next = nextBucket;\n \n return toBucket;\n }\n \n public Bucket createBucketToTheLeft(Bucket fromBucket, String key, int count) {\n //initialize\n Bucket toBucket = new Bucket(key);\n toBucket.count = count;\n \n Bucket prevBucket = fromBucket.prev;\n prevBucket.next = toBucket;\n toBucket.prev = prevBucket;\n fromBucket.prev = toBucket;\n toBucket.next = fromBucket;\n \n return toBucket;\n }\n \n public boolean clean(Bucket oldBucket) {//clean bucket if bucket does not have any keys\n if (!oldBucket.keys.isEmpty()) {\n return false;\n }\n \n removeBucket(oldBucket);\n \n return true;\n }\n \n public void removeBucket(Bucket bucket) {\n Bucket prevBucket = bucket.prev;\n Bucket nextBucket = bucket.next;\n \n prevBucket.next = nextBucket;\n nextBucket.prev = prevBucket;\n }\n }\n \n\n public AllOne() {\n this.stringToBucket = new HashMap<>();\n this.countToBucket = new HashMap<>();\n this.bucketList = new BucketList();\n }\n \n public void inc(String key) {\n //first check if the string already present\n if (!stringToBucket.containsKey(key)) { //if not present \n Bucket bucket = null;\n \n //check if there is count of 1 bucket already\n if (!countToBucket.containsKey(1)) { //if does not contain count of 1\n //we need to create a new bucket for count of 1 and add to the head (the minimum). Because count 1 should be the minimum exists in the bucket list\n bucket = bucketList.createNewBucket(key);\n } else { //if contains count of 1\n //then we just need to add the key to the bucket\n bucket = countToBucket.get(1);\n bucket.keys.add(key);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, bucket);\n countToBucket.put(1, bucket);\n } else { //if the key alreay present\n //first of all we need to get the current count for the key\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count++; //increment 1\n //don't forget that we need to remove the key from existing bucket\n oldBucket.keys.remove(key);\n \n //now let's add the key with new count\n if (countToBucket.containsKey(count)) { //if there is already a bucket for this count\n //then just add to the set of keys\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else { //if there is no bucket for this count, create a new bucket, but where to place it? Ans: to the right of the old bucket\n newBucket = bucketList.createBucketToTheRight(oldBucket, key, count); \n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n }\n \n public void dec(String key) {\n //since it is given that \"It is guaranteed that key exists in the data structure before the decrement.\" we don't do additional validation for key exists here\n Bucket oldBucket = stringToBucket.get(key);\n Bucket newBucket = null;\n \n int count = oldBucket.count;\n count--; //decrement\n oldBucket.keys.remove(key);\n \n //special scenario - when count == 0\n if (count == 0) {\n stringToBucket.remove(key);\n } else {\n //now let's find a new bucket for the decremented count\n if (countToBucket.containsKey(count)) {//if there is already a bucket for the count\n newBucket = countToBucket.get(count);\n newBucket.keys.add(key);\n } else {//if there is no bucket for the count, then following similar logic as before, we need to add a bucket to the left of the existing bucket\n newBucket = bucketList.createBucketToTheLeft(oldBucket, key, count);\n }\n \n //don't forget to update the maps\n stringToBucket.put(key, newBucket);\n countToBucket.putIfAbsent(count, newBucket);\n }\n \n //special scenario: if old bucket don't have any keys after removing the last key, then we need to remove the entire old bucket from the bucket list\n if (bucketList.clean(oldBucket)) {\n countToBucket.remove(oldBucket.count); //remove from map because the old bucket was removed\n }\n }\n \n public String getMaxKey() {\n Set maxSet = bucketList.dummyTail.prev.keys;\n \n return maxSet.isEmpty() ? \"\" : maxSet.iterator().next(); //if maxSet is empty, that means the bucketList don't have actual buckets\n \n }\n \n public String getMinKey() {\n Set minSet = bucketList.dummyHead.next.keys;\n \n return minSet.isEmpty() ? \"\" : minSet.iterator().next(); //if minSet is empty, that means the bucketList don't have actual buckets\n }\n}\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne obj = new AllOne();\n * obj.inc(key);\n * obj.dec(key);\n * String param_3 = obj.getMaxKey();\n * String param_4 = obj.getMinKey();\n */", "solution_c": "class AllOne {\npublic:\n map> minmax;\n unordered_map count;\n AllOne() {\n \n }\n \n void inc(string key) {\n int was = count[key]++;\n if(was>0) {\n minmax[was].erase(key);\n if(minmax[was].size()==0) minmax.erase(was);\n }\n minmax[was+1].insert(key);\n }\n \n void dec(string key) {\n int was = count[key]--;\n minmax[was].erase(key);\n if(minmax[was].size()==0) minmax.erase(was);\n if(was-1==0) {\n count.erase(key);\n }else {\n minmax[was-1].insert(key);\n }\n }\n \n string getMaxKey() {\n return minmax.size() == 0 ? \"\" : *minmax.rbegin()->second.begin();\n }\n \n string getMinKey() { \n return minmax.size() == 0 ? \"\" : *minmax.begin()->second.begin();\n }\n};\n\n/**\n * Your AllOne object will be instantiated and called as such:\n * AllOne* obj = new AllOne();\n * obj->inc(key);\n * obj->dec(key);\n * string param_3 = obj->getMaxKey();\n * string param_4 = obj->getMinKey();\n */" }, { "title": "Numbers At Most N Given Digit Set", "algo_input": "Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.\n\nReturn the number of positive integers that can be generated that are less than or equal to a given integer n.\n\n \nExample 1:\n\nInput: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\nOutput: 20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n\n\nExample 2:\n\nInput: digits = [\"1\",\"4\",\"9\"], n = 1000000000\nOutput: 29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.\n\n\nExample 3:\n\nInput: digits = [\"7\"], n = 8\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= digits.length <= 9\n\tdigits[i].length == 1\n\tdigits[i] is a digit from '1' to '9'.\n\tAll the values in digits are unique.\n\tdigits is sorted in non-decreasing order.\n\t1 <= n <= 109\n\n", "solution_py": "class Solution():\n def atMostNGivenDigitSet(self, digits, n):\n cache = {}\n target = str(n)\n\n def helper(idx, isBoundary, isZero):\n if idx == len(target): return 1\n if (idx, isBoundary, isZero) in cache: return cache[(idx, isBoundary, isZero)]\n \n res = 0\n if isZero and idx != len(target)-1:\n res+= helper(idx+1, False, True)\n for digit in digits:\n if isBoundary and int(digit) > int(target[idx]): continue\n res+= helper(idx+1, True if isBoundary and digit == target[idx] else False, False)\n\n cache[(idx, isBoundary, isZero)] = res\n return res\n\n return helper(0, True, True)", "solution_js": "var atMostNGivenDigitSet = function(digits, n) {\n const asString = \"\"+ n;\n let smaller = 0;\n let prev = 1;\n for (let i = asString.length - 1; i >= 0; --i) {\n const L = asString.length - 1 - i;\n const num = +asString[i];\n let equal = 0;\n let less = 0;\n for (let digit of digits) {\n if (digit == num) {\n equal = 1;\n }\n if (digit > num) {\n break;\n }\n if (digit < num) {\n less++;\n }\n }\n prev = (less * Math.pow(digits.length, L)) + equal * prev;\n if (L < asString.length - 1) {\n smaller += Math.pow(digits.length, L + 1);\n }\n }\n return smaller + prev;\n};", "solution_java": "class Solution {\n \n \n // DIGIT DP IS LOVE \n Integer[][][] digitdp;\n public int solve(String num, int pos, boolean bound, Integer[] dig,boolean lead) {\n\n if (pos == num.length()) {\n return 1;\n }\n\n int maxDigit = -1;\n \n if(digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] !=null) return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0];\n\n if (bound) {\n maxDigit = num.charAt(pos) - '0';\n } else {\n maxDigit = 9;\n }\n\n int ans = 0;\n for (int i = 0; i <=maxDigit; i++) {\n \n // 0 can only be leading \n if(i==0 && lead){\n\n ans += solve(num,pos+1,false,dig,lead);\n \n }else{\n \n int res = Arrays.binarySearch(dig,i);\n\n if(res>=0){\n // lead = false; // now it is not possible to 0 to be in lead any more once any other call has been made\n ans += solve(num, pos + 1, bound & (i == num.charAt(pos)-'0'), dig,false);\n }\n \n }\n }\n\n return digitdp[pos][(bound==true)?1:0][(lead==true)?1:0] = ans;\n\n }\n\n public int atMostNGivenDigitSet(String[] digits, int n) {\n\n String num = n + \"\";\n Integer[] dig = new Integer[digits.length];\n for(int i=0;igetDigits(int n) {\n vectordigits;\n while(n) {\n digits.push_back(n % 10);\n n /= 10;\n }\n\n reverse(digits.begin(), digits.end());\n return digits;\n }\n\n\n int solve(int idx, bool flag, vector&digits, vector&number) {\n if(!flag) {\n int res = 1;\n for(int i = idx; i= number.size()) return 1;\n\n int curr = 0;\n\n for(int dig: digits) {\n if(dig < number[idx]) {\n curr += solve(idx + 1, false, digits, number);\n } else if(dig == number[idx]) {\n curr += solve(idx + 1, true, digits, number);\n } else break;\n }\n\n return curr;\n }\n\n\n int atMostNGivenDigitSet(vector& digits, int n) {\n int len = countLen(n);\n vectornums;\n for(string str: digits) {\n nums.push_back(stoi(str));\n }\n sort(nums.begin(), nums.end());\n ll res = 0;\n \n \n for(int i = 1; inumber = getDigits(n);\n \n res += solve(0, true, nums, number);\n\n return res;\n\n }\n};" }, { "title": "Circle and Rectangle Overlapping", "algo_input": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.\n\nReturn true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.\n\n \nExample 1:\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput: true\nExplanation: Circle and rectangle share the point (1,0).\n\n\nExample 2:\n\nInput: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput: false\n\n\nExample 3:\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput: true\n\n\n \nConstraints:\n\n\n\t1 <= radius <= 2000\n\t-104 <= xCenter, yCenter <= 104\n\t-104 <= x1 < x2 <= 104\n\t-104 <= y1 < y2 <= 104\n\n", "solution_py": "class Solution:\n def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n \n def find(a1, a2, aCenter):\n if a1 <= aCenter and aCenter <= a2:\n return 0 \n elif a1 > aCenter:\n return a1 - aCenter\n else:\n return aCenter - a2\n\n return (find(x1, x2, xCenter))**2 + (find(y1, y2, yCenter))**2 <= radius**2 \n\t```", "solution_js": "var checkOverlap = function(radius, xCenter, yCenter, x1, y1, x2, y2) {\n const closestX = clamp(xCenter, x1, x2);\n const closestY = clamp(yCenter, y1, y2);\n \n const dist = (xCenter - closestX)**2 + (yCenter - closestY)**2;\n \n return dist <= radius * radius ? true : false;\n \n \n function clamp(val, min, max) {\n if (val < min) return min;\n if (max < val) return max;\n return val;\n }\n};", "solution_java": "class Solution\n{\n public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2)\n {\n return Math.pow(Math.max(x1,Math.min(x2,xCenter))-xCenter,2)\n + Math.pow(Math.max(y1,Math.min(y2,yCenter))-yCenter,2) <= radius*radius;\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) {\n //nearest_x = x1 when xCenter x2) ? x2 : xCenter;\n //same logic for nearest_y as in nearest_x\n int nearest_y = (yCenter < y1) ? y1 : (yCenter > y2) ? y2 : yCenter;\n int dist_x = xCenter - nearest_x, dist_y = yCenter - nearest_y;\n return dist_x * dist_x + dist_y * dist_y <= radius * radius;\n }\n};" }, { "title": "Rotated Digits", "algo_input": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.\n\nA number is valid if each digit remains a digit after rotation. For example:\n\n\n\t0, 1, and 8 rotate to themselves,\n\t2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),\n\t6 and 9 rotate to each other, and\n\tthe rest of the numbers do not rotate to any other number and become invalid.\n\n\nGiven an integer n, return the number of good integers in the range [1, n].\n\n \nExample 1:\n\nInput: n = 10\nOutput: 4\nExplanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 0\n\n\nExample 3:\n\nInput: n = 2\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "class Solution:\n def rotatedDigits(self, n: int) -> int:\n d={\n 0:0,\n 1:1,\n 2:5,\n 3:None,\n 4: None,\n 5:2,\n 6:9,\n 7:None,\n 8:8,\n 9:6\n }\n res=0\n for i in range(n+1):\n t=i\n pos=0\n temp=0\n status=True\n while t>0:\n r=d[t%10] #Every Digit Rotation Is Must, We Don't Have Choice To Leave It Without Rotating\n if r is None:\n status=False\n break\n\n temp+=((10**pos)*r)\n pos+=1\n t=t//10\n\n if temp!=i and status:\n res+=1\n return res", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar rotatedDigits = function(n) {\n let count=0;\n for(let i=1;i<=n;i++){\n let str=i.toString().split(\"\");\n let f=str.filter(s=> s!=1 && s!=0 && s!=8);\n if(f.length===0) continue;\n let g=f.filter(s=> s!=5 && s!=2 && s!=6 && s!=9);\n if(g.length===0) count++;\n }\n return count;\n};", "solution_java": "class Solution {\n public int rotatedDigits(int n) {\n int ans=0;\n for(int i=1; i<=n; i++){\n int k = i;\n boolean bool1=true; boolean bool2=false;\n while(k>0){\n int m=k%10;\n if(m==3 || m==4 || m==7){ bool1=false; break; }\n else if(m==2 || m==5 || m==6 || m==9){ bool2=true; }\n k/=10;\n }\n if(bool1 && bool2){ ans++; }\n }\n return ans;\n }\n}", "solution_c": "class Solution\n{\npublic:\n bool isValid(int n)\n {\n bool check = false;\n while (n > 0)\n {\n int k = n % 10;\n if (k == 2 || k == 5 || k == 6 || k == 9)\n check = true;\n if (k == 3 || k == 4 || k == 7)\n return false;\n n /= 10;\n }\n return check;\n }\n int rotatedDigits(int n)\n {\n vector dp(n + 1, 0);\n for (int i = 2; i <= n; i++)\n {\n if (isValid(i))\n dp[i]++;\n dp[i] += dp[i - 1];\n }\n return dp[n];\n }\n};" }, { "title": "Maximum Fruits Harvested After at Most K Steps", "algo_input": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.\n\nYou are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.\n\nReturn the maximum total number of fruits you can harvest.\n\n \nExample 1:\n\nInput: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput: 9\nExplanation: \nThe optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.\n\n\nExample 2:\n\nInput: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput: 14\nExplanation: \nYou can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.\n\n\nExample 3:\n\nInput: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput: 0\nExplanation:\nYou can move at most k = 2 steps and cannot reach any position with fruits.\n\n\n \nConstraints:\n\n\n\t1 <= fruits.length <= 105\n\tfruits[i].length == 2\n\t0 <= startPos, positioni <= 2 * 105\n\tpositioni-1 < positioni for any i > 0 (0-indexed)\n\t1 <= amounti <= 104\n\t0 <= k <= 2 * 105\n\n", "solution_py": "class Solution:\n def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n arr = [0 for _ in range(2*k+1)]\n for pos, numOfFruit in fruits:\n if pos < startPos-k or pos > startPos+k:\n continue\n arr[pos-(startPos-k)] += numOfFruit\n\n left, right = sum(arr[:k+1]), sum(arr[k:])\n maxSeen = max(left, right)\n\n turn = 1 # turning point\n for i in range(2, k+1, 2):\n left = left-arr[i-2]-arr[i-1]+arr[k+turn]\n right = right-arr[~(i-2)]-arr[~(i-1)]+arr[k-turn]\n maxSeen = max(maxSeen, left, right)\n turn += 1\n\n return maxSeen", "solution_js": "/**\n * @param {number[][]} fruits\n * @param {number} startPos\n * @param {number} k\n * @return {number}\n */\nvar maxTotalFruits = function(fruits, startPos, k) {\n \n let n = Math.max(fruits[fruits.length-1][0], startPos)+1;\n let numFruits = new Array(n).fill(0);\n let sums = new Array(n).fill(0);\n for(let obj of fruits) {\n let [pos, num] = obj;\n numFruits[pos] = num;\n }\n sums[startPos] = numFruits[startPos] ;\n for(let i = startPos+1; i < n && i <= startPos + k; i++) {\n sums[i] = sums[i-1] + numFruits[i];\n }\n for(let i = startPos-1; i >=0 && i >= startPos - k; i--) {\n sums[i] = sums[i+1] + numFruits[i];\n }\n //console.log(sums);\n let output = 0;\n for(let leftMoves = k; leftMoves >= 0; leftMoves--) {\n let rightMoves = Math.max(k - 2*leftMoves, 0);\n let leftPos = Math.max(0, startPos - leftMoves);\n let rightPos = Math.min(n-1, startPos + rightMoves);\n let count = sums[leftPos] + sums[rightPos] - sums[startPos];\n output = Math.max(output, count);\n }\n for(let rightMoves = k; rightMoves >= 0; rightMoves--) {\n let leftMoves = Math.max(k - 2*rightMoves, 0);\n let leftPos = Math.max(0, startPos - leftMoves);\n let rightPos = Math.min(n-1, startPos + rightMoves);\n let count = sums[leftPos] + sums[rightPos] - sums[startPos];\n output = Math.max(output, count);\n }\n return output;\n};", "solution_java": "class Solution {\n public int maxTotalFruits(int[][] fruits, int startPos, int k) {\n int n = fruits.length;\n int posOfLastFruit = fruits[n-1][0];\n int prefixArr[] = new int[posOfLastFruit + 1];\n int start = Math.max(startPos - k, 0);\n int end = Math.min(startPos + k, prefixArr.length-1);\n\n if(startPos > posOfLastFruit) {\n int diff = startPos - posOfLastFruit;\n startPos = posOfLastFruit;\n k = k - diff;\n if(k == 0)\n return fruits[posOfLastFruit][1];\n else if(k < 0)\n return 0;\n }\n\n for(int i = 0 ; i < n ; i++) {\n prefixArr[fruits[i][0]] = fruits[i][1];\n }\n\n int curr = 0;\n for(int i = startPos-1 ; i >= start ; i--) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n curr = 0;\n for(int i = startPos+1 ; i <= end ; i++) {\n curr += prefixArr[i];\n prefixArr[i] = curr;\n }\n\n int minimum = prefixArr[startPos];\n prefixArr[startPos] = 0;\n int ans = 0;\n\n for(int i = start ; i < startPos ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = startPos - i;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i + stepsRemaining;\n\n if(endIndex > startPos && endIndex < prefixArr.length) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex >= prefixArr.length) {\n maxCurrPossible += prefixArr[prefixArr.length-1];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n for(int i = startPos+1 ; i <= end ; i++) {\n int maxCurrPossible = prefixArr[i];\n int stepsAlreadyWalked = i - startPos;\n int stepsRemaining = k - stepsAlreadyWalked;\n int endIndex = i - stepsRemaining;\n\n if(endIndex < startPos && endIndex >= 0) {\n maxCurrPossible += prefixArr[endIndex];\n } else if(endIndex < 0) {\n maxCurrPossible += prefixArr[0];\n }\n\n ans = Math.max(ans, maxCurrPossible);\n }\n\n return ans + minimum;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxTotalFruits(vector>& fruits, int startPos, int k) {\n vector arr;\n for (int i=0; i<2*k+1; ++i) {\n arr.push_back(0);\n }\n\n for (int i=0; i startPos+k)) continue;\n arr[fruits[i][0]-(startPos-k)] += fruits[i][1];\n }\n\n int left = 0, right = 0;\n for (int i = 0; i <= k; ++i) {\n left += arr[i];\n right += arr[k+i];\n }\n int maxSeen = max(left, right);\n int L = arr.size();\n int turn = 1;\n for (int i = 2; i < k+1; i += 2) {\n left = left+arr[k+turn]-arr[i-1]-arr[i-2];\n right = right+arr[k-turn]-arr[L-1-(i-1)]-arr[L-1-(i-2)];\n if (left > maxSeen) maxSeen = left;\n if (right > maxSeen) maxSeen = right;\n turn++;\n }\n return maxSeen;\n\n }\n};" }, { "title": "Surrounded Regions", "algo_input": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\n \nExample 1:\n\nInput: board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nOutput: [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nExplanation: Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.\n\n\nExample 2:\n\nInput: board = [[\"X\"]]\nOutput: [[\"X\"]]\n\n\n \nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 <= m, n <= 200\n\tboard[i][j] is 'X' or 'O'.\n\n", "solution_py": "# The question is an awesome example of multi-source bfs.\n# The intuition is to add the boundary to a heap if it is 'O'.\n# Start the bfs from the nodes added and since you're using queue(FIFO) this bfs will check for inner matrix elements and if they are also 'O' just start\n# convertin all these 'O's to 'E's. \n# The last step is to traverse the matrix and if the element is still 'O' turn it to 'X' if it is 'E' turn it to 'O' and we get our answer.\n# Pro-Tip -> Try to reduce the number of append operations in python. The lesser the append operations the better is the runtime!\nfrom collections import deque\nclass Solution:\n def solve(self, bb: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n heap = deque()\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n r, c = len(bb), len(bb[0])\n for i in range(r):\n if bb[i][0] == 'O': heap.append((i, 0))\n if bb[i][c - 1] == 'O': heap.append((i, c - 1))\n for i in range(1, c - 1):\n if bb[0][i] == 'O': heap.append((0, i))\n if bb[r - 1][i] == 'O': heap.append((r - 1, i))\n visited = set()\n def isValid(nr, nc):\n if 0 <= nr < r and 0 <= nc < c: return True\n else: return False\n while heap:\n ri, ci = heap.popleft()\n bb[ri][ci] = 'E'\n for i, j in directions:\n nr, nc = ri + i, ci + j\n if isValid(nr, nc) and (nr, nc) not in visited and bb[nr][nc] == 'O':\n heap.append((nr, nc))\n visited.add((nr, nc))\n for i in range(r):\n for j in range(c):\n if bb[i][j] == 'O':\n bb[i][j] = 'X'\n if bb[i][j] == 'E':\n bb[i][j] = 'O'\n ", "solution_js": "// time O(n * m) | space O(1)\n\n// We essentially invert this question\n// Instead of looking whether an 'O' node is surrounded,\n// we check if an 'O' node is on the edge (outer layer can't be surrounded)\n// and check if that is connected with any other nodes 'O' nodes (top, down, left, right).\n// We do no care if it is not connected to an 'O' edge node and thus never dfs for it.\nvar solve = function(board) {\n if (!board.length) return [];\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n // Only dfs if an 'O' and on the edge\n if (board[i][j] === 'O' && (i === 0 || i === board.length - 1 || j === 0 || j === board[0].length - 1)) {\n dfs(i, j);\n }\n }\n }\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n if (board[i][j] === 'V') {\n board[i][j] = 'O';\n } else {\n board[i][j] = 'X';\n }\n }\n }\n\n return board;\n\n function dfs(r, c) {\n if (r < 0 || r >= board.length || c < 0 || c >= board[0].length || board[r][c] === 'X' || board[r][c] === 'V') {\n return;\n }\n\n board[r][c] = 'V';\n\n dfs(r + 1, c);\n dfs(r - 1, c);\n dfs(r, c - 1);\n dfs(r, c + 1);\n }\n};", "solution_java": "class Solution {\n boolean isClosed = true;\n\n public void solve(char[][] board) {\n int m = board.length;\n int n = board[0].length;\n\n // To identify all those O which are adjacent and unbounded by 'X', we put a temporary value\n for(int i=0; i= board.length || j>=board[0].length || board[i][j] != 'O') return;\n\n board[i][j] = 'T'; // to put a temperory mark/ to mark as visited\n\n dfs(board, i, j+1); // Top\n dfs(board, i, j-1); // Bottom\n dfs(board, i+1, j); // Right\n dfs(board, i-1, j); // Left\n }\n}", "solution_c": "class Solution {\npublic:\n int n,m; int visited[201][201] = {0};\n // Breadth First Search\n // Flood Fill Algorithm\n void bfs(vector>& board, int x, int y){\n queue q; q.push(m*x+y);\n visited[x][y] = 1;\n int curr,i,j;\n while(!q.empty()){\n curr = q.front();\n q.pop();\n i = curr/m; j = curr%m;\n board[i][j] = 'O';\n if(i > 0 && !visited[i-1][j] && board[i-1][j] == 'C'){\n visited[i-1][j] = 1;\n q.push(m*(i-1)+j);\n }\n if(i < n-1 && !visited[i+1][j] && board[i+1][j] == 'C'){\n visited[i+1][j] = 1;\n q.push(m*(i+1)+j);\n }\n if(j > 0 && !visited[i][j-1] && board[i][j-1] == 'C'){\n visited[i][j-1] = 1;\n q.push(m*i+j-1);\n }\n if(j < m-1 && !visited[i][j+1] && board[i][j+1] == 'C'){\n visited[i][j+1] = 1;\n q.push(m*i+j+1);\n }\n }\n }\n void solve(vector>& board) {\n n = board.size(); m = board[0].size();\n // Marking the regions to capture\n // mark all the O to C\n for(int i=0; i int:\n dc = {}\n \n for i in range(len(arr)):\n if arr[i] not in dc:\n dc[arr[i]] = 1\n else:\n dc[arr[i]] = dc[arr[i]] + 1\n mx = -1\n for key,value in dc.items():\n if key == value:\n mx = max(key, mx)\n return mx", "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\n \nvar findLucky = function(arr) {\n\tlet obj = {};\n\tarr.map((num) => {\n\t\tobj[num] = obj[num] + 1 || 1;\n\t});\n\n\tlet answer = -1;\n\tfor (let key in obj) {\n\t\tif (Number(key) === obj[key]) answer = Math.max(answer, Number(key));\n\t}\n\n\treturn answer;\n};", "solution_java": "class Solution {\n public int findLucky(int[] arr) {\n HashMap map = new HashMap<>();\n for(int i : arr){\n map.put(i, map.getOrDefault(i,0)+1);\n }\n System.out.print(map);\n int max = 0;\n for (Map.Entry e : map.entrySet()){\n int temp = 0;\n if(e.getKey() == (int)e.getValue()){\n temp = (int)e.getKey();\n }\n if(max < temp){\n max= temp;\n }\n }\n if(max != 0)return max;\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int findLucky(vector& arr) {\n // sort(arr.begin(),arr.end());\n mapmp;\n vectorv;\n for(int i=0;i List[int]:\n result = self.function(spells,potions,success)\n return result\n\n def function(self,arr1,arr2,success):\n n2 = len(arr2)\n arr2.sort() #Sorting Enables Us To Do Binary Search\n ans = []\n for i in arr1:\n val = math.ceil(success/i) #Finding the Value Of Portion With Least Strength So That It Can Be Greater Than Success\n idx = bisect.bisect_left(arr2,val) #Finding The Left Most Index So That The Value Can Be Inserted\n res = n2-idx+1 #Calculating the remaining numbers after finding the suitable index\n ans.append(res-1)\n return ans", "solution_js": "/**\n * @param {number[]} spells\n * @param {number[]} potions\n * @param {number} success\n * @return {number[]}\n */\n var successfulPairs = function(spells, potions, success) {\n let res = [];\n potions.sort((a, b) => b-a);\n let map = new Map();\n \n for(let i=0; i= success) {\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n pairs[i] = m - left;\n }\n return pairs;\n }\n}", "solution_c": "class Solution {\npublic:\n vector successfulPairs(vector& spells, vector& potions, long long success) {\n \n vector res;\n int n(size(potions));\n sort(begin(potions), end(potions));\n \n for (auto& spell : spells) {\n int start(0), end(n);\n while (start < end) {\n int mid = start + (end-start)/2;\n ((long long)spell*potions[mid] >= success) ? end = mid : start = mid+1;\n }\n res.push_back(n-start);\n }\n return res;\n }\n};" }, { "title": "Shortest Path to Get All Keys", "algo_input": "You are given an m x n grid grid where:\n\n\n\t'.' is an empty cell.\n\t'#' is a wall.\n\t'@' is the starting point.\n\tLowercase letters represent keys.\n\tUppercase letters represent locks.\n\n\nYou start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.\n\nIf you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.\n\nFor some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\n\nReturn the lowest number of moves to acquire all keys. If it is impossible, return -1.\n\n \nExample 1:\n\nInput: grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput: 8\nExplanation: Note that the goal is to obtain all the keys not to open all the locks.\n\n\nExample 2:\n\nInput: grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput: 6\n\n\nExample 3:\n\nInput: grid = [\"@Aa\"]\nOutput: -1\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 30\n\tgrid[i][j] is either an English letter, '.', '#', or '@'.\n\tThe number of keys in the grid is in the range [1, 6].\n\tEach key in the grid is unique.\n\tEach key in the grid has a matching lock.\n\n", "solution_py": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n \n m=len(grid)\n n=len(grid[0])\n visited=set()\n \n steps=0\n q=deque([])\n keyCt=0\n \n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"@\":\n q.append((i,j,''))\n elif grid[i][j].islower():\n keyCt+=1\n \n while q:\n for _ in range(len(q)):\n curr_x,curr_y,keys = q.popleft()\n if (curr_x,curr_y,keys) in visited:\n continue\n \n visited.add((curr_x,curr_y,keys))\n \n if len(keys)==keyCt:\n return steps\n \n for x,y in ((0,1),(1,0),(-1,0),(0,-1)):\n nx=curr_x+x\n ny=curr_y+y\n if nx<0 or ny<0 or nx>=m or ny>=n or grid[nx][ny]=='#' or (nx,ny,keys) in visited:\n continue\n \n curr=grid[nx][ny] \n if curr in 'abcdef' and curr not in keys:\n q.append((nx,ny,keys+curr)) \n elif curr.isupper() and curr.lower() not in keys:\n continue\n else:\n q.append((nx,ny,keys))\n steps+=1\n \n return -1", "solution_js": "var shortestPathAllKeys = function(grid) {\n const n = grid.length;\n const m = grid[0].length;\n\n function isKey(letter) {\n return (\n letter.charCodeAt(0) >= 'a'.charCodeAt(0) && letter.charCodeAt(0) <= 'z'.charCodeAt(0)\n );\n }\n\n function isLock(letter) {\n return (\n letter.charCodeAt(0) >= 'A'.charCodeAt(0) && letter.charCodeAt(0) <= 'Z'.charCodeAt(0)\n );\n }\n\n const dns = [\n [1, 0],\n [0, 1],\n [-1, 0],\n [0, -1],\n ];\n\n let start = { x: 0, y: 0, keys: new Set() };\n let keyMap = new Map();\n\n for (let y = 0; y < n; ++y) {\n for (let x = 0; x < m; ++x) {\n const cell = grid[y][x];\n if (cell === '@') {\n start.x = x;\n start.y = y;\n } else if (isKey(cell)) {\n keyMap.set(cell, [x, y]);\n }\n }\n }\n\n function attemptToGetKey(x, y, keys, kx, ky) {\n let q = [[x, y, keys, 0]];\n let v = new Set();\n while (q.length) {\n let nextQueue = [];\n for (let i = 0; i < q.length; ++i) {\n const [x, y, keys, steps] = q[i];\n if (x === kx && ky === y) {\n keys.add(grid[ky][kx]);\n return { keysAcquired: keys, movesUsed: steps };\n }\n const locationHash = x + y * m;\n if (v.has(locationHash)) continue;\n v.add(locationHash);\n const cell = grid[y][x];\n if (cell !== '.') {\n if (isLock(cell) && !keys.has(cell.toLowerCase())) {\n continue;\n }\n if (isKey(cell)) {\n keys.add(cell);\n }\n }\n for (const [mx, my] of dns) {\n const nx = x + mx;\n const ny = y + my;\n const nextHash = ny * m + nx;\n if (grid[ny]?.[nx] != null && grid[ny]?.[nx] !== '#') {\n if (!v.has(nextHash)) {\n q.push([nx, ny, new Set(Array.from(keys)), steps + 1]);\n }\n }\n }\n }\n q = nextQueue;\n }\n return { keysAcquired: null, movesUsed: 0 };\n }\n\n let q = new MinPriorityQueue();\n q.enqueue([start.x, start.y, start.keys], 0);\n while (q.size()) {\n const { element, priority: steps } = q.dequeue();\n const [x, y, keys] = element;\n if (keys.size === keyMap.size) {\n return steps;\n }\n for (const [key, [kx, ky]] of keyMap) {\n if (!keys.has(key)) {\n let { movesUsed, keysAcquired } = attemptToGetKey(x, y, keys, kx, ky);\n if (movesUsed) {\n q.enqueue([kx, ky, keysAcquired], movesUsed + steps);\n }\n }\n }\n }\n return -1;\n}", "solution_java": "class Solution {\n \n private static final int[][] DIRS = new int[][]{ \n {1,0}, {-1,0}, {0,1}, {0,-1}\n };\n \n public int shortestPathAllKeys(String[] grid) {\n int m = grid.length, n = grid[0].length();\n int numKeys = 0, startRow = -1, startCol = -1;\n \n for(int i=0; i queue = new LinkedList();\n Set visited = new HashSet(); \n int steps = 0;\n \n queue.offer(start);\n visited.add(start);\n \n while( !queue.isEmpty() ) {\n int size = queue.size();\n \n while( size-- > 0 ) {\n int i = queue.peek().i;\n int j = queue.peek().j;\n int keys = queue.peek().keys;\n queue.poll();\n \n if( keys == keyMask )\n return steps;\n \n for(int[] dir : DIRS) {\n int di = i + dir[0];\n int dj = j + dir[1];\n int newKeys = keys;\n\n if( di < 0 || dj < 0 || di == m || dj == n )\n continue;\n\n char c = grid[di].charAt(dj);\n\n if( isWall(c) ) continue;\n \n if( isLock(c) && !isKeyPresent(keys, c) )\n continue;\n\n if( isKey(c) ) \n newKeys |= (1 << (c - 'a'));\n \n State newState = new State(di, dj, newKeys);\n \n if( visited.add(newState) ) \n queue.offer(newState);\n }\n }\n steps++;\n }\n return -1;\n }\n \n private boolean isLock(char c) {\n return c >= 'A' && c <= 'Z';\n }\n private boolean isKey(char c) {\n return c >= 'a' && c <= 'z';\n }\n private boolean isWall(char c) {\n return c == '#';\n }\n private boolean isStart(char c) {\n return c == '@';\n }\n private boolean isKeyPresent(int keys, char lock) {\n return (keys & (1 << (lock-'A'))) != 0;\n }\n}\nclass State {\n public int i, j, keys;\n \n public State(int i, int j, int keys) {\n this.i = i;\n this.j = j;\n this.keys = keys;\n }\n \n @Override\n public boolean equals(Object obj) {\n if( !(obj instanceof State) ) return false;\n State that = (State)obj;\n return i == that.i && j == that.j && keys == that.keys;\n }\n \n @Override\n public int hashCode() {\n int prime = 31;\n int hash = 1;\n hash = hash * prime + i;\n hash = hash * prime + j;\n hash = hash * prime + keys;\n return hash;\n }\n}", "solution_c": "class Solution {\n int dirx[4] = {-1,1,0,0};\n int diry[4] = {0,0,1,-1};\npublic:\n int shortestPathAllKeys(vector& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector> matrix(n, vector(m));\n vector lock(7,0);\n int sx, sy;\n int lk = 0;\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < m; j++)\n {\n if(grid[i][j] == '@')\n {\n sx = i, sy = j;\n matrix[i][j] = 0;\n }\n else if(grid[i][j] == '.')\n {\n matrix[i][j] = 0;\n //cout << grid[i][j];\n }\n else if(grid[i][j] >= 'A' && grid[i][j] <= 'F')\n {\n matrix[i][j] = -1*((grid[i][j]-'A') + 1);\n lock[(grid[i][j]-'A') + 1] = (1 << (grid[i][j]-'A'));\n }\n else if(grid[i][j] == '#')\n matrix[i][j] = -8;\n else\n {\n matrix[i][j] = (1 << (grid[i][j]-'a'));\n lk++;\n }\n //cout << matrix[i][j] << \" \";\n }\n //cout << endl;\n }\n int fnl = (1 << lk) - 1;\n //cout << fnl;\n vector> visited(n*m, vector(fnl,1));\n queue,int>> q;\n int ans = 0;\n q.push({{sx,sy},0});\n visited[sx*m+sy][0] = 0;\n while(!q.empty())\n {\n ans++;\n int sz = q.size();\n while(sz--)\n {\n int x = q.front().first.first;\n int y = q.front().first.second;\n int bit = q.front().second;\n q.pop();\n for(int i = 0; i < 4; i++)\n {\n int nxtx = x + dirx[i];\n int nxty = y + diry[i];\n if(nxtx >= n || nxtx < 0 || nxty >= m || nxty < 0) continue;\n if(matrix[nxtx][nxty] == -8) continue;\n if(visited[nxtx*m+nxty][bit] == 0) continue;\n if(matrix[nxtx][nxty] < 0)\n {\n int lkidx = -1*matrix[nxtx][nxty];\n if(bit&lock[lkidx])\n {\n q.push({{nxtx,nxty},bit});\n visited[nxtx*m+nxty][bit] = 0;\n }\n }\n else if(matrix[nxtx][nxty] == 0)\n {\n q.push({{nxtx,nxty},bit});\n visited[nxtx*m+nxty][bit] = 0;\n continue;\n }\n else\n {\n int fbit = bit | matrix[nxtx][nxty];\n if(fbit == fnl) return ans;\n q.push({{nxtx,nxty},fbit});\n visited[nxtx*m+nxty][fbit] = 0;\n }\n }\n }\n }\n return -1;\n }\n};" }, { "title": "Verify Preorder Serialization of a Binary Tree", "algo_input": "One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.\n\nFor example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where '#' represents a null node.\n\nGiven a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.\n\nIt is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.\n\nYou may assume that the input format is always valid.\n\n\n\tFor example, it could never contain two consecutive commas, such as \"1,,3\".\n\n\nNote: You are not allowed to reconstruct the tree.\n\n \nExample 1:\nInput: preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\nExample 2:\nInput: preorder = \"1,#\"\nOutput: false\nExample 3:\nInput: preorder = \"9,#,#,1\"\nOutput: false\n\n \nConstraints:\n\n\n\t1 <= preorder.length <= 104\n\tpreorder consist of integers in the range [0, 100] and '#' separated by commas ','.\n\n", "solution_py": "class Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n nodes = preorder.split(',')\n counter=1\n for i, node in enumerate(nodes):\n if node != '#':\n counter+=1\n else:\n if counter <= 1 and i != len(nodes) - 1:\n return False\n counter-=1\n return counter == 0", "solution_js": "/**\n * @param {string} preorder\n * @return {boolean}\n */\nvar isValidSerialization = function(preorder) {\n let balance = 1\n for(const node of preorder.split(','))\n if (balance > 0)\n if (node === '#') --balance\n else ++balance\n else return false\n return balance < 1\n}", "solution_java": "class Solution {\n public boolean isValidSerialization(String preorder) {\n String[] strs = preorder.split(\",\");\n //In starting we have one vacany for root\n int vacancy = 1;\n \n for(String str : strs){\n \n if(--vacancy < 0 ) return false;\n \n // whenever we encounter a new node vacancy decreases by 1 and left and right two vacancy for that node will added in total\n if(!str.equals(\"#\")) \n vacancy += 2;\n \n }\n \n \n return vacancy == 0;\n \n }\n}", "solution_c": "class Solution {\npublic:\n bool isValidSerialization(string preorder) {\n stringstream s(preorder);\n string str;\n int slots=1;\n while(getline(s, str, ',')) {\n if(slots==0) return 0;\n if(str==\"#\") slots--;\n else slots++;\n }\n return slots==0;\n }\n};" }, { "title": "Partition Equal Subset Sum", "algo_input": "Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.\n\n \nExample 1:\n\nInput: nums = [1,5,11,5]\nOutput: true\nExplanation: The array can be partitioned as [1, 5, 5] and [11].\n\n\nExample 2:\n\nInput: nums = [1,2,3,5]\nOutput: false\nExplanation: The array cannot be partitioned into equal sum subsets.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 200\n\t1 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def canPartition(self, nums: List[int]) -> bool:\n total = sum(nums)\n if total % 2: return False\n total //= 2\n leng = len(nums)\n dp = [[False] * (total + 1) for _ in range(leng + 1)]\n \n for i in range(leng + 1): dp[i][0] = True\n for i in range(1, leng + 1):\n for j in range(1, total + 1):\n dp[i][j] = dp[i-1][j]\n if j - nums[i-1] >= 0:\n dp[i][j] |= dp[i-1][j-nums[i-1]] \n return dp[leng][total]", "solution_js": "var canPartition = function(nums) {\n let sum = nums.reduce((prevVal, currValue) => prevVal + currValue, 0); // sum of each values\n if (sum % 2 !== 0) return false; // return false if odd sum\n \n let target = sum / 2; // ex.[1,5,11,5] target is half which is 11\n let dp = new Set(); // add unique values\n dp.add(0); //intialize with 0\n for (var i = nums.length - 1; i >= 0; i--) { //start from end\n nextDp = new Set(); \n for (const ele of dp.values()) {\n let newVal = ele + nums[i];\n if(newVal === target) return true; \n nextDp.add(newVal); \n }\n dp = new Set([...dp, ...nextDp]);\n }\n \n return false;\n};", "solution_java": "class Solution {\n public boolean canPartition(int[] nums) {\n int sum = 0;\n for(int i=0; i= 1? true : false;\n }\n public int helper(int[] nums, int sum, int i, int[][] dp){\n if(i==nums.length && sum==0){\n return 1;\n }\n if(i==nums.length){\n return 0;\n }\n if(sum < 0){\n return 0;\n }\n if(dp[i][sum] != -1){\n return dp[i][sum];\n }\n if(sum& nums) {\n int sum = 0;\n int n = nums.size();\n for(int i = 0;i= count[char] for char in 'QWER'):\n res = min(res, right - left + 1)\n count[s[left]] =count[s[left]]+ 1\n left += 1\n return res", "solution_js": "var balancedString = function(s) {\n \n let output = Infinity;\n \n let map = {\"Q\":0, \"W\":0, \"E\":0, \"R\":0};\n \n for(let letter of s){\n map[letter]++;\n }\n \n let valueGoal = s.length / 4\n \n let remainder = 0;\n \n let count = 4;\n \n for(let [key, val] of Object.entries(map)){\n \n if(val > valueGoal){\n remainder = remainder + (val - valueGoal); \n }\n \n if(val === valueGoal || val < valueGoal){\n map[key] = -Infinity;\n count--;\n }\n }\n \n if(remainder === 0){\n return 0;\n }\n \n let left = 0;\n \n let right = 0;\n \n while(right < s.length){\n\n if(map[s[right]] !== -Infinity){\n \n map[s[right]]--;\n\n if(map[s[right]] === valueGoal){\n count--;\n }\n \n }\n \n while(count === 0){\n\n output = Math.min(output, right - left + 1);\n \n if(map[s[left]] !== -Infinity){\n \n map[s[left]]++;\n \n if(map[s[left]] > valueGoal){\n count++;\n }\n \n }\n left++\n }\n\n right++;\n }\n\n return output;\n};", "solution_java": "class Solution {\n public int balancedString(String s) {\n int n = s.length(), ans = n, excess = 0;\n int[] cnt = new int[128];\n cnt['Q'] = cnt['W'] = cnt['E'] = cnt['R'] = -n/4;\n for (char ch : s.toCharArray()) if (++cnt[ch] == 1) excess++; //if count reaches 1, it is extra and to be removed.\n if (excess == 0) return 0;\n for (int i = 0, j = 0; i < n; i++){//i = window right end, j = window left end\n if (--cnt[s.charAt(i)] == 0) excess--; //remove letter at index i\n while (excess == 0){ //if no more excess, then \n if (++cnt[s.charAt(j)] == 1) excess++; //we put letter at index j back\n ans = Math.min(i - j + 1, ans);; //and update ans accordingly\n j++;\n }\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int balancedString(string s) {\n int n=s.length();\n unordered_mapumap;\n for(auto x:s)\n {\n umap[x]++; \n }\n umap['Q']=umap['Q']-n/4>0?umap['Q']-n/4:0;\n umap['W']=umap['W']-n/4>0?umap['W']-n/4:0;\n umap['E']=umap['E']-n/4>0?umap['E']-n/4:0;\n umap['R']=umap['R']-n/4>0?umap['R']-n/4:0;\n int count=umap['Q']+umap['W']+umap['E']+umap['R'];\n if(count==0)\n return 0;\n int i=0,ans=INT_MAX;\n unordered_mapnewMap;\n for(int j=0;j int:\n l=1\n h=n\n while l<=h:\n mid=(l+h)//2\n x =guess(mid)\n if(x==0):\n return mid\n elif(x==1):\n l = mid+1\n else:\n h = mid-1", "solution_js": "/** \n * Forward declaration of guess API.\n * @param {number} num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * var guess = function(num) {}\n */\n\n/**\n * @param {number} n\n * @return {number}\n */\nvar guessNumber = function(n) {\n let lower=1;\n let higher=n;\n while(lower<=higher){\n let mid=Math.floor((lower+higher)/2);\n if(guess(mid)==0){\n return mid; \n }\n else if(guess(mid)==-1){\n higher=mid-1;\n }\n else{\n lower=mid+1;\n }\n }\n return 0;\n \n};", "solution_java": "/** \n * Forward declaration of guess API.\n * @param num your guess\n * @return \t -1 if num is higher than the picked number\n *\t\t\t 1 if num is lower than the picked number\n * otherwise return 0\n * int guess(int num);\n */\n\npublic class Solution extends GuessGame {\n public int guessNumber(int n) {\n int left = 1;\n int right = n;\n \n while(left < right){\n int mid = ((right - left) / 2) + left;\n if(guess(mid) == 0)\n return mid;\n else if(guess(mid) < 0)\n right = mid - 1;\n else\n left = mid + 1;\n }\n \n return left;\n }\n}", "solution_c": "class Solution {\npublic:\n int guessNumber(int n) {\n int s = 1, e = n;\n int mid = s + (e - s)/2;\n \n while (s <= e){\n if (guess(mid) == 0){ \n return mid;\n }\n \n else if (guess(mid) == -1){\n e = mid - 1;\n }\n \n else if (guess(mid) == 1){\n s = mid +1;\n }\n \n mid = s + (e - s)/2;\n }\n \n return mid;\n }\n};" }, { "title": "Arithmetic Subarrays", "algo_input": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.\n\nFor example, these are arithmetic sequences:\n\n1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9\n\nThe following sequence is not arithmetic:\n\n1, 1, 2, 5, 7\n\nYou are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.\n\nReturn a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.\n\n \nExample 1:\n\nInput: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]\nOutput: [true,false,true]\nExplanation:\nIn the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.\n\nExample 2:\n\nInput: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput: [false,true,false,false,true,true]\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\tm == l.length\n\tm == r.length\n\t2 <= n <= 500\n\t1 <= m <= 500\n\t0 <= l[i] < r[i] < n\n\t-105 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n out=[]\n for i, j in zip(l, r):\n out.append(self.canMakeArithmeticProgression(nums[i:j+1]))\n return out\n \n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n minArr = min(arr)\n maxArr = max(arr)\n\t\t\n\t\t# if difference between minArr and maxArr cannot be divided into equal differences, then return false\n if (maxArr-minArr)%(len(arr)-1)!=0:\n return False\n\t\t\t\n\t\t# consecutive difference in arithmetic progression\n diff = int((maxArr-minArr)/(len(arr)-1))\n if diff == 0:\n if arr != [arr[0]]*len(arr):\n return False\n return True\n\t\t\n\t\t# array to check all numbers in A.P. are present in input array.\n\t\t# A.P.[minArr, minArr+d, minArr+2d, . . . . . . . maxArr]\n check = [1]*len(arr)\n for num in arr:\n if (num-minArr)%diff != 0:\n return False\n check[(num-minArr)//diff]=0\n\t\t\n\t\t# if 1 is still in check array it means at least one number from A.P. is missing from input array.\n if 1 in check:\n return False\n return True", "solution_js": "/**\n * @param {number[]} nums\n * @param {number[]} l\n * @param {number[]} r\n * @return {boolean[]}\n */\n var checkArithmeticSubarrays = function(nums, l, r) {\n let result = [];\n for(let i=0;i a-b);\n let diff = subNums[1]-subNums[0];\n let s = true\n for(let j=0;j checkArithmeticSubarrays(int[] nums, int[] l, int[] r) {\n List result = new ArrayList<>();\n int L = nums.length, ll = l.length,ind=0;\n for(int i=0;i checkArithmeticSubarrays(vector& nums, vector& l, vector& r) {\n \n vector ans(l.size(),false);\n for(int i=0;i& nums,int start,int end)\n {\n //get the maximum and min elements \n int mini=INT_MAX;\n int maxi=INT_MIN;\n for(int i=start;i<=end;i++)\n {\n mini=min(nums[i],mini);\n maxi=max(nums[i],maxi);\n }\n \n //when mini==maxi it means all the elements are same in the sub array\n if(mini==maxi)\n return true; \n \n //we cant have same common difference betweeen two adjacent elements\n //when we arrange in arthemetic sequence\n if((maxi-mini)%(end-start)!=0)\n return false;\n \n \n //the diff between every two integers when we rearrange sub array\n int diff=(maxi-mini)/(end-start);\n \n //to check if the duplicate elemnts are present\n //ex- [2,4,6,6]\n //6 is repeating two times \n vector present(end-start+1,false);\n for(int i=start;i<=end;i++)\n {\n \n //we cant set a index of nums[i]\n if((nums[i]-mini)%diff!=0)\n return false;\n \n int ind=(nums[i]-mini)/diff;\n \n // same element is alreeady repeated ( 6 in the above example)\n if(present[ind])\n return false;\n //mark it presence\n present[ind]=true;\n \n }\n return true;\n \n }\n};" }, { "title": "Check Array Formation Through Concatenation", "algo_input": "You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].\n\nReturn true if it is possible to form the array arr from pieces. Otherwise, return false.\n\n \nExample 1:\n\nInput: arr = [15,88], pieces = [[88],[15]]\nOutput: true\nExplanation: Concatenate [15] then [88]\n\n\nExample 2:\n\nInput: arr = [49,18,16], pieces = [[16,18,49]]\nOutput: false\nExplanation: Even though the numbers match, we cannot reorder pieces[0].\n\n\nExample 3:\n\nInput: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput: true\nExplanation: Concatenate [91] then [4,64] then [78]\n\n\n \nConstraints:\n\n\n\t1 <= pieces.length <= arr.length <= 100\n\tsum(pieces[i].length) == arr.length\n\t1 <= pieces[i].length <= arr.length\n\t1 <= arr[i], pieces[i][j] <= 100\n\tThe integers in arr are distinct.\n\tThe integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).\n\n", "solution_py": "class Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n keys, ans = {}, []\n for piece in pieces:\n keys[piece[0]] = piece\n for a in arr:\n if a in keys:\n ans.extend(keys[a])\n return ''.join(map(str, arr)) == ''.join(map(str, ans))", "solution_js": "var canFormArray = function(arr, pieces) {\n\tlet total = \"\";\n arr=arr.join(\"\");\n for (let i = 0; i < pieces.length; i++) {\n pieces[i] = pieces[i].join(\"\");\n total += pieces[i];\n if (arr.indexOf(pieces[i]) == -1) return false;\n }\n return total.length == arr.length;\n};", "solution_java": "class Solution {\n public boolean canFormArray(int[] arr, int[][] pieces) {\n HashMap hm = new HashMap();\n for(int[] list:pieces)\n hm.put(list[0],list);\n \n int index = 0;\n while(index=arr.length || val!=arr[index])\n return false;\n index++;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canFormArray(vector& arr, vector>& pieces) {\n map> mp; \n // map the 1st element in pieces[i] to pieces[i]\n for(auto p:pieces) \n mp[p[0]] = p;\n vector result;\n for(auto a:arr) {\n if(mp.find(a)!=mp.end()) \n result.insert(result.end(),mp[a].begin(),mp[a].end());\n }\n return result ==arr;\n }\n};" }, { "title": "Power of Three", "algo_input": "Given an integer n, return true if it is a power of three. Otherwise, return false.\n\nAn integer n is a power of three, if there exists an integer x such that n == 3x.\n\n \nExample 1:\n\nInput: n = 27\nOutput: true\n\n\nExample 2:\n\nInput: n = 0\nOutput: false\n\n\nExample 3:\n\nInput: n = 9\nOutput: true\n\n\n \nConstraints:\n\n\n\t-231 <= n <= 231 - 1\n\n\n \nFollow up: Could you solve it without loops/recursion?", "solution_py": "class Solution:\n def isPowerOfThree(self, n: int) -> bool:\n return round(log(n,3), 9) == round(log(n,3)) if n >= 1 else False", "solution_js": "var isPowerOfThree = function(n) {\n if(n === 1){return true;}\n if(n === 0){return false;}\n\n n/=3;\n\n if(n%3 != 0 && n != 1){\n return false;\n }else{\n let x = isPowerOfThree(n);\n return x;\n }\n};", "solution_java": "class Solution {\n public boolean isPowerOfThree(int n) {\n if(n==1){\n return true;\n }\n if(n<=0){\n return false;\n }\n if(n%3 !=0 && n>1){\n return false;\n }\n else{\n return isPowerOfThree(n/3); // recurssion \n }\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool isPowerOfThree(int n) {\n\t\tif(n<=0){return false;}\n\t\tif(n>pow(2, 31)-1 || n 0 and stones[i] + jump in pos:\n if self.possible(pos[stones[i] + jump], n, stones, pos, [jump - 1, jump, jump + 1]):\n self.cache[key] = True\n return True\n self.cache[key] = False\n return False\n\n def canCross(self, stones: List[int]) -> bool:\n n = len(stones)\n pos = {}\n for i, stone in enumerate(stones):\n pos[stone] = i\n self.cache = {}\n return self.possible(0, n, stones, pos, [1])", "solution_js": "var canCross = function(stones) {\n let hash = {};\n function dfs(idx = 0, jumpUnits = 0) {\n let key = `${idx}-${jumpUnits}`;\n if (key in hash) return hash[key];\n\t\t\n if (idx === stones.length - 1) return true;\n if (idx >= stones.length) return false;\n\t\t\n let minJump = jumpUnits - 1, maxJump = jumpUnits + 1;\n for (let i = idx + 1; i < stones.length; i++) {\n let jump = stones[i] - stones[idx];\n if (jump >= minJump && jump <= maxJump) {\n if (dfs(i, jump)) return hash[idx] = true;\n } else if (jump > maxJump) break;\n } return hash[key] = false;\n }\n return dfs();\n};", "solution_java": "class Solution {\n static boolean flag = false; // If flag is true no more operations in recursion, directly return statement\n public boolean canCross(int[] stones) {\n int i = 0; // starting stone\n int k = 1; // starting jump\n flag = false; \n return canBeCrossed(stones, k, i);\n }\n \n public boolean canBeCrossed(int[] stones, int k, int i){\n if(!flag){ // If flag is false \n if(stones[i] + k == stones[stones.length - 1]){ // If frog do 'k' jump from current stone lands on last stones, no more recusive calls and return true\n flag = true;\n return true;\n }\n\t\t// If frog do 'k' jump from current stone crosses last stone or not able to reach next stone\n\t\t//return false\n if((stones[i] + k > stones[stones.length - 1]) || (stones[i]+k stones[temp]) temp++;\n\t\t//If loop exited 2 condition possible\n\t\t//jump from current stone is reached next possible stone\n\t\t//or not\n\t\t\n\t\t//If next possible stone reached\n\t\t//then do all possible jumps from this stone \n\t\t//the current stone is 'temp'\n\t\t//possible jumps are 'k-1', k, 'k+1'\n if(stones[i]+k == stones[temp]) return (canBeCrossed(stones, k+1, temp) || canBeCrossed(stones, k, temp) || canBeCrossed(stones,k-1,temp));\n\t\t\n\t\t//If next possible stone not reached means jump from the current stone can't reach any stone\n\t\t//hence return false\n else return false;\n }\n else return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canCross(vector& stones) {\n unordered_mapmp; //to see the position where stone is present\n for(int i=0;i,bool>dp;\n return fun(mp,stone,jump,dp,last_stone);\n }\n bool fun( unordered_map&mp,int stone,int jump,map,bool>&dp,int &ls)\n {\n if(stone==ls) //reached last stone\n {\n return true;\n }\n if(mp.find(stone)==mp.end()) //stone is not present\n {\n return false;\n }\n if(dp.find({stone,jump})!=dp.end())\n {\n return dp[{stone,jump}];\n }\n bool jump1=false;\n bool jump2=false;\n bool jump3=false;\n if((stone+jump-1)>stone) //can take jump of k-1 units\n {\n jump1=fun(mp,stone+jump-1,jump-1,dp,ls);\n }\n if((stone+jump)>stone) //can take jump of k units\n {\n jump2=fun(mp,stone+jump,jump,dp,ls);\n }\n if((stone+jump+1)>stone) //can take jump of k+1 units\n {\n jump3=fun(mp,stone+jump+1,jump+1,dp,ls);\n }\n dp[{stone,jump}]=jump1 or jump2 or jump3;\n return dp[{stone,jump}];\n }\n};" }, { "title": "Critical Connections in a Network", "algo_input": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.\n\nA critical connection is a connection that, if removed, will make some servers unable to reach some other server.\n\nReturn all critical connections in the network in any order.\n\n \nExample 1:\n\nInput: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput: [[1,3]]\nExplanation: [[3,1]] is also accepted.\n\n\nExample 2:\n\nInput: n = 2, connections = [[0,1]]\nOutput: [[0,1]]\n\n\n \nConstraints:\n\n\n\t2 <= n <= 105\n\tn - 1 <= connections.length <= 105\n\t0 <= ai, bi <= n - 1\n\tai != bi\n\tThere are no repeated connections.\n\n", "solution_py": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \n dic = collections.defaultdict(list)\n for c in connections:\n u, v = c\n dic[u].append(v)\n dic[v].append(u)\n \n \n timer = 0\n \n depth, lowest, parent, visited = [float(\"inf\")]*n, [float(\"inf\")]*n, [float(\"inf\")]*n, [False]*n\n res = []\n \n def find(u):\n \n nonlocal timer\n \n visited[u] = True\n depth[u], lowest[u] = timer, timer\n timer += 1\n \n for v in dic[u]: \n \n if not visited[v]:\n parent[v] = u\n find(v)\n if lowest[v]>depth[u]:\n res.append([u,v])\n \n if parent[u]!=v:\n lowest[u] = min(lowest[u], lowest[v])\n \n find(0)\n return res\n ", "solution_js": "var criticalConnections = function(n, connections) {\n // Graph Formation\n const graph = new Map();\n connections.forEach(([a, b]) => {\n const aconn = graph.get(a) || [];\n const bconn = graph.get(b) || [];\n\n aconn.push(b), bconn.push(a);\n graph.set(a, aconn);\n graph.set(b, bconn);\n });\n\n // Find Bridges\n const bridges = [];\n const visited = new Array(n).fill(false);\n const tin = new Array(n).fill(-1);\n const dis = new Array(n).fill(-1);\n\n let time = 0;\n\n const dfs = (node, parent = -1) => {\n visited[node] = true;\n ++time;\n tin[node] = time;\n dis[node] = time;\n\n const connections = graph.get(node);\n for(let conn of connections) {\n if(conn == parent) {\n continue;\n }\n if(visited[conn]) {\n dis[node] = Math.min(dis[node], tin[conn]);\n } else {\n dfs(conn, node);\n dis[node] = Math.min(dis[node], dis[conn]);\n if(dis[conn] > tin[node]) {\n bridges.push([node, conn]);\n }\n }\n };\n }\n\n dfs(0);\n\n return bridges;\n};", "solution_java": "class Solution {\n // We record the timestamp that we visit each node. For each node, we check every neighbor except its parent and return a smallest timestamp in all its neighbors. If this timestamp is strictly less than the node's timestamp, we know that this node is somehow in a cycle. Otherwise, this edge from the parent to this node is a critical connection\n public List> criticalConnections(int n, List> connections) {\n List[] graph = new ArrayList[n];\n for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n \n for(List oneConnection :connections) {\n graph[oneConnection.get(0)].add(oneConnection.get(1));\n graph[oneConnection.get(1)].add(oneConnection.get(0));\n }\n int timer[] = new int[1];\n List> results = new ArrayList<>();\n boolean[] visited = new boolean[n];\n int []timeStampAtThatNode = new int[n]; \n criticalConnectionsUtil(graph, -1, 0, timer, visited, results, timeStampAtThatNode);\n return results;\n }\n \n \n public void criticalConnectionsUtil(List[] graph, int parent, int node, int timer[], boolean[] visited, List> results, int []timeStampAtThatNode) {\n visited[node] = true;\n timeStampAtThatNode[node] = timer[0]++;\n int currentTimeStamp = timeStampAtThatNode[node];\n \n for(int oneNeighbour : graph[node]) {\n if(oneNeighbour == parent) continue;\n if(!visited[oneNeighbour]) criticalConnectionsUtil(graph, node, oneNeighbour, timer, visited, results, timeStampAtThatNode);\n timeStampAtThatNode[node] = Math.min(timeStampAtThatNode[node], timeStampAtThatNode[oneNeighbour]);\n if(currentTimeStamp < timeStampAtThatNode[oneNeighbour]) results.add(Arrays.asList(node, oneNeighbour));\n }\n \n \n }\n \n}", "solution_c": "class Solution {\n int timer = 1;\npublic:\nvoid dfs(vectoradj[] , int node , int parent , vector&tin , vector&low , vector&vis , vector>&ans)\n{\n vis[node] = 1;\n tin[node] = low[node] = timer;\n timer++;\n for(auto it:adj[node])\n {\n if(it == parent) continue;\n if(vis[it] == 0)\n {\n dfs(adj , it , node , tin , low , vis , ans);\n low[node] = min(low[node] , low[it]);\n if(tin[node] < low[it])\n ans.push_back({node , it});\n }\n else\n {\n low[node] = min(low[node] , low[it]);\n }\n }\n}\n vector> criticalConnections(int n, vector>& con) {\n vectoradj[n];\n for(int i = 0;i>ans;\n vectorvis(n , 0) , tin(n , 0) , low(n , 0);\n dfs(adj , 0 , -1 , tin , low , vis , ans);\n return ans;\n }\n};" }, { "title": "Maximum Number of Events That Can Be Attended II", "algo_input": "You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.\n\nYou can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\n\nReturn the maximum sum of values that you can receive by attending events.\n\n \nExample 1:\n\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput: 7\nExplanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n\nExample 2:\n\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput: 10\nExplanation: Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n\nExample 3:\n\n\n\nInput: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput: 9\nExplanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n\n \nConstraints:\n\n\n\t1 <= k <= events.length\n\t1 <= k * events.length <= 106\n\t1 <= startDayi <= endDayi <= 109\n\t1 <= valuei <= 106\n\n", "solution_py": "import bisect\nfrom functools import lru_cache\n\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n if k == 1: # optimization for TLE test case 57/67\n return max([event[2] for event in events])\n \n events.sort()\n event_starts = [event[0] for event in events] # enables binary search\n \n @lru_cache(None)\n def dp(i, j):\n if j == 0: # out of turns\n return 0\n if i >= len(events): # end of events array\n return 0\n max_score = events[i][2]\n \n # get minimum index where start day is greater than current end day\n next_index_minimum = bisect.bisect_left(event_starts, events[i][1] + 1)\n \n # check each possibility from the minimum next index until end of the array\n for k in range(next_index_minimum, len(events)):\n max_score = max(max_score, events[i][2] + dp(k, j - 1))\n \n # check if we can get a better score if we skip this index altogether\n max_score = max(max_score, dp(i + 1, j))\n return max_score\n return dp(0, k)", "solution_js": "/**\n * @param {number[][]} events\n * @param {number} k\n * @return {number}\n */\nvar maxValue = function(events, k) {\n events = events.sort((a, b) => a[1] - b[1]);\n const n = events.length;\n var ans = 0;\n var dp = Array.from(Array(k+1), () => new Array(n).fill(0));\n \n for(let i = 0; i < n; i++) {\n dp[1][i] = Math.max((i ? dp[1][i-1] :0), events[i][2]);\n ans = Math.max(dp[1][i], ans);\n }\n \n function binarySearch(l, r, target) {\n var pos = -1;\n while(l <= r) {\n const mid = Math.floor((l+r)/2);\n if (events[mid][1] < target) {\n pos = mid;\n l = mid+1;\n }\n else r = mid-1;\n }\n return pos;\n }\n \n for(let i = 0; i < n; i++) {\n const j = binarySearch(0, i-1, events[i][0]);\n for(let l = 2; l <= k; l++) {\n dp[l][i] = Math.max(( j >= 0 ? dp[l-1][j] + events[i][2] : 0), (i ? dp[l][i-1] : 0));\n ans = Math.max(dp[l][i], ans);\n }\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int maxValue(int[][] events, int k) {\n Arrays.sort(events, (e1, e2) -> (e1[0] == e2[0] ? e1[1]-e2[1] : e1[0]-e2[0]));\n return maxValue(events, 0, k, 0, new int[k+1][events.length]);\n }\n\n private int maxValue(int[][] events, int index, int remainingEvents, int lastEventEndDay, int[][] dp) {\n // Return 0 if no events are left or maximum choice is reached\n if (index >= events.length || remainingEvents == 0)\n return 0;\n\n // An Event cannot be picked if the previous event has not completed before current event\n if (lastEventEndDay >= events[index][0])\n return maxValue(events, index+1, remainingEvents, lastEventEndDay, dp);\n\n // Return the value if the solution is already available\n if (dp[remainingEvents][index] != 0)\n return dp[remainingEvents][index];\n\n // There are 2 choices that we can make,\n // SKIP this meeting or PICK this meeting\n return dp[remainingEvents][index] = Math.max(\n maxValue(events, index+1, remainingEvents, lastEventEndDay, dp), // skip\n maxValue(events, index+1, remainingEvents-1, events[index][1], dp) + events[index][2] // pick\n );\n }\n}", "solution_c": "class Solution {\npublic:\n \n int ans; \n unordered_map>> dp;\n \n int Solve(vector>& events, int start, int n, int k, int endtime){\n if(k == 0 || start == n){\n return 0;\n }\n \n if(dp.find(start) != dp.end() && dp[start].find(k) != dp[start].end() && dp[start][k].find(endtime) != dp[start][k].end()){\n \n return dp[start][k][endtime];\n }\n int t1 = 0;\n if(events[start][0] > endtime){\n t1 = events[start][2] + Solve(events, start+1, n, k-1, events[start][1]);\n }\n \n int t2 = Solve(events,start+1,n,k,endtime);\n \n dp[start][k][endtime] = max(t1,t2);\n // cout<< dp[start][k][endtime]<>& events, int k) {\n \n dp.clear();\n \n // sort according to start time\n sort(events.begin(), events.end(),[](vector &a,vector &b){\n return a[0] < b[0];\n });\n \n return Solve(events,0,events.size(),k,0);\n \n }\n};" }, { "title": "Generate Random Point in a Circle", "algo_input": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.\n\nImplement the Solution class:\n\n\n\tSolution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).\n\trandPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].\n\n\n \nExample 1:\n\nInput\n[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]\nOutput\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\nExplanation\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n\n\n \nConstraints:\n\n\n\t0 < radius <= 108\n\t-107 <= x_center, y_center <= 107\n\tAt most 3 * 104 calls will be made to randPoint.\n\n", "solution_py": "class Solution:\n\n def __init__(self, radius: float, x_center: float, y_center: float):\n self.rad = radius\n self.xc = x_center\n self.yc = y_center\n\n def randPoint(self) -> List[float]:\n while True:\n xg=self.xc+random.uniform(-1, 1)*self.rad*2\n yg=self.yc+random.uniform(-1, 1)*self.rad*2\n if (xg-self.xc)**2 + (yg-self.yc)**2 <= self.rad**2:\n return [xg, yg]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(radius, x_center, y_center)\n# param_1 = obj.randPoint()", "solution_js": "/**\n * @param {number} radius\n * @param {number} x_center\n * @param {number} y_center\n */\nvar Solution = function(radius, x_center, y_center) {\n this.radius = radius;\n this.x_center = x_center;\n this.y_center = y_center;\n};\n\n/**\n * @return {number[]}\n */\nSolution.prototype.randPoint = function() {\n const randomX = randRange(this.x_center + this.radius, this.x_center - this.radius);\n const randomY = randRange(this.y_center + this.radius, this.y_center - this.radius);\n \n const distanceInSquares = Math.pow(randomX - this.x_center, 2) + Math.pow(randomY - this.y_center, 2);\n const isOutOfTheCircle = distanceInSquares > Math.pow(this.radius, 2);\n \n if (isOutOfTheCircle)) {\n return this.randPoint();\n }\n\n return [randomX, randomY];\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(radius, x_center, y_center)\n * var param_1 = obj.randPoint()\n */\n\nfunction randRange(maximum, minimum) {\n return Math.random() * (maximum - minimum) + minimum;\n}", "solution_java": "class Solution {\n double radius;\n double x_center;\n double y_center;\n Random r=new Random();\n public Solution(double radius, double x_center, double y_center) {\n this.radius=radius;\n this.x_center=x_center;\n this.y_center=y_center;\n }\n \n public double[] randPoint() {\n double angle=r.nextDouble(Math.PI*2);\n\t\t//For probability is inversely proportional to radius, we use sqrt of random number.\n double rad=Math.sqrt(r.nextDouble())*radius;\n double[] ret=new double[2];\n ret[0]=rad*Math.cos(angle)+x_center;\n ret[1]=rad*Math.sin(angle)+y_center;\n return ret;\n }\n}", "solution_c": "class Solution {\npublic:\n double r,x,y;\n Solution(double radius, double x_center, double y_center) {\n r = radius;\n x = x_center;\n y = y_center;\n }\n \n vector randPoint() {\n double x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r);\n double y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r);\n \n while(solve(x_r,y_r,x,y)>=r*r)\n {\n x_r = ((double)rand()/RAND_MAX * (2*r)) + (x-r);\n y_r = ((double)rand()/RAND_MAX * (2*r)) + (y-r);\n }\n \n return {x_r,y_r};\n }\n \n double solve(double x_r,double y_r,double x,double y)\n {\n return (x-x_r)*(x-x_r) + (y-y_r)*(y-y_r);\n }\n};" }, { "title": "Swap For Longest Repeated Character Substring", "algo_input": "You are given a string text. You can swap two of the characters in the text.\n\nReturn the length of the longest substring with repeated characters.\n\n \nExample 1:\n\nInput: text = \"ababa\"\nOutput: 3\nExplanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.\n\n\nExample 2:\n\nInput: text = \"aaabaaa\"\nOutput: 6\nExplanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.\n\n\nExample 3:\n\nInput: text = \"aaaaa\"\nOutput: 5\nExplanation: No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 2 * 104\n\ttext consist of lowercase English characters only.\n\n", "solution_py": "class Solution:\n def maxRepOpt1(self, text: str) -> int:\n char_groups = []\n \n for char, group in groupby(text):\n group_len = len(list(group))\n char_groups.append((char, group_len))\n \n char_count = Counter(text)\n \n longest_substr_len = 1 # Each char itself is substring of len 1\n \n # Scenario-1: Get the longest substr length by just adding one more char to each group\n for char, group_len in char_groups:\n # NOTE: If the total count of the char across full string is < group_len+1,\n # make sure to take the total count only\n #\n # It means we don't have any extra char occurrence which we can add to the current group\n \n group_len_w_one_addition = min(group_len+1, char_count[char])\n longest_substr_len = max(longest_substr_len, group_len_w_one_addition)\n \n \n # Scenario-2: \n # If there are two groups of same char, separated by a group of different char with length=1:\n # 1) We can either swap that one char in the middle with the same char as those two groups \n # Ex: 'aaa b aaa c a'\n # - We can swap the 'b' in between two groups of 'a' using same char 'a' from last index\n # - So after swapping, it will become 'aaa a aaa c b' \n # - hence longest substr len of same char 'a' = 7\n #\n # 2) We can merge the two groups\n # Ex: 'aaa b aaa' \n # -> here there are two groups of char 'a' with len = 3 each.\n # -> they are separated by a group of char 'b' with len = 1\n # -> hence, we can merge both groups of char 'a' - so that longest substr len = 6\n # -> basically, swap the 'b' with 'a' at very last index\n # -> the final string will look like 'aaaaaa b'\n #\n # We will take max length we can get from above two options.\n #\n # Since we need to check the group prior to curr_idx \"i\" and also next to curr_idx \"i\";\n # we will iterate from i = 1 to i = len(char_groups)-2 -- both inclusive\n \n for i in range(1, len(char_groups)-1):\n prev_group_char, prev_group_len = char_groups[i-1]\n curr_group_char, curr_group_len = char_groups[i]\n next_group_char, next_group_len = char_groups[i+1]\n \n if curr_group_len != 1 or prev_group_char != next_group_char:\n continue\n \n len_after_swapping = min(prev_group_len + next_group_len + 1, char_count[next_group_char])\n longest_substr_len = max(longest_substr_len, len_after_swapping)\n \n return longest_substr_len", "solution_js": "/**\n * @param {string} text\n * @return {number}\n */\n\nconst getLast = (ar)=> ar[ar.length-1];\n var maxRepOpt1 = function(text) {\n\n let freq = {};\n\n // compute frequency map\n for(let i=0;i c){ // x x a , a x x , x a x\n max = Math.max(max,c+1);\n }\n if(i+2 sum){\n max = Math.max(max,1+sum);\n }else{\n max = Math.max(max,sum);\n }\n }\n }\n }\n\n return max;\n\n};", "solution_java": "class Solution {\n\t\tpublic int maxRepOpt1(String s) {\n\t\t int[] count = new int[26];\n\t\t int[] left = new int[s.length()];\n\t\t int[] right = new int[s.length()];\n\t\t\tint max =0;\n\t\t\t// Left Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=0;i 0){\n\t\t\t\t\tif(s.charAt(i) == s.charAt(i-1)){\n\t\t\t\t\t\tleft[i] = left[i-1]+1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleft[i] = 1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tleft[i] =1;\n\t\t\t\t}\n\t\t\t\tmax = Math.max(max,left[i]);\n\t\t\t}\n\t\t\t// Right Array Containing Length Of Subarray Having Equal Characters Till That Index\n\t\t\tfor(int i=s.length()-1;i>=0;i--){\n\t\t\t\tif(i < s.length()-1){\n\t\t\t\t\tif(s.charAt(i+1) == s.charAt(i)){\n\t\t\t\t\t\tright[i] = right[i+1] +1;\n\t\t\t\t\t}else{\n\t\t\t\t\t\tright[i] =1;\n\t\t\t\t\t}\n\t\t\t\t}else{\n\t\t\t\t\tright[i] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Count The Length Of SubString Having Maximum Length When A Character Is Swapped\n\t\t\tfor(int i=1 ; i> intervals[26];\n // a: [st, ed], .....\n for(int i = 0; i < text.size();){\n int st = i, ed = i;\n while(i < text.size() && text[i] == text[st]){\n ed = i;\n i++;\n }\n intervals[text[st] - 'a'].push_back({st, ed});\n }\n \n int ans = 0;\n for(int i = 0; i < 26; i++){\n for(int j = 0; j < intervals[i].size(); j++){\n // 单个的最大值\n int len1 = intervals[i][j].second - intervals[i][j].first + 1;\n if(intervals[i].size() > 1)\n len1++;\n ans = max(ans, len1);\n \n // 合并\n // [1, 2] [4, 6]\n if(j+1 < intervals[i].size() && intervals[i][j].second + 2 == intervals[i][j+1].first){\n int len2 = intervals[i][j].second - intervals[i][j].first + 1 + intervals[i][j+1].second - intervals[i][j+1].first + 1;\n if(intervals[i].size() > 2){ // 一定有一个愿意牺牲\n len2++;\n }\n ans = max(ans, len2);\n }\n }\n }\n \n return ans;\n }\n};\n\n/**\nabababababac\n\n*/" }, { "title": "Construct Target Array With Multiple Sums", "algo_input": "You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :\n\n\n\tlet x be the sum of all elements currently in your array.\n\tchoose index i, such that 0 <= i < n and set the value of arr at index i to x.\n\tYou may repeat this procedure as many times as needed.\n\n\nReturn true if it is possible to construct the target array from arr, otherwise, return false.\n\n \nExample 1:\n\nInput: target = [9,3,5]\nOutput: true\nExplanation: Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done\n\n\nExample 2:\n\nInput: target = [1,1,1,2]\nOutput: false\nExplanation: Impossible to create target array from [1,1,1,1].\n\n\nExample 3:\n\nInput: target = [8,5]\nOutput: true\n\n\n \nConstraints:\n\n\n\tn == target.length\n\t1 <= n <= 5 * 104\n\t1 <= target[i] <= 109\n\n", "solution_py": "class Solution:\n def isPossible(self, target: List[int]) -> bool:\n if len(target) == 1:\n return target == [1]\n res = sum(target)\n heap = [-elem for elem in target]\n heapify(heap)\n while heap[0]<-1:\n maximum = -heappop(heap)\n res -= maximum\n\n if res == 1:\n return True\n x = maximum % res\n if x == 0 or (x != 1 and x == maximum):\n return False\n\n res += x\n heappush(heap,-x)\n return True", "solution_js": "var isPossible = function(target) {\n let max=0\n let index=-1\n\n for(let i=target.length-1;i>=0;i--){\n if(target[i]>max){\n max=target[i]\n index=i\n }\n }\n if(max===1)return true // if max itself is 1 return true\n\n let total=0\n for(let i=0;i[3,1]->...[10,1] we can make sure it leads to target\n if(total===1)return true;\n // max should be greater than remaining nums sum OR if total is 0 it would lead to infinite loop( num%0 === NaN) so return false\n if(max<=total||total===0)return false;\n max=max%total;\n if(max<1)return false; // it should not be less than 1\n target[index]=max;\n\n return isPossible(target)\n};", "solution_java": "class Solution {\n public boolean isPossible(int[] target) {\n if(target.length==1) return target[0]==1;\n\n PriorityQueue que = new PriorityQueue(Collections.reverseOrder());\n int totsum = 0;\n\n for(int i=0;i& target) {\n \n //Priority queue for storing all the nums in taget in decreasing order.\n priority_queue pq;\n long long sum = 0; //for storing total sum\n\n for(auto num : target){ //adding the nums in pq and sum\n pq.push(num);\n sum+=num;\n }\n \n //iterating untill all elements in pq become 1 (in turn pq.top() will also become 1);\n while(pq.top() != 1){\n\n sum -= pq.top(); //removing the greatest element as it was last upadted when converting [1,1,1...] array to target. So we are left with sum of other elements.\n \n //when there are elements greeter than 1 then sum of other elements can not be 0 or sum can not be greater than top element because sum + x(any number>0) is pq.top().\n if(sum == 0 || sum >= pq.top()) return false;\n \n //if we delete all copies of sum from pq.top() we get an old element.\n int old = pq.top() % sum;\n \n //all old elements were > 0 so it can not be 0 unless sum is 1 (This is only possible if array has only 2 elements)\n if(sum != 1 && old == 0) return false;\n \n pq.pop(); //Deleting greatest element\n\n pq.push(old); //Adding old element to restore array.\n sum += old; //Updating sum\n }\n \n //if all elements are 1 then return true\n return true;\n }\n};" }, { "title": "Perfect Squares", "algo_input": "Given an integer n, return the least number of perfect square numbers that sum to n.\n\nA perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.\n\n \nExample 1:\n\nInput: n = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4.\n\n\nExample 2:\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "class Solution:\n\n def __init__(self):\n self.perSq = []\n\n def numSquares(self, n):\n # finding perfect squares up to n\n i = 1\n while i*i <= n:\n self.perSq.append(i*i)\n i += 1\n\n return self.lengths(n)\n\n # algorithm to find sum from perfect squares\n def outcomes(self, n, current):\n rem = n\n nums = []\n while sum(nums) != n:\n if current < len(self.perSq)*-1:\n current = self.perSq[0]\n\n val = self.perSq[current]\n\n if rem < val:\n current -= 1\n continue\n else:\n nums.append(val)\n rem -= val\n if (rem > 0) and (rem % val == 0):\n nums.append(val)\n rem -= val\n\n return len(nums)\n\n # algorithm to find sum with least possible numbers\n def lengths(self, n):\n data = []\n for i in range(-1, -1*(len(self.perSq)+1), -1):\n data.append(self.outcomes(n, i))\n\n return min(data)", "solution_js": "var numSquares = function(n) {\n let dp = new Array(n+1).fill(Infinity);\n \n dp[0] = 0;\n \n for(let i=1; i <= n; i++){\n for(let k=1; k*k <= i; k++){\n dp[i] = Math.min(dp[i],dp[i - (k*k)] + 1);\n }\n }\n \n return dp[n];\n};", "solution_java": "class Solution {\n public int numSquares(int n) {\n \n ArrayList perfect_squares = new ArrayList<>();\n int i=1;\n while(i*i <= n){\n perfect_squares.add(i*i);\n i++;\n }\n Integer[][] dp = new Integer[n+1][perfect_squares.size()+1];\n int answer = helper(n , perfect_squares , perfect_squares.size()-1,dp);\n return answer;\n }\n \n public int helper(int n , ArrayList coins ,int i,Integer[][] dp){\n \n if(n == 0){\n return 0;\n }\n if(i<0){\n return 999999; // I'm not taking INT_MAX here, since int variables will overflow with (1 + INT_MAX)\n\t\t\t // just take any number greater than constraint ( 10^4) \n }\n if(dp[n][i] != null){\n return dp[n][i];\n }\n int nottake = 0 + helper(n , coins, i-1,dp);\n int take = 9999999;\n if(coins.get(i) <= n){\n take = 1 + helper(n-coins.get(i),coins,i,dp ); \n }\n dp[n][i] = Math.min(nottake,take);\n return dp[n][i];\n \n \n \n }\n \n \n}", "solution_c": "class Solution {\npublic:\n int numSquares(int n) {\n \n vector perfectSq;\n \n for(int i = 1; i*i <= n; ++i){\n perfectSq.push_back(i*i);\n }\n \n int m = perfectSq.size();\n vector> dp( m+1, vector(n+1, 0));\n \n dp[0][0] = 0;\n for( int i = 1; i <= n; ++i ) dp[0][i] = INT_MAX;\n \n for(int i = 1; i <= m; ++i){\n for(int j = 1; j <= n; ++j){\n \n if( j < perfectSq[i-1]){\n dp[i][j] = dp[i-1][j];\n }\n else{\n dp[i][j] = min( dp[i-1][j], dp[i][ j - perfectSq[i-1] ] + 1);\n }\n \n }\n }\n \n return dp[m][n];\n }\n};" }, { "title": "Count Number of Maximum Bitwise-OR Subsets", "algo_input": "Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.\n\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.\n\nThe bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).\n\n \nExample 1:\n\nInput: nums = [3,1]\nOutput: 2\nExplanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]\n\n\nExample 2:\n\nInput: nums = [2,2,2]\nOutput: 7\nExplanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.\n\n\nExample 3:\n\nInput: nums = [3,2,1,5]\nOutput: 6\nExplanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 16\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \n def dfs(i,val):\n if maxBit == val : return 1<<(len(nums)-i)\n if i == len(nums): return 0\n return dfs(i+1,val|nums[i]) + dfs(i+1,val)\n maxBit = 0\n for i in nums: maxBit |= i\n return dfs(0,0)", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countMaxOrSubsets = function(nums) {\n\n let n = nums.length;\n let len = Math.pow(2, n);\n let ans = 0;\n let hash = {};\n\n for (let i = 0; i < len; i++) {\n let tmp = 0;\n for (let j = 0; j < n; j++) {\n if(i & (1 << j)) {\n tmp |= nums[j];\n }\n }\n if (hash[tmp]) {\n hash[tmp] += 1;\n } else {\n hash[tmp] = 1;\n }\n ans = Math.max(ans, tmp);\n }\n\n return hash[ans];\n};", "solution_java": "class Solution {\n public int countMaxOrSubsets(int[] nums) {\n \n subsets(nums, 0, 0);\n return count;\n }\n \n int count = 0;\n int maxOR = 0;\n \n private void subsets(int[] arr, int vidx, int OR){\n \n if(vidx == arr.length){\n \n if(OR == maxOR){\n count ++;\n }else if(OR > maxOR){\n count = 1;\n maxOR = OR;\n }\n \n return;\n }\n \n // include\n subsets(arr, vidx+1, OR | arr[vidx]);\n \n // exclude\n subsets(arr, vidx+1, OR);\n }\n}", "solution_c": "class Solution {\npublic:\n int countMaxOrSubsets(vector& nums) {\n \n int i,j,max_possible_or=0,n=nums.size(),ans=0;\n \n //maximum possible or=or of all number in array\n for(i=0;i int:\n # TC = O(NlogN) because sorting the array \n # SC = O(1); no extra space needed; sorting was done in place.\n \n # sorting the array in descending order\n nums.sort(reverse = True)\n \n # maximum product can only occur for:\n # 1. positive no * positive no * positive no\n # 2. negative no * negative no * positive no\n \n # one negative and two positives and all negatives wont give max product\n # case where all numbers in the array are negative \n # eg : [-4,-3,-2,-1] is covered in all positives \n \n return max(nums[0]*nums[1]*nums[2],nums[-1]*nums[-2]*nums[0])", "solution_js": "var maximumProduct = function(nums) {\n nums.sort((a, b) => a-b)\n \n var lastNumber = nums.length - 1\n var midNumber = nums.length - 2\n var firstNumber = nums.length - 3\n var total = nums[lastNumber] * nums[midNumber] * nums[firstNumber]\n return total\n \n};", "solution_java": "class Solution {\n public int maximumProduct(int[] nums) {\n int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;\n int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;\n for (int n: nums) {\n if (n <= min1) {\n min2 = min1;\n min1 = n;\n } else if (n <= min2) { // n lies between min1 and min2\n min2 = n;\n }\n if (n >= max1) { // n is greater than max1, max2 and max3\n max3 = max2;\n max2 = max1;\n max1 = n;\n } else if (n >= max2) { // n lies betweeen max1 and max2\n max3 = max2;\n max2 = n;\n } else if (n >= max3) { // n lies betwen max2 and max3\n max3 = n;\n }\n }\n return Math.max(min1 * min2 * max1, max1 * max2 * max3);\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumProduct(vector& nums) {\n\n int min1 = INT_MAX , min2 = INT_MAX; // Both have the maximum value that is +infinte\n int max1 = INT_MIN, max2 = INT_MIN , max3 = INT_MIN; //All these have the minimum value that is -infinte\n\n //now finding all these value above declared.\n for(int i = 0 ; i < nums.size() ; i++)\n {\n if(nums[i] > max1 )\n {\n max3 = max2 ;\n max2 = max1;\n max1 = nums[i];\n\n }\n else if(nums[i] > max2)\n {\n max3 = max2 ;\n max2 = nums[i] ;\n\n }\n else if(nums[i] > max3)\n {\n max3 = nums[i] ;\n\n }\n\n if(nums[i] < min1)\n {\n min2 = min1 ;\n min1 = nums[i] ;\n\n }\n else if(nums[i] < min2)\n {\n min2 = nums[i];\n\n }\n }\n return max(min1*min2*max1 , max1*max2*max3);\n }\n};" }, { "title": "Maximum Frequency Stack", "algo_input": "Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\n\nImplement the FreqStack class:\n\n\n\tFreqStack() constructs an empty frequency stack.\n\tvoid push(int val) pushes an integer val onto the top of the stack.\n\tint pop() removes and returns the most frequent element in the stack.\n\t\n\t\tIf there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.\n\t\n\t\n\n\n \nExample 1:\n\nInput\n[\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]\nOutput\n[null, null, null, null, null, null, null, 5, 7, 5, 4]\n\nExplanation\nFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n\n\n \nConstraints:\n\n\n\t0 <= val <= 109\n\tAt most 2 * 104 calls will be made to push and pop.\n\tIt is guaranteed that there will be at least one element in the stack before calling pop.\n\n", "solution_py": "class FreqStack:\n\n def __init__(self):\n self.cnt = {}\n self.maxcount = 0\n self.stack = {}\n\n def push(self, val: int) -> None:\n count = self.cnt.get(val,0)+1\n self.cnt[val] = count\n if count>self.maxcount:\n self.maxcount = count\n self.stack[count] = []\n self.stack[count].append(val)\n\n def pop(self) -> int:\n res = self.stack[self.maxcount].pop()\n self.cnt[res]-=1\n if not self.stack[self.maxcount]:\n self.maxcount-=1\n return res\n\n# Your FreqStack object will be instantiated and called as such:\n# obj = FreqStack()\n# obj.push(val)\n# param_2 = obj.pop()", "solution_js": "var FreqStack = function() {\n //hashMap to keep track of the values being repeated\n this.frequencyMap = {};\n\n //List map to keep track of the sequence of the value being entered\n this.listMap = {};\n\n //Max Frequency variable to keep track of the max frequency\n this.maxValueFrequency = 0;\n};\n\n/**\n * @param {number} val\n * @return {void}\n */\nFreqStack.prototype.push = function(val) {\n //if the hashMap doesn't have value being pushed then make a entry to it with 1 else increament by 1\n this.frequencyMap[val] = this.frequencyMap[val] ? this.frequencyMap[val]+1 : 1;\n\n //get the frequency of the value being pushed\n const currentValueFrequency = this.frequencyMap[val];\n\n //check if the current frequency is max or itself\n this.maxValueFrequency = Math.max(this.maxValueFrequency, currentValueFrequency);\n\n //if current value frequency is not in the listmap then make a new entry else push it\n if(!this.listMap[currentValueFrequency]) this.listMap[currentValueFrequency] =[val];\n else this.listMap[currentValueFrequency].push(val);\n\n};\n\n/**\n * @return {number}\n */\nFreqStack.prototype.pop = function() {\n //make a temporary list of the max value frequency\n const tempList = this.listMap[this.maxValueFrequency];\n\n //get the last element from the temporary list\n const top = tempList[tempList.length - 1];\n\n //remove the item from the list\n tempList.pop();\n\n //update the list\n this.listMap[this.maxValueFrequency] = tempList;\n\n //if the popped item exist in the frequecy map then decrease it by 1\n if(this.frequencyMap[top]) this.frequencyMap[top]--;\n\n //if the max value frequency in the listmap is blank then reduce the maxValueFrequency;\n if(this.listMap[this.maxValueFrequency].length === 0) this.maxValueFrequency--;\n\n //return the max value frequency with proper order if it is same\n return top;\n\n};\n\n//Time O(Log n) // for both Push and Pop\n//Space O(n) for storing all the values in the hashMap and listMap", "solution_java": "class Node{\n int data, freq, time;\n Node(int data, int freq, int time){\n this.data=data;\n this.freq=freq;\n this.time=time;\n }\n}\n\nclass CompareNode implements Comparator{\n @Override\n public int compare(Node a, Node b){\n if(a.freq-b.freq==0){\n return b.time-a.time;\n }\n return b.freq-a.freq;\n }\n}\n\nclass FreqStack {\n PriorityQueue pq;\n Map map;\n int c=0;\n public FreqStack(){\n pq=new PriorityQueue<>(new CompareNode());\n map=new HashMap<>();\n }\n\n public void push(int val){\n c++;\n int freq=1;\n if(map.containsKey(val)){\n freq+=map.get(val).freq;\n }\n map.put(val, new Node(val, freq, c));\n pq.add(new Node(val,freq,c++));\n }\n\n public int pop() {\n Node r=pq.remove();\n Node a=map.get(r.data);\n a.freq--;\n return r.data;\n }\n}", "solution_c": "class FreqStack {\npublic:\n unordered_map ump;\n unordered_map> ump_st;\n \n int cap=1;\n \n FreqStack() {\n ump.clear();\n ump_st.clear();\n }\n \n void push(int val) {\n\t\n\t\t//increasing the count\n if(ump.find(val)!=ump.end())\n {\n ump[val]++;\n }\n else\n {\n ump[val]=1;\n }\n \n\t\t//update the highest level\n if(cap int:\n count = 0 \n while s or g:\n if s%2 != g%2: count+=1\n s, g = s//2, g//2\n return count", "solution_js": "var minBitFlips = function(start, goal) {\n return (start^goal).toString(2).split(\"0\").join(\"\").length;\n};", "solution_java": "class Solution {\n\tpublic static int minBitFlips(int a1, int a2) {\n\t\tint n = (a1 ^ a2);\n\t\tint res = 0;\n\t\twhile (n != 0) {\n\t\t\tres++;\n\t\t\tn &= (n - 1);\n\t\t}\n\t\treturn res;\n\t}\n}", "solution_c": "class Solution {\npublic:\n int minBitFlips(int start, int goal) {\n return __builtin_popcount(start^goal);\n }\n};" }, { "title": "Parallel Courses III", "algo_input": "You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.\n\nYou must find the minimum number of months needed to complete all the courses following these rules:\n\n\n\tYou may start taking a course at any time if the prerequisites are met.\n\tAny number of courses can be taken at the same time.\n\n\nReturn the minimum number of months needed to complete all the courses.\n\nNote: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).\n\n \nExample 1:\n\n\nInput: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\nOutput: 8\nExplanation: The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.\n\n\nExample 2:\n\n\nInput: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\nOutput: 12\nExplanation: The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 5 * 104\n\t0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)\n\trelations[j].length == 2\n\t1 <= prevCoursej, nextCoursej <= n\n\tprevCoursej != nextCoursej\n\tAll the pairs [prevCoursej, nextCoursej] are unique.\n\ttime.length == n\n\t1 <= time[i] <= 104\n\tThe given graph is a directed acyclic graph.\n\n", "solution_py": "class Solution:\n def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n in_degree=defaultdict(int)\n graph=defaultdict(list)\n latest=[0]*(n+1)\n for u,v in relations:\n graph[u].append(v)\n in_degree[v]+=1\n q=[]\n for i in range(1,n+1):\n if in_degree[i]==0:\n latest[i]=time[i-1]\n q.append(i)\n while q:\n node=q.pop()\n t0=latest[node]\n for nei in graph[node]:\n t=time[nei-1]\n latest[nei]=max(latest[nei],t0+t)\n in_degree[nei]-=1\n if in_degree[nei]==0:\n q.append(nei)\n return max(latest)", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} relations\n * @param {number[]} time\n * @return {number}\n */\nvar minimumTime = function(n, relations, time) {\n /*\n Approach: We can create reverse edges for relation.\n    Then longest path(by weightage of time for each node) from the node will be the minimum time to finish that course(node)\n    Now we can use simple DFS to find the longest path for each node.\n    The node containing the longest path will be course to finish the last.We can also use memo to save the longest path from node, so when we reach to this node, we need not to calculate the longest path again. \n */\n let edges={};\n for(let i=0;i adj[] = new ArrayList[n];\n int indegree[] = new int[n];\n int completionTime[] = new int[n];\n for(int i=0; i();\n for(int relation[]: relations){\n int u = relation[0]-1, v = relation[1]-1;\n adj[u].add(v);\n indegree[v]++;\n }\n Queue q = new LinkedList<>();\n for(int i=0; i>& relations, vector& time) {\n vector> adjList(n);\n vector inDegree(n),cTime(n,0);\n\n for(auto &r:relations) { // Create adjacency list and in degree count vectors.\n adjList[r[0]-1].push_back(r[1]-1);\n inDegree[r[1]-1]++;\n }\n queue> q;\n\n for(int i=0;i int:\n s = [0]\n n = len(arr)\n if n <= 1:\n return 0 \n for i in range(n):\n s.append(s[-1]^arr[i])\n # a = s[i] ^ s[j], b = s[j] ^ s[k+1] \n count = defaultdict(int)\n # a = b <-> a ^ b == 0 <-> (s[i] ^ s[j]) ^ (s[j] ^ s[k+1]) == 0 \n # <-> s[i] ^ (s[j] ^ m ) = 0 (where m = s[j] ^ s[k+1])\n # <-> s[i] ^ s[k+1] == 0 <-> s[i] == s[k+1]\n \n res = 0 \n # len(s) == n+1, 0<=i<=n-2, 1<=k<=n-1, i+1<=j<=k\n for i in range(n-1):\n for k in range(i+1, n):\n if s[i] == s[k+1]:\n res += (k-i)\n return res ", "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar countTriplets = function(arr) {\n let count = 0\n for(let i=0;i= 0; i--){\n \n int bit = 1 & (num >> i) ;\n \n if ( root->child[bit] == NULL){\n root->child[bit] = new TrieNode();\n }\n root = root->child[bit];\n }\n root->sumOfIndex += idx;\n root->numOfIndex++;\n }\n int calculateIndexPair(TrieNode* root, int num, int idx){\n for( int i = 31; i >= 0; i--){\n int bit = 1 & (num >> i);\n \n if (root->child[bit] == NULL){\n return 0;\n }\n root = root->child[bit];\n }\n return (((root->numOfIndex) * idx) - (root->sumOfIndex));\n }\n int countTriplets(vector& arr) {\n long long ans=0;\n int XOR = 0;\n TrieNode* root = new TrieNode();\n \n for ( int i = 0 ; i < arr.size(); i++){\n addNumber(root, XOR, i);\n XOR ^= arr[i];\n ans = (ans + calculateIndexPair(root, XOR, i)) % 1000000007;\n }\n return ans;\n }\n};" }, { "title": "Baseball Game", "algo_input": "You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.\n\nAt the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:\n\n\n\tAn integer x - Record a new score of x.\n\t\"+\" - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.\n\t\"D\" - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.\n\t\"C\" - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.\n\n\nReturn the sum of all the scores on the record. The test cases are generated so that the answer fits in a 32-bit integer.\n\n \nExample 1:\n\nInput: ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput: 30\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\n\n\nExample 2:\n\nInput: ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput: 27\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n\n\nExample 3:\n\nInput: ops = [\"1\",\"C\"]\nOutput: 0\nExplanation:\n\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n\n\n \nConstraints:\n\n\n\t1 <= ops.length <= 1000\n\tops[i] is \"C\", \"D\", \"+\", or a string representing an integer in the range [-3 * 104, 3 * 104].\n\tFor operation \"+\", there will always be at least two previous scores on the record.\n\tFor operations \"C\" and \"D\", there will always be at least one previous score on the record.\n\n", "solution_py": "class Solution:\n def calPoints(self, ops: List[str]) -> int:\n temp = []\n for i in ops:\n if i!=\"C\" and i!=\"D\" and i!=\"+\":\n temp.append(int(i))\n elif i==\"C\":\n temp.remove(temp[len(temp)-1])\n elif i==\"D\":\n temp.append(2*temp[len(temp)-1])\n elif i==\"+\":\n temp.append(temp[len(temp)-1]+temp[len(temp)-2])\n \n \n return sum(temp)", "solution_js": "//Plus sign in the below algo confirms that the data type we are getting is integer. So, instead of adding it as a string, the data type will be added as integer\nvar calPoints = function(ops) {\n let stack = [];\n for(let i = 0; i < ops.length; i++){\n if(ops[i] === \"C\")\n stack.pop();\n else if(ops[i] === \"D\")\n stack.push((+stack[stack.length - 1]) * 2);\n //we have to take stack.length to get the element of stack. We cannot take i for getting the element of stack as i refers to ops and it wont give the index of previous element in stack\n else if(ops[i] ===\"+\")\n stack.push((+stack[stack.length - 1]) + (+stack[stack.length - 2]));\n else\n stack.push(+ops[i]);\n }\n let sum = 0;\n for(let i = 0; i < stack.length; i++){\n sum = sum + stack[i];\n }\n return sum;\n};", "solution_java": "class Solution {\n public int calPoints(String[] ops) {\n List list = new ArrayList();\n \n for(int i = 0; i < ops.length; i++){\n switch(ops[i]){\n case \"C\":\n list.remove(list.size() - 1);\n break;\n case \"D\":\n list.add(list.get(list.size() - 1) * 2);\n break;\n case \"+\":\n list.add(list.get(list.size() - 1) + list.get(list.size() - 2));\n break;\n default:\n list.add(Integer.valueOf(ops[i]));\n break;\n }\n }\n \n int finalScore = 0;\n for(Integer score: list)\n finalScore += score;\n \n return finalScore;\n }\n}", "solution_c": "class Solution {\npublic:\n int calPoints(vector& ops) {\n stackst;\n int n = ops.size();\n for(int i=0;i str:\n nums = list(map(str, nums))\n nums = reversed(sorted(nums, key = cmp_to_key(lambda x, y: -1 if int(x+y) < int(y+x) else ( 1 if int(x+y) > int(y+x) else 0))))\n res = \"\".join(nums)\n return res if int(res) else \"0\"", "solution_js": "var largestNumber = function(nums) {\n var arr=[]\n nums.forEach((item)=>{\n arr.push(item.toString());\n })\n arr.sort((a,b)=>(b+a).localeCompare(a+b));\n var ret=\"\"\n if(arr[0]==\"0\") return \"0\";\n arr.forEach((item)=>{\n ret+=item;\n })\n return ret;\n};", "solution_java": "class Solution {\n public String largestNumber(int[] nums) {\n String[] arr=new String[nums.length];\n for(int i=0;i(b+a).compareTo(a+b));\n if(arr[0].equals(\"0\")) return \"0\";\n StringBuilder builder=new StringBuilder();\n for(String item:arr){\n builder.append(item);\n }\n return builder.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string largestNumber(vector& nums) {\n sort(nums.begin(),nums.end(),[&](int a,int b){\n string order1 = to_string(a)+to_string(b);\n string order2 = to_string(b)+to_string(a);\n return order1>order2;\n });\n \n string ans = \"\";\n for(int i = 0;i= len(s):\n result.append(\" \".join(ans))\n return\n\n for w in dic[s[idx]]:\n if s[idx : idx+len(w)] == w:\n ans.append(w)\n recursion(idx+len(w), ans)\n ans.pop()\n\n return\n recursion(0, [])\n return result", "solution_js": "var wordBreak = function(s, wordDict) {\n const n = s.length;\n const result = [];\n\n const findValidSentences = (currentString = '', remainingString = s, currentIndex = 0) => {\n if(currentIndex === remainingString.length) {\n if(wordDict.includes(remainingString)) {\n result.push(`${currentString} ${remainingString}`.trim())\n }\n return result;\n }\n\n const newWord = remainingString.slice(0, currentIndex);\n if(wordDict.includes(newWord)) {\n const newCurrentString = `${currentString} ${newWord}`;\n const newRemainingString = remainingString.slice(currentIndex);\n findValidSentences(newCurrentString, newRemainingString, 0);\n }\n\n return findValidSentences(currentString, remainingString, currentIndex + 1);\n }\n\n return findValidSentences();\n};", "solution_java": "class Solution {\n\tList res = new ArrayList<>();\n\tString s;\n\tint index = 0;\n\tSet set = new HashSet<>();\n public List wordBreak(String s, List wordDict) {\n this.s = s;\n\t\tfor (String word: wordDict) set.add(word);\n\t\tbacktrack(\"\");\n\t\treturn res;\n }\n\tpublic void backtrack(String sentence) {\n\t if (index == s.length()) {\n\t res.add(sentence.trim());\n\t return;\n }\n int indexCopy = index;\n for (int i = index + 1; i <= s.length(); i++) {\n\t String str = s.substring(index, i);\n\t if (set.contains(str)) {\n\t index = i;\n\t backtrack(sentence + \" \" + str);\n\t index = indexCopy;\n }\n }\n return;\n }\n}", "solution_c": "class Solution {\npublic:\n void helper(string s, unordered_set& dict,int start, int index,string current,vector& ans){\n if(start==s.size()){\n ans.push_back(current);\n return;\n }\n if(index==s.size()) return;\n\n string sub=s.substr(start,index-start+1);\n\n if(dict.count(sub)>0){\n string recursion;\n if(current.size()==0) recursion=sub;\n else recursion=current+\" \"+sub; \n helper(s,dict,index+1,index+1,recursion,ans);\n }\n helper(s,dict,start,index+1,current,ans);\n return;\n }\n vector wordBreak(string s, vector& wordDict) {\n unordered_set dict;\n for(int i=0;i ans;\n helper(s,dict,0,0,\"\",ans);\n return ans;\n \n }\n};" }, { "title": "Number of Ways to Split Array", "algo_input": "You are given a 0-indexed integer array nums of length n.\n\nnums contains a valid split at index i if the following are true:\n\n\n\tThe sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.\n\tThere is at least one element to the right of i. That is, 0 <= i < n - 1.\n\n\nReturn the number of valid splits in nums.\n\n \nExample 1:\n\nInput: nums = [10,4,-8,7]\nOutput: 2\nExplanation: \nThere are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.\n\n\nExample 2:\n\nInput: nums = [2,3,1,0]\nOutput: 2\nExplanation: \nThere are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t-105 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n prefix_sum = [nums[0]]\n n = len(nums)\n for i in range(1, n):\n prefix_sum.append(nums[i] + prefix_sum[-1]) \n \n count = 0\n for i in range(n-1):\n if prefix_sum[i] >= prefix_sum[n-1] - prefix_sum[i]:\n count += 1\n return count", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar waysToSplitArray = function(nums) {\n let result = 0;\n let letsum = 0;\n let rightsum = nums.reduce((a,b)=> a+b);\n let end = nums.length-1;\n for (let i = 0;i=rightsum) {\n result++;\n }\n }\n return result;\n};", "solution_java": "class Solution {\n public int waysToSplitArray(int[] nums) {\n long sum = 0;\n for(int i : nums){\n sum+=i;\n }\n int sol = 0;\n long localSum = 0;\n for(int i=0; i= sum-localSum){\n sol++;\n }\n }\n return sol;\n }\n}", "solution_c": "class Solution {\npublic:\n int waysToSplitArray(vector& nums) {\n\n long long sumFromBack(0), sumFromFront(0);\n for (auto& i : nums) sumFromBack += i;\n\n int n(size(nums)), res(0);\n for (auto i=0; i= sumFromBack) res++;\n }\n return res;\n }\n};" }, { "title": "Check if All the Integers in a Range Are Covered", "algo_input": "You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.\n\nReturn true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.\n\nAn integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.\n\n \nExample 1:\n\nInput: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput: true\nExplanation: Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.\n\n\nExample 2:\n\nInput: ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput: false\nExplanation: 21 is not covered by any range.\n\n\n \nConstraints:\n\n\n\t1 <= ranges.length <= 50\n\t1 <= starti <= endi <= 50\n\t1 <= left <= right <= 50\n\n", "solution_py": "class Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n \n \n t=[0]*(60)\n \n for i in ranges:\n \n t[i[0]]+=1\n t[i[1]+1]-=1\n \n for i in range(1,len(t)):\n t[i] += t[i-1]\n \n return min(t[left:right+1])>=1\n \n \n \n \n ", "solution_js": "var isCovered = function(ranges, left, right) {\n var map=new Map()\n for(let i=left;i<=right;i++){\n map.set(i,0)\n }\n for(let range of ranges){\n for(let i=range[0];i<=range[1];i++){\n map.set(i,1)\n }\n }\n // console.log(map)\n for(let key of map.keys()){\n if(map.get(key)===0) return false\n }\n return true\n};", "solution_java": "class Solution {\n public boolean isCovered(int[][] ranges, int left, int right) {\n boolean flag = false;\n for (int i=left; i<=right; i++) {\n for (int[] arr: ranges) {\n if (i >= arr[0] && i <= arr[1]) {\n flag = true;\n break;\n }\n }\n if (!flag) return false;\n flag = false;\n }\n\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isCovered(vector>& ranges, int left, int right) {\n int n = ranges.size();\n \n sort(ranges.begin(), ranges.end());\n \n if(left < ranges[0][0]) //BASE CASE\n return false;\n \n bool ans = false;\n \n for(int i = 0; i < n; i++){\n if(left>=ranges[i][0] && left<=ranges[i][1]){\n left = ranges[i][1]+1;\n }\n if(left > right){\n ans = true;\n break;\n }\n }\n return ans;\n }\n};" }, { "title": "Reverse Integer", "algo_input": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.\n\nAssume the environment does not allow you to store 64-bit integers (signed or unsigned).\n\n \nExample 1:\n\nInput: x = 123\nOutput: 321\n\n\nExample 2:\n\nInput: x = -123\nOutput: -321\n\n\nExample 3:\n\nInput: x = 120\nOutput: 21\n\n\n \nConstraints:\n\n\n\t-231 <= x <= 231 - 1\n\n", "solution_py": "import bisect\nclass Solution:\n def reverse(self, x: int) -> int:\n\n flag = 0\n if x<0:\n x = abs(x)\n flag = 1\n \n l = [i for i in str(x)]\n l.reverse()\n \n ret = ''.join(l)\n ret = int(ret)\n \n if flag == 1:\n ret = ret*-1\n \n if ((ret >= (-(2**31))) and (ret<=((2**31)-1))):\n return ret\n else:\n return 0", "solution_js": "var reverse = function(x) {\n let val = Math.abs(x)\n let res = 0\n while(val !=0){\n res = (res*10) + val %10\n val = Math.floor(val/10)\n }\n if(x < 0)res = 0 - res\n return (res > ((2**31)-1) || res < (-2)**31) ? 0 : res \n};", "solution_java": "class Solution {\n public int reverse(int x) {\n long reverse = 0;\n while (x != 0) {\n int digit = x % 10;\n reverse = reverse * 10 + digit;\n x = x / 10;\n }\n if (reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) return 0;\n return (int) reverse;\n }\n}", "solution_c": "class Solution {\npublic:\n int reverse(int x) {\n long res = 0;\n while (abs(x) > 0) {\n res = (res + x % 10) * 10;\n x /= 10;\n }\n x < 0 ? res = res / 10 * -1 : res = res / 10;\n if (res < INT32_MIN || res > INT32_MAX) {\n res = 0;\n }\n return res;\n }\n};" }, { "title": "Minimum Cost to Cut a Stick", "algo_input": "Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:\n\nGiven an integer array cuts where cuts[i] denotes a position you should perform a cut at.\n\nYou should perform the cuts in order, you can change the order of the cuts as you wish.\n\nThe cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\n\nReturn the minimum total cost of the cuts.\n\n \nExample 1:\n\nInput: n = 7, cuts = [1,3,4,5]\nOutput: 16\nExplanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n\nThe first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n\nExample 2:\n\nInput: n = 9, cuts = [5,6,1,4,2]\nOutput: 22\nExplanation: If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 106\n\t1 <= cuts.length <= min(n - 1, 100)\n\t1 <= cuts[i] <= n - 1\n\tAll the integers in cuts array are distinct.\n\n", "solution_py": "class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n cuts = [0] + sorted(cuts) + [n]\n k = len(cuts)\n dp = [[float('inf')] * k for _ in range(k)]\n for l in range(1, k + 1):\n for beg in range(k - l):\n end = beg + l\n if l == 1:\n dp[beg][end] = 0\n continue\n for i in range(beg + 1, end):\n currcost = cuts[end] - cuts[beg]\n currcost += dp[beg][i] + dp[i][end]\n dp[beg][end] = min(dp[beg][end], currcost)\n return dp[0][k - 1]", "solution_js": "var minCost = function(n, cuts) {\n cuts = cuts.sort((a, b) => a - b);\n let map = new Map();\n // Use cutIdx to track the idx of the cut position in the cuts array\n function dfs(start, end, cutIdx) {\n let key = `${start}-${end}`;\n if (map.has(key)) return map.get(key);\n let min = Infinity\n for (let i = cutIdx; i < cuts.length; i++) {\n let cut = cuts[i];\n if (cut <= start) continue;\n if (cut < end) {\n let len = end - start;\n let left = dfs(start, cut, 0);\n let right = dfs(cut, end, i + 1);\n min = Math.min(min, len + left + right);\n } else break;\n }\n if (min === Infinity) {\n map.set(key, 0);\n return 0;\n }\n else {\n map.set(key, min);\n return min;\n }\n }\n return dfs(0, n, 0);\n};", "solution_java": "class Solution {\n public int minCost(int n, int[] cuts) {\n \n int len = cuts.length;\n \n Arrays.sort(cuts);\n \n int[] arr = new int[len+2];\n for(int i = 1 ; i <= len ; i++)\n arr[i] = cuts[i-1];\n \n arr[0] = 0;\n arr[len+1] = n;\n int[][] dp = new int[len+1][len+1];\n for(int i = 0 ; i <= len ; i++)\n for(int j = 0 ; j <= len ; j++)\n dp[i][j] = -1;\n return cut(arr , 1 , len , dp);\n }\n \n int cut(int[] cuts , int i , int j , int[][] dp){\n if(i > j)\n return 0;\n \n if(dp[i][j] != -1)\n return dp[i][j];\n \n int mini = Integer.MAX_VALUE;\n for(int k = i ; k <= j ; k++){\n int cost = cuts[j+1]-cuts[i-1] + cut(cuts , i , k-1 , dp) + cut(cuts , k+1 , j , dp);\n mini = Math.min(cost , mini);\n }\n \n return dp[i][j] = mini;\n }\n}", "solution_c": "class Solution {\npublic:\n long cutMin(int i, int j, vector&c, vector>&dp)\n {\n if(i>j) return 0;\n if(dp[i][j]!=-1) return dp[i][j];\n long mini = INT_MAX;\n for(int ind=i;ind<=j;ind++)\n {\n long cost = c[j+1]-c[i-1]+cutMin(i,ind-1,c,dp)+cutMin(ind+1,j,c,dp);\n mini = min(mini,cost);\n }\n return dp[i][j] = mini;\n }\n int minCost(int n, vector& cuts) {\n int c = cuts.size();\n cuts.push_back(0);\n cuts.push_back(n);\n sort(cuts.begin(),cuts.end());\n vector>dp(c+1,vector(c+1,-1));\n return cutMin(1,c,cuts,dp);\n }\n};" }, { "title": "Diameter of Binary Tree", "algo_input": "Given the root of a binary tree, return the length of the diameter of the tree.\n\nThe diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.\n\nThe length of a path between two nodes is represented by the number of edges between them.\n\n \nExample 1:\n\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n\n\nExample 2:\n\nInput: root = [1,2]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-100 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n \"\"\"\n Top Down recursion approach: it is sub optimal\n \"\"\"\n def __init__(self):\n self.max_diameter = 0\n def diameter(self, root):\n if root is None:\n return 0\n return self.max_depth(root.left) + self.max_depth(root.right)\n\n def max_depth(self, root):\n if root is None:\n return 0\n return 1 + max(self.max_depth(root.left), self.max_depth(root.right))\n\n def func(self, root):\n if root is not None:\n diameter = self.diameter(root)\n if self.max_diameter < diameter:\n self.max_diameter = diameter\n self.diameterOfBinaryTree(root.left)\n self.diameterOfBinaryTree(root.right)\n\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.func(root)\n return self.max_diameter\n\n \"\"\"\n Better Approach: I can try to approach this problem using bottom up recursion\n \"\"\"\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n self.diameter = 0\n def fun(root):\n if root is None:\n return 0\n left = fun(root.left)\n right = fun(root.right)\n if left + right > self.diameter:\n self.diameter = left + right\n return max(left, right) + 1\n fun(root)\n return self.diameter", "solution_js": "function fastDiameter(node) {\n if(node == null) {\n let pair = new Array(2).fill(0)\n pair[0] = 0\n pair[1] = 0\n return pair\n }\n \n let leftPair = fastDiameter(node.left)\n let rightPair = fastDiameter(node.right)\n \n let leftDiameter = leftPair[0]\n let rightDiameter = rightPair[0]\n \n let height = leftPair[1] + rightPair[1] + 1\n \n let maxDiameter = Math.max(leftDiameter,rightDiameter,height)\n \n let maxHeight = Math.max(leftPair[1],rightPair[1]) + 1\n \n return [maxDiameter,maxHeight]\n}\n\n// diameter --> number of edges between two end nodes\nvar diameterOfBinaryTree = function(root) {\n \n let pair = fastDiameter(root)\n \n return pair[0]-1\n};", "solution_java": "class Solution {\n // Declare Global Variable ans to 0\n int ans = 0;\n // Depth First Search Function\n public int dfs(TreeNode root) {\n if(root == null) return 0;\n // recursive call for left height\n int lh = dfs(root.left);\n // recursive call for right height\n int rh = dfs(root.right);\n\n // update ans\n ans = Math.max(ans, lh + rh);\n\n // return max value\n return Math.max(lh, rh) + 1;\n }\n\n // Diameter of Binary Tree Function\n public int diameterOfBinaryTree(TreeNode root) {\n // Call dfs Function\n dfs(root);\n return ans;\n }\n}\n\n// Output -\n/*\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n*/\n\n// Time & Space Complexity -\n/*\nTime - O(n)\nSpace - O(n)\n*/", "solution_c": "class Solution {\npublic:\n int diameterOfBinaryTree(TreeNode* root) {\n int diameter = 0;\n height(root, diameter);\n return diameter;\n }\nprivate:\n int height(TreeNode* node, int& diameter) {\n if (!node) {\n return 0;\n }\n int lh = height(node->left, diameter);\n int rh = height(node->right, diameter);\n diameter = max(diameter, lh + rh);\n return 1 + max(lh, rh);\n }\n};" }, { "title": "Sort Characters By Frequency", "algo_input": "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.\n\nReturn the sorted string. If there are multiple answers, return any of them.\n\n \nExample 1:\n\nInput: s = \"tree\"\nOutput: \"eert\"\nExplanation: 'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.\n\n\nExample 2:\n\nInput: s = \"cccaaa\"\nOutput: \"aaaccc\"\nExplanation: Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.\n\n\nExample 3:\n\nInput: s = \"Aabb\"\nOutput: \"bbAa\"\nExplanation: \"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 * 105\n\ts consists of uppercase and lowercase English letters and digits.\n\n", "solution_py": "class Solution:\n def frequencySort(self, s: str) -> str:\n di = Counter(s)\n #it wont strike immediately that this is a heap kind of question.\n heap = []\n heapq.heapify(heap)\n for key,val in di.items():\n heapq.heappush(heap,(-1*val,key))\n # n = len(s)\n res = \"\"\n # print(heap)\n while(len(heap)):\n val,ch = heapq.heappop(heap)\n res+=(ch*(-1*val))\n return res", "solution_js": "var frequencySort = function(s) {\n let obj = {}\n for(const i of s){\n obj[i] = (obj[i] || 0) +1\n }\n let sorted = Object.entries(obj).sort((a,b)=> b[1]-a[1])\n return sorted.map((e)=> e[0].repeat(e[1])).join('')\n};", "solution_java": "class Solution {\n public String frequencySort(String s) {\n HashMap hm1=new HashMap<>();\n TreeMap> hm2=new TreeMap<>(Collections.reverseOrder());\n for(int i=0;i temp=hm2.get(hm1.get(c));\n temp.add(c);\n hm2.put(hm1.get(c),temp);\n }\n else\n {\n ArrayList temp=new ArrayList<>();\n temp.add(c);\n hm2.put(hm1.get(c),temp);\n }\n }\n StringBuilder sb=new StringBuilder(\"\");\n for(int x :hm2.keySet())\n {\n ArrayList temp=hm2.get(x);\n for(char c: temp)\n {\n for(int i=0;imp;\n for(int i=0;i>pq; //store the freq and char pair in max heap\n for(auto it=mp.begin();it!=mp.end();it++)\n {\n pq.push({it->second,it->first});\n }\n string str=\"\";\n int val;\n while(!pq.empty())\n {\n val=pq.top().first; //append the char frequency times\n while(val--)\n {\n str.push_back(pq.top().second);\n }\n pq.pop();\n }\n return str;\n\n }\n};" }, { "title": "Edit Distance", "algo_input": "Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.\n\nYou have the following three operations permitted on a word:\n\n\n\tInsert a character\n\tDelete a character\n\tReplace a character\n\n\n \nExample 1:\n\nInput: word1 = \"horse\", word2 = \"ros\"\nOutput: 3\nExplanation: \nhorse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')\n\n\nExample 2:\n\nInput: word1 = \"intention\", word2 = \"execution\"\nOutput: 5\nExplanation: \nintention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')\n\n\n \nConstraints:\n\n\n\t0 <= word1.length, word2.length <= 500\n\tword1 and word2 consist of lowercase English letters.\n\n", "solution_py": "from functools import cache\n\n\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m, n = len(word1), len(word2)\n \n @cache\n def dp(i, j):\n if i == 0:\n return j\n if j == 0:\n return i\n \n l1, l2 = word1[i - 1], word2[j - 1]\n if l1 != l2:\n return 1 + min(\n dp(i, j - 1), # Delete / insert j\n dp(i - 1, j), # Delete / insert i\n dp(i - 1, j - 1) # Replace i or j\n )\n return dp(i - 1, j - 1) \n \n return dp(m, n)", "solution_js": "var minDistance = function(word1, word2) {\n const m = word1.length;\n const n = word2.length;\n\n const memo = new Array(m).fill().map(() => new Array(n));\n const dfs = (i = m - 1, j = n - 1) => {\n if(i < 0 && j < 0) return 0;\n if(i < 0 && j >= 0) return j + 1;\n if(i >= 0 && j < 0) return i + 1;\n if(memo[i][j] !== undefined) return memo[i][j];\n\n if(word1[i] === word2[j]) {\n return memo[i][j] = dfs(i - 1, j - 1);\n }\n\n return memo[i][j] = 1 + Math.min(...[\n dfs(i, j - 1),\n dfs(i - 1, j),\n dfs(i - 1, j - 1)\n ]);\n }\n\n return dfs();\n};", "solution_java": "class Solution {\n \n public int minDistance(String word1, String word2) {\n int m = word1.length();\n int n = word2.length();\n int dp[][] = new int[m][n];\n for(int i=0 ; i> dp(m + 1, vector(n + 1, 0));\n for (int i = 1; i <= m; i++) {\n dp[i][0] = i;\n }\n for (int j = 1; j <= n; j++) {\n dp[0][j] = j;\n }\n for (int i = 1; i <= m; i++) {\n for (int j = 1; j <= n; j++) {\n if (word1[i - 1] == word2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1];\n } else {\n dp[i][j] = min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j])) + 1;\n }\n }\n }\n return dp[m][n];\n }\n};" }, { "title": "Matrix Diagonal Sum", "algo_input": "Given a square matrix mat, return the sum of the matrix diagonals.\n\nOnly include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.\n\n \nExample 1:\n\nInput: mat = [[1,2,3],\n  [4,5,6],\n  [7,8,9]]\nOutput: 25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.\n\n\nExample 2:\n\nInput: mat = [[1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1],\n  [1,1,1,1]]\nOutput: 8\n\n\nExample 3:\n\nInput: mat = [[5]]\nOutput: 5\n\n\n \nConstraints:\n\n\n\tn == mat.length == mat[i].length\n\t1 <= n <= 100\n\t1 <= mat[i][j] <= 100\n\n", "solution_py": "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n \n n = len(mat)\n \n mid = n // 2\n \n summation = 0\n \n for i in range(n):\n \n # primary diagonal\n summation += mat[i][i]\n \n # secondary diagonal\n summation += mat[n-1-i][i]\n \n \n if n % 2 == 1:\n # remove center element (repeated) on odd side-length case\n summation -= mat[mid][mid]\n \n \n return summation", "solution_js": "var diagonalSum = function(mat) {\n return mat.reduce((acc, matrix, i)=>{\n const matrixlength = matrix.length-1;\n return acc += (i !== matrixlength-i) ? matrix[i]+ matrix[matrixlength-i] : matrix[i];\n },0)\n};\n\n/*\n*/", "solution_java": "class Solution {\n public int diagonalSum(int[][] mat) {\n int sum1 = 0;\n int sum2 = 0;\n int n = mat.length;\n for(int i = 0 ; i < n ; i++)\n {\n sum1 += mat[i][i];\n sum2 += mat[i][n-i-1];\n }\n int res = sum1 + sum2;\n if(n%2 != 0)\n {\n res -= mat[n/2][n/2];\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int diagonalSum(vector>& mat) {\n int n = mat.size() ;\n int ans = 0 ;\n\n for(int i = 0 ; i < n ; i++){\n ans = ans + mat[i][i] + mat[i][n - i - 1] ;\n }\n ans = (n & 1) ? ans - mat[n/2][n/2] : ans ;//if n is odd then we have to subtract mat[n/2][n/2] from the ans because we add it twice earlier.\n return ans ;\n }\n};" }, { "title": "Find Peak Element", "algo_input": "A peak element is an element that is strictly greater than its neighbors.\n\nGiven a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.\n\nYou may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.\n\nYou must write an algorithm that runs in O(log n) time.\n\n \nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\n\nExample 2:\n\nInput: nums = [1,2,1,3,5,6,4]\nOutput: 5\nExplanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t-231 <= nums[i] <= 231 - 1\n\tnums[i] != nums[i + 1] for all valid i.\n\n", "solution_py": "class Solution(object):\n def findPeakElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = [-2**32]+nums+[-2**32]\n l,r = 0,len(nums)-1\n while l <=r:\n m = (l+r)//2\n\t\t\t# we find the target:\n if nums[m] > nums[m-1] and nums[m] > nums[m+1]:\n return m -1\n else:\n if nums[m] {\n const midIndex = Math.floor((startIndex + endIndex)/2);\n\n if (startIndex === endIndex) return startIndex;\n if (startIndex + 1 === endIndex) {\n return nums[endIndex] >= nums [startIndex] ? endIndex : startIndex;\n }\n\n if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return midIndex;\n if(nums[midIndex] > nums[midIndex-1] && nums[midIndex] < nums[midIndex+1]) return recursion(midIndex + 1, endIndex);\n if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] > nums[midIndex+1]) return recursion(startIndex, midIndex - 1);\n if(nums[midIndex] < nums[midIndex-1] && nums[midIndex] < nums[midIndex+1])\n return nums[midIndex-1] > nums[midIndex+1] ? recursion(startIndex, midIndex - 1) : recursion(midIndex + 1, endIndex);\n\n }\n\n return recursion(0, nums.length - 1);\n};", "solution_java": "class Solution {\n public int findPeakElement(int[] nums) {\n int start = 0;\n int end = nums.length - 1;\n \n while(start < end){\n int mid = start + (end - start) / 2;\n if(nums[mid] > nums[mid + 1]){\n //It means that we are in decreasing part of the array\n end = mid;\n }\n else{\n //It means that we are in increasing part of the array\n start = mid + 1;\n }\n }\n return start;\n }\n}", "solution_c": "class Solution {\npublic:\n int findPeakElement(vector& nums) {\n int peak = 0;\n for(int i=1; inums[i-1])\n peak = i;\n }\n return peak;\n }\n};" }, { "title": "Number of Good Ways to Split a String", "algo_input": "You are given a string s.\n\nA split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.\n\nReturn the number of good splits you can make in s.\n\n \nExample 1:\n\nInput: s = \"aacaba\"\nOutput: 2\nExplanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\n\n\nExample 2:\n\nInput: s = \"abcd\"\nOutput: 1\nExplanation: Split the string as follows (\"ab\", \"cd\").\n\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 numSplits(self, s: str) -> int:\n one = set()\n two = set()\n dic = {}\n \n for i in s:\n dic[i] = dic.get(i, 0) + 1\n two.add(i)\n tot = 0\n \n for i in s:\n one.add(i)\n dic[i] -= 1\n if dic[i] == 0:\n two.remove(i)\n \n if len(one) == len(two):\n tot += 1\n return tot", "solution_js": "var numSplits = function(s) {\n let n = s.length;\n let preFix = new Array(n) , suFix = new Array(n);\n let preSet = new Set();\n let suSet = new Set();\n\n for(let i=0; ileft(26,0);\n vectorright(26,0);\n int left_count=0,right_count=0;\n int splits=0;\n for(auto &it:s){\n right[it-'a']++;\n if(right[it-'a']==1)right_count++;\n }\n for(auto &it:s){\n left[it-'a']++;\n right[it-'a']--;\n if(left[it-'a']==1)left_count++;\n if(right[it-'a']==0)right_count--;\n if(left_count==right_count)\n splits++;\n }\n return splits;\n }\n};" }, { "title": "Count Pairs With XOR in a Range", "algo_input": "Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.\n\nA nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.\n\n \nExample 1:\n\nInput: nums = [1,4,2,7], low = 2, high = 6\nOutput: 6\nExplanation: All nice pairs (i, j) are as follows:\n - (0, 1): nums[0] XOR nums[1] = 5 \n - (0, 2): nums[0] XOR nums[2] = 3\n - (0, 3): nums[0] XOR nums[3] = 6\n - (1, 2): nums[1] XOR nums[2] = 6\n - (1, 3): nums[1] XOR nums[3] = 3\n - (2, 3): nums[2] XOR nums[3] = 5\n\n\nExample 2:\n\nInput: nums = [9,8,4,2,1], low = 5, high = 14\nOutput: 8\nExplanation: All nice pairs (i, j) are as follows:\n​​​​​ - (0, 2): nums[0] XOR nums[2] = 13\n  - (0, 3): nums[0] XOR nums[3] = 11\n  - (0, 4): nums[0] XOR nums[4] = 8\n  - (1, 2): nums[1] XOR nums[2] = 12\n  - (1, 3): nums[1] XOR nums[3] = 10\n  - (1, 4): nums[1] XOR nums[4] = 9\n  - (2, 3): nums[2] XOR nums[3] = 6\n  - (2, 4): nums[2] XOR nums[4] = 5\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t1 <= nums[i] <= 2 * 104\n\t1 <= low <= high <= 2 * 104\n", "solution_py": "from collections import defaultdict\n\nclass TrieNode:\n def __init__(self):\n self.nodes = defaultdict(TrieNode)\n self.cnt = 0\n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, val):\n cur = self.root\n for i in reversed(range(15)):\n bit = val >> i & 1\n cur.nodes[bit].cnt += 1\n cur = cur.nodes[bit]\n\n def count(self, val, high):\n res = 0\n cur = self.root\n for i in reversed(range(15)):\n if not cur:\n break\n bit = val >> i & 1\n cmp = high >> i & 1\n if cmp:\n res += cur.nodes[bit].cnt\n cur = cur.nodes[1^bit]\n else:\n cur = cur.nodes[bit]\n return res\n\nclass Solution:\n def countPairs(self, nums: List[int], low: int, high: int) -> int:\n trie = Trie()\n res = 0\n for num in nums:\n res += trie.count(num, high + 1) - trie.count(num, low)\n trie.insert(num)\n\n return res", "solution_js": "var countPairs = function(nums, low, high) {\n function insert(num){\n var node = root;\n for(i = 14; i>=0; i--)\n {\n var bit = (num >> i) & 1;\n if(!node.children[bit])\n {\n node.children[bit] = new TrieNode();\n }\n node.children[bit].cnt += 1;\n node = node.children[bit];\n }\n }\n function countSmallerNums(num, limit)\n {\n var cnt = 0;\n // count pairs with num strictly smaller than limit\n var node = root;\n for(i = 14; i>=0 && node; i--)\n {\n var lbit = (limit>>i) & 1;\n var nbit = (num >> i) & 1;\n if(lbit===1)\n {\n // we can decrease on 1 bit\n if(node.children[nbit])\n {\n cnt += node.children[nbit].cnt;\n }\n // go to another way to find next bit count\n node = node.children[1-nbit];\n }\n else\n {\n // cannot increase the lbit === 0,\n // find the same Nbit to XOR to be '0'\n node = node.children[nbit];\n }\n }\n return cnt;\n }\n // starts here\n var root = new TrieNode();\n var res =0;\n for(var num of nums)\n {\n res += countSmallerNums(num, high+1) - countSmallerNums(num, low);\n insert(num);\n }\n return res;\n};\n\nclass TrieNode{\n constructor()\n {\n this.cnt = 0;\n this.children = new Array(2).fill(null);\n }\n}", "solution_java": "class Solution {\n public int countPairs(int[] nums, int low, int high) {\n Trie trie=new Trie();\n int cnt=0;\n for(int i=nums.length-1;i>=0;i--){\n // count all the element whose xor is less the low\n int cnt1=trie.maxXor(nums[i],low);\n // count all the element whose xor is less the high+1\n int cnt2=trie.maxXor(nums[i],high+1);\n trie.add(nums[i]);\n cnt+=cnt2-cnt1;\n }\n return cnt;\n }\n}\nclass Trie{\n private Node root;\n Trie(){\n root=new Node();\n }\n public void add(int x){\n Node cur=root;\n for(int i=31;i>=0;i--){\n int bit=(x>>i)&1;\n if(!cur.contains(bit)){\n cur.put(bit);\n }\n cur.inc(bit);\n cur=cur.get(bit);\n }\n }\n public int maxXor(int x,int limit){\n int low_cnt=0;\n Node cur=root;\n for(int i=31;i>=0 && cur!=null;i--){\n int bit=(x>>i)&(1);\n int req=(limit>>i)&1;\n if(req==1){\n if(cur.contains(bit)){\n low_cnt+=cur.get(bit).cnt;\n }\n cur=cur.get(1-bit);\n }else{\n cur=cur.get(bit);\n }\n\n }\n return low_cnt;\n\n }\n}\nclass Node{\n private Node links[];\n int cnt;\n Node(){\n links=new Node[2];\n cnt=0;\n }\n public void put(int bit){\n links[bit]=new Node();\n }\n public Node get(int bit){\n return links[bit];\n }\n public boolean contains(int bit){\n return links[bit]!=null;\n }\n public void inc(int bit){\n links[bit].cnt++;\n }\n}", "solution_c": "struct Node {\n Node* arr[2];\n int count = 0;\n\n bool contains(int bitNo) {\n return arr[bitNo] != NULL;\n }\n\n void put(int bitNo, Node* newNode) {\n arr[bitNo] = newNode;\n }\n\n Node* getNext(int bitNo) {\n return arr[bitNo];\n }\n\n int getCount(int bitNo) {\n return arr[bitNo]->count;\n }\n\n void setCount(int bitNo) {\n arr[bitNo]->count++;\n }\n};\n\nclass Solution {\npublic:\n\n Node* root = new Node();\n\n void insert(int num) {\n Node* temp = root;\n\n for(int bit=15; bit>=0; bit--) {\n int bitVal = (bool)(num & (1<contains(bitVal)) {\n temp->put(bitVal, new Node());\n }\n temp->setCount(bitVal);\n temp = temp->getNext(bitVal);\n }\n }\n\n int getPairs(int num, int k) {\n Node* temp = root;\n\n int cntPairs = 0;\n\n for(int bit=15; bit>=0 && temp; bit--) {\n int bit_num = (bool)(num & (1<contains(bit_num)) {\n cntPairs += temp->getCount(bit_num);\n }\n if(temp->contains(1 - bit_num)) {\n temp = temp->getNext(1 - bit_num);\n }\n else break;\n }\n else if(temp->contains(bit_num)) {\n temp = temp->getNext(bit_num);\n }\n else {\n break;\n }\n }\n return cntPairs;\n }\n\n int countPairs(vector& nums, int low, int high) {\n\n int n = nums.size();\n int cnt = 0;\n for(int i=0; i Optional[TreeNode]:\n inorder_list = []\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n inorder_list.append(root.val)\n inorder(root.right)\n \n inorder(root)\n inorder_list.append(val)\n \n def get_maximum(val_list):\n max_index = -1\n max_val = -1\n for i, val in enumerate(val_list):\n if val > max_val:\n max_val = val\n max_index = i\n return max_index, max_val\n \n def create_tree(val_list):\n if not len(val_list):\n return None\n index, val = get_maximum(val_list)\n node = TreeNode(val)\n node.left = create_tree(val_list[:index])\n node.right = create_tree(val_list[index+1:])\n return node\n \n b = create_tree(inorder_list)\n return b", "solution_js": "/**\n * @param {TreeNode} root\n * @param {number} val\n * @return {TreeNode}\n */\nvar insertIntoMaxTree = function(root, val) {\n // get new node\n var node = new TreeNode(val);\n\n // no root\n if(!root) {\n return node;\n }\n\n // upward derivation if val larger then root\n if(val > root.val) {\n return node.left = root, node;\n }\n\n // downward derivation\n root.right = insertIntoMaxTree(root.right, val);\n\n // root construct\n return root;\n};", "solution_java": "class Solution {\n public TreeNode insertIntoMaxTree(TreeNode root, int val) {\n if (root==null) return new TreeNode(val);\n if (val > root.val) {\n TreeNode newRoot = new TreeNode(val);\n newRoot.left = root;\n return newRoot;\n }\n root.right = insertIntoMaxTree(root.right, val);\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\n void insertIntoMaxTreeRec(TreeNode* root,TreeNode* newNode)//o(logn)\n {\n\n if(!root)\n return;\n if(root->right&&root->right->valval)\n {\n newNode->left=root->right;\n root->right=newNode;\n\n return;\n\n }\n if(!root->right)\n {root->right=newNode;\n\n return;}\n\n insertIntoMaxTreeRec( root->right, newNode);\n\n }\n TreeNode* insertIntoMaxTree(TreeNode* root, int val) {\n TreeNode* curr=new TreeNode(val);\n\n if(root->valleft=root;\n root=curr;\n }else\n {\n insertIntoMaxTreeRec( root, curr);\n\n }\n return root;\n\n }\n};" }, { "title": "Find Kth Bit in Nth Binary String", "algo_input": "Given two positive integers n and k, the binary string Sn is formed as follows:\n\n\n\tS1 = \"0\"\n\tSi = Si - 1 + \"1\" + reverse(invert(Si - 1)) for i > 1\n\n\nWhere + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).\n\nFor example, the first four strings in the above sequence are:\n\n\n\tS1 = \"0\"\n\tS2 = \"011\"\n\tS3 = \"0111001\"\n\tS4 = \"011100110110001\"\n\n\nReturn the kth bit in Sn. It is guaranteed that k is valid for the given n.\n\n \nExample 1:\n\nInput: n = 3, k = 1\nOutput: \"0\"\nExplanation: S3 is \"0111001\".\nThe 1st bit is \"0\".\n\n\nExample 2:\n\nInput: n = 4, k = 11\nOutput: \"1\"\nExplanation: S4 is \"011100110110001\".\nThe 11th bit is \"1\".\n\n\n \nConstraints:\n\n\n\t1 <= n <= 20\n\t1 <= k <= 2n - 1\n\n", "solution_py": "class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n i, s, hash_map = 1, '0', {'1': '0', '0': '1'}\n for i in range(1, n):\n s = s + '1' + ''.join((hash_map[i] for i in s))[::-1]\n return s[k-1]", "solution_js": "var findKthBit = function(n, k) {\n return recursivelyGenerate(n-1)[k-1];\n}\n\nfunction recursivelyGenerate(bitLength, memo=new Array(bitLength+1)){\n if(bitLength===0) return \"0\";\n if(memo[bitLength]) return memo[bitLength];\n const save = recursivelyGenerate(bitLength-1);\n memo[bitLength] = save + '1' + reverseInvert(save);\n return memo[bitLength];\n}\n\nfunction reverseInvert(s){\n return s.split(\"\").map(a=>a==='0'?'1':'0').reverse().join(\"\");\n}", "solution_java": "class Solution {\n private String invert(String s){\n char [] array=s.toCharArray();\n for(int i=0;i>& points) {\n vectorsk;\n int x,y,maxy=0;\n for(int i=0;i int:\n return func(n,-1,-1)", "solution_js": "var distinctSequences = function(n) {\n // 3D DP [n + 1][7][7] => rollIdx, prev, prevPrev\n const dp = Array.from({ length: n + 1}, () => {\n return new Array(7).fill(0).map(() => new Array(7).fill(0));\n });\n\n const gcd = (a, b) => {\n if(a < b) [b, a] = [a, b];\n while(b) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n\n const ds = (n, p = 0, pp = 0) => {\n if(n == 0) return 1;\n if(dp[n][p][pp] == 0) {\n for(let i = 1; i <= 6; i++) {\n if((i != p && i != pp) && (p == 0 || gcd(p, i) == 1)) {\n dp[n][p][pp] = (dp[n][p][pp] + ds(n - 1, i, p)) % 1000000007;\n }\n }\n }\n return dp[n][p][pp];\n }\n return ds(n);\n};", "solution_java": "class Solution {\n static long[][] dp;\n public int distinctSequences(int n) {\n if(n==1) return 6;\n int mod = 1_000_000_007;\n dp =new long[][]\n {\n {0,1,1,1,1,1},\n {1,0,1,0,1,0},\n {1,1,0,1,1,0},\n {1,0,1,0,1,0},\n {1,1,1,1,0,1},\n {1,0,0,0,1,0}\n };\n for(int i=2;i int:\n two_c_options = 6\n tot_options = 12\n for i in range(n-1):\n temp = tot_options\n tot_options = (two_c_options * 5) + ((tot_options - two_c_options) * 4)\n two_c_options = (two_c_options * 3) + ((temp - two_c_options) * 2)\n tot_options = tot_options % (1000000007)\n return tot_options", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar numOfWays = function(n) {\n const mod = Math.pow(10, 9) + 7;\n const dp212 = [6];\n const dp123 = [6];\n for (let i = 1; i < n; i++) {\n // two sides same\n dp212[i] = (dp212[i - 1] * (5 - 2) + dp123[i - 1] * (6 - 2 - 1 - 1)) % mod;\n // three different colors\n dp123[i] = (dp123[i - 1] * (5 - 1 - 1 - 1) + dp212[i - 1] * (6 - 2 - 2)) % mod;\n }\n return (dp212[n - 1] + dp123[n - 1]) % mod;\n};", "solution_java": "class Solution {\n int MOD = 1000000007;\n int[][] states = {{0,1,0},{1,0,1},{2,0,1},\n {0,1,2},{1,0,2},{2,0,2},\n {0,2,0},{1,2,0},{2,1,0},\n {0,2,1},{1,2,1},{2,1,2}};\n \n HashMap> nextMap = new HashMap<>();\n Long[][] memo;\n \n public int numOfWays(int n) {\n if(n == 0)\n return 0;\n \n\t\t// Graph\n for(int prev = 0; prev < 12; prev++){\n List nexts = new ArrayList<>();\n for(int next = 0; next < 12; next++){\n if(next == prev) continue;\n \n boolean flag = true;\n for(int i = 0; i < 3; i++){\n if(states[prev][i] == states[next][i]){\n flag = false;\n break;\n }\n }\n if(flag)\n nexts.add(next);\n }\n nextMap.put(prev, nexts);\n }\n\t\t\n\t\t//DFS\n memo = new Long[12][n];\n long ways = 0;\n for(int i = 0; i < 12; i++){\n ways += dfs(i, n-1);\n ways %= MOD;\n }\n \n return (int)(ways);\n }\n \n long dfs(int prev, int n){\n if(n == 0)\n return 1;\n \n if(memo[prev][n] != null)\n return memo[prev][n];\n \n long ways = 0;\n \n List nexts = nextMap.get(prev);\n for(int next : nexts){\n ways += dfs(next, n-1);\n ways %= MOD;\n }\n \n memo[prev][n] = ways;\n return ways;\n }\n}", "solution_c": "class Solution {\npublic:\n int numOfWays(int n) {\n int mod=1e9+7;\n long long c2=6,c3=6;\n for(int i=2;i<=n;i++){\n long long temp=c3;\n c3=(2*c3+2*c2)%mod;\n c2=(2*temp+3*c2)%mod;\n }\n return (c2+c3)%mod;\n }\n};" }, { "title": "Network Delay Time", "algo_input": "You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.\n\nWe will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.\n\n \nExample 1:\n\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput: 2\n\n\nExample 2:\n\nInput: times = [[1,2,1]], n = 2, k = 1\nOutput: 1\n\n\nExample 3:\n\nInput: times = [[1,2,1]], n = 2, k = 2\nOutput: -1\n\n\n \nConstraints:\n\n\n\t1 <= k <= n <= 100\n\t1 <= times.length <= 6000\n\ttimes[i].length == 3\n\t1 <= ui, vi <= n\n\tui != vi\n\t0 <= wi <= 100\n\tAll the pairs (ui, vi) are unique. (i.e., no multiple edges.)\n\n", "solution_py": "import heapq\nclass Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n \n adjlist = [[] for _ in range(n+1)]\n \n for src, dst, weight in times:\n adjlist[src].append((dst, weight))\n \n visited = [-1]*(n+1)\n captured =[-1]*(n+1)\n\n priority_queue = [(0,k)]\n \n nums = 0\n total_dist = 0\n \n while priority_queue:\n\n dst, node = heapq.heappop(priority_queue)\n\n if captured[node] != -1:\n continue\n captured[node] = dst\n \n nums += 1\n total_dist = dst\n \n for nbr,wt in adjlist[node]:\n if captured[nbr] == -1:\n heapq.heappush(priority_queue,(captured[node]+wt, nbr))\n if nums == n:\n return total_dist\n else:\n return -1", "solution_js": "/**\n * @param {number[][]} times\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\n\nlet visited,edges,dijkastra_arr,min_heap\nconst MAX_VALUE=Math.pow(10,6);\n\nconst dijkastra=(source)=>{\n visited[source]=true;\n min_heap.pop();\n let nei=edges[source]||[];\n // if(!nei.length)return;\n for(let i=0;i=MAX_VALUE)continue;\n let time_till_dst=time_till_src+t;\n dijkastra_arr[dst]=Math.min(dijkastra_arr[dst],time_till_dst);\n }\n min_heap.sort((a,b)=>{\n return dijkastra_arr[b]-dijkastra_arr[a];\n });\n if(min_heap.length && dijkastra_arr[min_heap[min_heap.length-1]]{\n return dijkastra_arr[b]-dijkastra_arr[a];\n });\n min_heap.pop();//For removing zeroth entry;\n dijkastra(k);\n let max_time=0;\n if(min_heap.length)return -1;\n for(let i=0;i> map = new HashMap<>();\n public int networkDelayTime(int[][] times, int n, int k) {\n for (int i = 1; i <= n; i++) {\n map.put(i, new HashMap<>());\n }\n for (int i = 0; i < times.length; i++) {\n map.get(times[i][0]).put(times[i][1], times[i][2]);\n }\n int ans = BFS(k, n);\n\n return ans == 1000 ? -1 : ans;\n }\n public int BFS(int k, int n) {\n LinkedList queue = new LinkedList<>();\n\n int[] timeReach = new int[n + 1];\n Arrays.fill(timeReach, 1000);\n timeReach[0] = 0;\n\n timeReach[k] = 0;\n\n queue.add(k);\n\n while (!queue.isEmpty()) {\n int rv = queue.remove();\n for (int nbrs : map.get(rv).keySet()) {\n int t = map.get(rv).get(nbrs) + timeReach[rv];\n if (t < timeReach[nbrs]) {\n timeReach[nbrs] = t;\n queue.add(nbrs);\n }\n }\n }\n\n int time = 0;\n\n for (int i : timeReach) {\n time = Math.max(i, time);\n }\n\n return time;\n }\n}", "solution_c": "class cmp{\n public:\n bool operator()(pair &a,pair &b)\n {\n return a.second>b.second;\n }\n};\n\nclass Solution {\npublic:\n int networkDelayTime(vector>& times, int n, int k) {\n vector> a[n];\n for(auto it:times)\n {\n a[it[0]-1].push_back({it[1]-1,it[2]});\n }\n\n priority_queue,vector>,cmp> pq;\n vector dist(n,1e7);\n\n pq.push({k-1,0});\n\n vector vis(n,0);\n while(pq.size())\n {\n auto curr = pq.top();\n pq.pop();\n\n int v = curr.first;\n int w = curr.second;\n\n if(vis[v])continue;\n\n vis[v] = 1;\n dist[v] = w;\n for(auto it:a[v])\n {\n if(vis[it.first]==0)\n {\n pq.push({it.first,it.second + w});\n }\n }\n }\n\n int mx = INT_MIN;\n for(auto it:dist)\n mx = max(mx,it);\n\n if(mx>=1e7)return -1;\n return mx;\n\n }\n};" }, { "title": "Remove Duplicates from Sorted List II", "algo_input": "Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.\n\n \nExample 1:\n\nInput: head = [1,2,3,3,4,4,5]\nOutput: [1,2,5]\n\n\nExample 2:\n\nInput: head = [1,1,1,2,3]\nOutput: [2,3]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 300].\n\t-100 <= Node.val <= 100\n\tThe list is guaranteed to be sorted in ascending order.\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if (not head):\n return None\n\n result = tail = ListNode(-1)\n\n while(head):\n curr = head\n head = head.next\n hasDup = False\n while(head) and (curr.val == head.val):\n hasDup = True\n headNext = head.next\n head = None\n head = headNext\n\n if (hasDup == False):\n tail.next = curr\n tail = tail.next\n tail.next = None\n\n return result.next", "solution_js": "var deleteDuplicates = function(head) {\n \n let map = new Map()\n let result = new ListNode(-1)\n \n let newCurr = result\n let curr = head\n \n while(head){\n if(map.has(head.val)){\n map.set(head.val, 2)\n }else{\n newArr.push(head.val)\n map.set(head.val, 1)\n }\n head = head.next\n }\n \n while(curr){\n if(map.get(curr.val) !== 2){\n newCurr.next = new ListNode(curr.val)\n newCurr = newCurr.next\n }\n curr = curr.next\n }\n \n return result.next\n};", "solution_java": "class Solution {\n public ListNode deleteDuplicates(ListNode head) {\n if (head == null) return head;\n ListNode temp = head;\n int last = -1;\n int[]array = new int[201];\n // zero == index 100\n // one == index 101;\n // -100 == index 0;\n\n while (temp != null){\n array[temp.val + 100]++;\n temp = temp.next;\n }\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n last = i;\n }\n }\n if (last == -1) return null;\n temp = head;\n\n for (int i = 0; i < 201; i++){\n if (array[i] == 1){\n temp.val = i - 100;\n if (i == last){\n temp.next = null;\n break;\n }\n temp=temp.next;\n }\n }\n temp.next = null;\n\n return head;\n }\n}```", "solution_c": "class Solution {\npublic:\n ListNode* deleteDuplicates(ListNode* head) {\n ListNode* k=new ListNode();\n ListNode *root=k,*cur=head;\n while(cur!=NULL)\n {\n ListNode *t=cur;\n while(t->next!=NULL && t->next->val==t->val)\n t=t->next;\n if(t==cur)\n {\n if(root==NULL)\n root->val=t->val;\n else\n {\n ListNode* p=new ListNode(t->val);\n root->next=p;\n root=root->next;\n }\n }\n cur=t->next;\n }\n return k->next;\n }\n};" }, { "title": "Shortest Path Visiting All Nodes", "algo_input": "You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.\n\nReturn the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n\n \nExample 1:\n\nInput: graph = [[1,2,3],[0],[0],[0]]\nOutput: 4\nExplanation: One possible path is [1,0,2,0,3]\n\n\nExample 2:\n\nInput: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput: 4\nExplanation: One possible path is [0,1,4,2,3]\n\n\n \nConstraints:\n\n\n\tn == graph.length\n\t1 <= n <= 12\n\t0 <= graph[i].length < n\n\tgraph[i] does not contain i.\n\tIf graph[a] contains b, then graph[b] contains a.\n\tThe input graph is always connected.\n\n", "solution_py": "class Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n = len(graph)\n dist = [[inf]*n for _ in range(n)]\n \n for i, x in enumerate(graph): \n dist[i][i] = 0\n for ii in x: dist[i][ii] = 1\n \n # floyd-warshall \n for k in range(n): \n for i in range(n): \n for j in range(n): \n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n \n @cache \n def fn(x, mask): \n if mask == 0: return 0 \n ans = inf \n for i in range(n): \n if mask & (1 << i): \n ans = min(ans, dist[x][i] + fn(i, mask ^ (1< 0) {\n const [mask, node, dist] = queue.shift();\n\n if (mask === allVisited) {\n return dist;\n }\n\n for (const neighbor of graph[node]) {\n const newMask = mask | (1 << neighbor);\n const hashValue = newMask * 16 + neighbor;\n\n if (!visited.has(hashValue)) {\n visited.add(hashValue);\n queue.push([newMask, neighbor, dist + 1]);\n }\n }\n }\n\n return -1;\n}", "solution_java": "class Solution {\n class Pair {\n int i;\n int path;\n public Pair(int i, int path) {\n this.i = i;\n this.path = path;\n }\n }\n public int shortestPathLength(int[][] graph) {\n /*\n For each node currentNode, steps as key, visited as value\n boolean[currentNode][steps]\n */\n int n = graph.length;\n\n // 111....1, 1<< n - 1\n int allVisited = (1 << n) - 1;\n\n boolean[][] visited = new boolean[n][1 << n];\n Queue q = new LinkedList<>();\n for (int i = 0; i < n; i++) {\n if (1 << i == allVisited) return 0;\n visited[i][1 << i] = true;\n q.offer(new Pair(i, 1 << i));\n }\n int step = 0;\n while (!q.isEmpty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n Pair p = q.poll();\n int[] edges = graph[p.i];\n\n for(int t: edges) {\n int path = p.path | (1 << t);\n if (path == allVisited) return step + 1;\n if (!visited[t][path]) {\n visited[t][path] = true;\n q.offer(new Pair(t, path));\n }\n }\n }\n step++;\n }\n return step;\n }\n}", "solution_c": "class Solution {\npublic:\n int shortestPathLength(vector>& graph) {\n int n = graph.size();\n string mask = \"\";\n string eq = \"\";\n for(int i=0; i>q;\n set>s;\n for(int i=0; i int:\n dp = [[0]*(len(nums1)+ 1) for _ in range(len(nums2) + 1)]\n max_len = 0\n for row in range(len(nums2)):\n for col in range(len(nums1)):\n if nums2[row] == nums1[col]:\n dp[row][col] = 1 + dp[row - 1][col - 1]\n max_len = max(max_len,dp[row][col])\n else:\n dp[row][col] = 0\n return max_len\n ", "solution_js": "var findLength = function(nums1, nums2) {\n let dp = new Array(nums1.length+1).fill(0).map(\n () => new Array(nums2.length+1).fill(0)\n )\n let max = 0;\n for (let i = 0; i < nums1.length; i++) {\n for (let j = 0; j < nums2.length; j++) {\n if (nums1[i] != nums2[j]) {\n continue;\n }\n dp[i+1][j+1] = dp[i][j]+1;\n max = Math.max(max, dp[i+1][j+1]);\n }\n }\n\n return max;\n};", "solution_java": "class Solution {\n public int findLength(int[] nums1, int[] nums2) {\n int n= nums1.length , m = nums2.length;\n int[][] dp = new int [n+1][m+1];\n // for(int [] d: dp)Arrays.fill(d,-1);\n int ans =0;\n for(int i =n-1;i>=0;i--){\n for(int j = m-1 ;j>=0;j--){\n if(nums1[i]==nums2[j]){\n dp[i][j] = dp[i+1][j+1]+1;\n if(ans& nums1, vector& nums2) {\n \n \n int n1 = nums1.size();\n int n2 = nums2.size();\n\n //moving num2 on num1\n \n int ptr2 = 0;\n \n int cnt = 0;\n \n int largest = INT_MIN;\n \n for(int i=0;i suffixSum[0]:\n return \"Alice\"\n else:\n return \"Bob\"", "solution_js": "var stoneGameIII = function(stoneValue) {\n let len = stoneValue.length-1\n let bestMoves = [0,0,0]\n bestMoves[len%3] = stoneValue[len]\n for(let i = len-1; i >= 0 ; i--){\n let turn = stoneValue[i]\n let option1 = turn - bestMoves[(i+1)%3]\n turn += stoneValue[i+1] ||0\n let option2 = turn - bestMoves[(i+2)%3]\n turn += stoneValue[i+2] || 0\n let option3 = turn - bestMoves[i %3]\n let best = Math.max(option1,option2,option3)\n bestMoves[i%3] = best\n }\n return bestMoves[0] > 0\n ? \"Alice\"\n : bestMoves[0] !== 0\n ? \"Bob\"\n : \"Tie\"\n};", "solution_java": "class Solution {\n\tInteger[] dp;\n\n\tpublic String stoneGameIII(int[] stoneValue) {\n\t\tdp = new Integer[stoneValue.length + 1];\n\t\n\t\t\tArrays.fill(dp, null);\n\t\t\n\t\tint ans = stoneGameIII(0, stoneValue);\n\t\tif (ans == 0)\n\t\t\treturn \"Tie\";\n\t\telse if (ans > 0)\n\t\t\treturn \"Alice\";\n\t\telse\n\t\t\treturn \"Bob\";\n\t}\n\n\tpublic int stoneGameIII(int l, int[] s) {\n\t\tif (l >= s.length)\n\t\t\treturn 0;\n\t\tif (dp[l] != null)\n\t\t\treturn dp[l];\n\t\tint ans;\n\t\t\tans = Integer.MIN_VALUE;\n\t\t\tif (l < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] - stoneGameIII(l + 1, s));\n\t\t\t}\n\t\t\tif (l + 1 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] -stoneGameIII(l + 2, s));\n\t\t\t}\n\t\t\tif (l + 2 < s.length) {\n\t\t\t\tans = Math.max(ans, s[l] + s[l + 1] +s[l + 2] -stoneGameIII(l + 3, s));\n\t\t\t}\n\t\t \n\t\treturn dp[l] = ans;\n\t}\n}", "solution_c": "class Solution {\npublic:\n\n int dp[50001][2][2];\n\n int playGame(vector& stones, bool alice, bool bob, int i) {\n\n if (i >= stones.size()) return 0;\n\n int ans;\n int sum = 0;\n\n if (dp[i][alice][bob] != -1) return dp[i][alice][bob];\n\n if (alice) {\n ans = INT_MIN;\n for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) {\n sum += stones[idx];\n ans = max(ans, sum + playGame(stones, false, true, idx + 1));\n }\n }\n\n if (bob) {\n ans = INT_MAX;\n for (int idx=i; idx < i + 3 && idx < stones.size(); idx++) {\n sum += stones[idx];\n ans = min(ans, playGame(stones, true, false, idx + 1));\n }\n }\n\n return dp[i][alice][bob] = ans;\n }\n\n string stoneGameIII(vector& stoneValue) {\n memset(dp, -1, sizeof dp);\n int totalScore = 0;\n for (auto i : stoneValue) totalScore += i;\n int aliceScore = playGame(stoneValue, true, false, 0);\n if (totalScore - aliceScore > aliceScore)\n return \"Bob\";\n else if (totalScore - aliceScore < aliceScore)\n return \"Alice\";\n else return \"Tie\";\n }\n};" }, { "title": "Largest Odd Number in String", "algo_input": "You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string \"\" if no odd integer exists.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: num = \"52\"\nOutput: \"5\"\nExplanation: The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.\n\n\nExample 2:\n\nInput: num = \"4206\"\nOutput: \"\"\nExplanation: There are no odd numbers in \"4206\".\n\n\nExample 3:\n\nInput: num = \"35427\"\nOutput: \"35427\"\nExplanation: \"35427\" is already an odd number.\n\n\n \nConstraints:\n\n\n\t1 <= num.length <= 105\n\tnum only consists of digits and does not contain any leading zeros.\n\n", "solution_py": "class Solution:\n def largestOddNumber(self, num: str) -> str:\n indx = -1\n n = len(num)\n for i in range(n):\n if int(num[i])%2 == 1:\n indx = i\n \n if indx == -1:\n return \"\"\n return num[:indx+1]", "solution_js": "var largestOddNumber = function(num) {\n for (let i = num.length - 1; i >= 0; i--) {\n\t // +num[i] converts string into number like parseInt(num[i])\n if ((+num[i]) % 2) {\n return num.slice(0, i + 1);\n }\n }\n return '';\n};", "solution_java": "class Solution {\n public String largestOddNumber(String num) {\n for (int i = num.length() - 1; i > -1; i--) {\n if (num.charAt(i) % 2 == 1) return num.substring(0,i+1);\n }\n return \"\";\n }\n}", "solution_c": "class Solution {\npublic:\n string largestOddNumber(string num) {\n // Length of the given string\n int len = num.size();\n // We initialize an empty string for the result\n string res = \"\";\n // We start searching digits from the very right to left because we want to find the first odd digit\n // Which will be the last digit of our biggest odd number\n for (int i = len - 1; i >= 0; i--) {\n // Here we just convert char to an integer in C++\n // We can also do the reverse operation by adding '0' to an int to get char from an int\n int isOdd = num[i] - '0';\n // We check if the current digit is odd, if so this is the position we want to find\n if (isOdd % 2 == 1) {\n // Since we have found the correct spot, let's create our result string\n // We can basically extract the part starting from 0th index to right most odd digit's index\n // Like this:\n // 0123456 -> indices\n // 1246878 -> digits\n // ^....^ -> The part we extracted [0 to 5]\n res = num.substr(0, i + 1); // i+1 is length of substring\n // Because we know this would be the largest substring as we are starting from last\n // We can terminate the loop and return the result\n break;\n }\n }\n return res;\n }\n};" }, { "title": "Number of Submatrices That Sum to Target", "algo_input": "Given a matrix and a target, return the number of non-empty submatrices that sum to target.\n\nA submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.\n\nTwo submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.\n\n \nExample 1:\n\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\n\n\nExample 2:\n\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n\n\nExample 3:\n\nInput: matrix = [[904]], target = 0\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= matrix.length <= 100\n\t1 <= matrix[0].length <= 100\n\t-1000 <= matrix[i] <= 1000\n\t-10^8 <= target <= 10^8\n\n", "solution_py": "class Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n m, n = len(matrix), len(matrix[0])\n matrix_sums = [[0 for _ in range(n)] for _ in range(m)]\n \n # Calculate all the submatrices sum with the transition formula we found\n for row in range(m):\n for col in range(n):\n # first cell\n if row == 0 and col == 0:\n matrix_sums[row][col] = matrix[row][col]\n # Rows and columns are like prefix sums, without intersection\n elif row == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col-1]\n elif col == 0:\n matrix_sums[row][col] = matrix[row][col] + matrix_sums[row-1][col]\n \n # current sum is the sum of the matrix above, to the left and subtract the intersection\n else:\n matrix_sums[row][col] = matrix[row][col] \\\n + (matrix_sums[row][col-1]) \\\n + (matrix_sums[row-1][col]) \\\n - (matrix_sums[row-1][col-1])\n\n \n ans = 0\n # Generate all submatrices\n for y1 in range(m):\n for x1 in range(n):\n for y2 in range(y1, m):\n for x2 in range(x1, n):\n # calculate sum in O(1)\n submatrix_total = matrix_sums[y2][x2] \\\n - (matrix_sums[y2][x1-1] if x1-1 >= 0 else 0) \\\n - (matrix_sums[y1-1][x2] if y1-1 >= 0 else 0) \\\n + (matrix_sums[y1-1][x1-1] if y1-1 >= 0 and x1-1 >= 0 else 0)\n \n if submatrix_total == target:\n ans += 1\n return ans", "solution_js": "var numSubmatrixSumTarget = function(matrix, target) {\n let result = 0;\n \n for (let i = 0; i < matrix.length; i++) {\n for (let j = 1; j < matrix[0].length; j++) {\n matrix[i][j] = matrix[i][j] + matrix[i][j-1]\n }\n }\n \n for (let i = 0; i < matrix[0].length; i++) {\n for (let j = i; j < matrix[0].length; j++) {\n let dict = {};\n let cur = 0;\n dict[0] = 1;\n \n for (let k = 0; k < matrix.length; k++) {\n cur += matrix[k][j] - ((i > 0)?(matrix[k][i - 1]):0);\n result += ((dict[cur - target] == undefined)?0:dict[cur - target]);\n dict[cur] = ((dict[cur] == undefined)?0:dict[cur])+1;\n } \n }\n }\n \n return result;\n};", "solution_java": "class Solution {\npublic int numSubmatrixSumTarget(int[][] matrix, int target) {\n int m = matrix.length, n = matrix[0].length;\n\n int[] summedArray = new int[n];\n int ans = 0;\n for(int i = 0; i < m; i++){ //starting row\n Arrays.fill(summedArray, 0);\n for(int j = i; j < m; j++){ //ending row\n for(int k = 0; k < n; k++){ // column\n summedArray[k] += matrix[j][k];\n }\n ans += subarraySum(summedArray, target);\n }\n }\n return ans;\n}\n\n public int subarraySum(int[] nums, int k) {\n //map\n Map map = new HashMap<>();\n int count = 0;\n map.put(0,1);\n int sum = 0;\n for(int num : nums){\n sum += num;\n int diff = sum - k;\n if(map.containsKey(diff)){\n count += map.get(diff);\n }\n map.put(sum, map.getOrDefault(sum, 0) + 1);\n }\n return count;\n}\n}", "solution_c": "class Solution {\npublic:\n int numSubmatrixSumTarget(vector>& matrix, int target) {\n int n=matrix.size(),m=matrix[0].size(),count=0;\n vector>temp(n+1,vector(m));\n for(int i=0;i List[int]:\n d = {i:[] for i in range(numCourses)}\n \n for crs, prereq in prerequisites:\n d[crs].append(prereq)\n \n visit, cycle = set(), set()\n output = []\n def dfs(crs):\n if crs in cycle:\n return False\n if crs in visit:\n return True\n \n cycle.add(crs)\n for nei in d[crs]:\n if not dfs(nei):\n return False\n cycle.remove(crs)\n visit.add(crs)\n output.append(crs)\n return True\n \n for crs in range(numCourses):\n if not dfs(crs):\n return []\n return output\n ", "solution_js": "/**\n * @param {number} numCourses\n * @param {number[][]} prerequisites\n * @return {number[]}\n */\nvar findOrder = function(numCourses, prerequisites) {\n let visiting = new Set();\n const visited = new Set();\n const adjList = new Map();\n const result = [];\n \n\t// Generate scaffold of adjacency list\n\t// initialized with no prereqs\n for (let i = 0; i < numCourses; i++) {\n adjList.set(i, []);\n }\n \n\t// Fill adjacency list with course prereqs\n\t// Key is the course\n\t// Value is any course prereqs\n for (const item of prerequisites) {\n const [course, prereq] = item;\n adjList.get(course).push(prereq);\n }\n \n const dfs = (node) => {\n\t // We've already traversed down this path before\n\t\t// and determined that it isn't cyclical\n if (visited.has(node)) return true;\n\t\t\n\t\t// Visiting keeps track of what we've seen\n\t\t// during this current traversal and determines\n\t\t// if we have a cycle.\n if (visiting.has(node)) return false;\n \n\t\t// Mark this node as part of the current traversal\n visiting.add(node);\n \n\t\t// Get all adjacent nodes to traverse\n\t\t// traverse them in a loop looking for cycles\n const children = adjList.get(node);\n for (const child of children) {\n if (!dfs(child)) return false;\n }\n\t\t\n\t\t// Ensures we don't re-traverse already traversed nodes since\n\t\t// we've already determined they contain no cycles.\n visited.add(node);\n\t\t\n\t\t// Add this node to the result stack to return at the end\n result.push(node);\n return true;\n }\n \n for (const node of adjList.keys()) {\n if(!dfs(node)) return [];\n }\n \n return result;\n};", "solution_java": "class Solution {\n public int[] findOrder(int numCourses, int[][] prerequisites) {\n Map> graph = new HashMap<>();\n int[] inDegree = new int[numCourses];\n for (int i = 0; i < numCourses; i++) {\n graph.put(i, new HashSet());\n }\n \n for (int[] pair : prerequisites) {\n graph.get(pair[1]).add(pair[0]);\n inDegree[pair[0]]++;\n }\n \n // BFS - Kahn's Algorithm - Topological Sort\n Queue bfsContainer = new LinkedList<>();\n for (int i = 0; i < numCourses; i++) {\n if (inDegree[i] == 0) {\n bfsContainer.add(i); \n }\n }\n \n int count = 0;\n int[] ans = new int[numCourses];\n while (!bfsContainer.isEmpty()) {\n int curr = bfsContainer.poll();\n ans[count++] = curr;\n for (Integer num : graph.get(curr)) {\n inDegree[num]--;\n if (inDegree[num] == 0) {\n bfsContainer.add(num);\n }\n }\n }\n \n if (count < numCourses) {\n return new int[] {};\n } else {\n return ans;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n vector findOrder(int numCourses, vector>& prerequisites) {\n map>adj;\n vector indegree(numCourses,0);\n vectorres;\n for(int i=0;i q;\n for(int i=0;i List[List[int]]:\n\n answer = []\n\n if len(firstList) == 0 or len(secondList) == 0:\n return answer\n\n first_queue= deque(firstList)\n second_queue = deque(secondList )\n\n first = first_queue.popleft()\n second = second_queue.popleft()\n\n while first_queue or second_queue:\n\n if first[1] < second[0]:\n if len(first_queue):\n first = first_queue.popleft()\n continue\n break\n if second[1] < first[0]:\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n answer.append([second[0], first[1]])\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n else:\n answer.append(second)\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n if second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n answer.append([first[0], second[1]])\n if len(second_queue) > 0:\n second = second_queue.popleft()\n continue\n break\n\n else:\n answer.append(first)\n if len(first_queue) > 0:\n first = first_queue.popleft()\n continue\n break\n\n if first[0] <= second[0] and second[0] <= first[1]:\n if first[1] <= second[1]:\n\n if len(answer) > 0:\n\n if answer[-1] != [second[0], first[1]]:\n answer.append([second[0], first[1]])\n elif not answer:\n answer.append([second[0], first[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != second:\n answer.append(second)\n elif not answer:\n answer.append(second)\n elif second[0] <= first[0] and first[0] <= second[1]:\n if second[1] <= first[1]:\n if len(answer) > 0:\n if answer[-1] != [first[0], second[1]]:\n answer.append([first[0], second[1]])\n elif not answer:\n answer.append([first[0], second[1]])\n else:\n if len(answer) > 0:\n if answer[-1] != first:\n answer.append(first)\n elif not answer:\n\n answer.append(first)\n\n return answer", "solution_js": "var intervalIntersection = function(firstList, secondList) {\n //if a overlap b - a.start >= b.start && a.start <= b.end\n //if b overlap a - b.start >= a.start && b.start <= a.end\n\n //handle empty edge cases\n if(firstList.length === 0 || secondList.length === 0){\n return [];\n }\n\n let merged = [];\n let i =0;\n let j = 0;\n while(i= secondList[j][0] && firstList[i][0] <= secondList[j][1];\n let b_overlap_a = secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1];\n\n if(a_overlap_b || b_overlap_a){\n let start = Math.max(firstList[i][0], secondList[j][0]);\n let end = Math.min(firstList[i][1], secondList[j][1]);\n merged.push([start, end]);\n }\n\n if(firstList[i][1] < secondList[j][1]){\n i++;\n }else {\n j++;\n }\n }\n\n return merged;\n\n};", "solution_java": "class Solution {\n public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {\n int i = 0;\n int j = 0;\n \n List ans = new ArrayList<>();\n \n while(i=a[0])\n ans.add(new int[]{b[0], Math.min(a[1], b[1])});\n else if(a[0]<=b[1] && a[0]>=b[0])\n ans.add(new int[]{a[0], Math.min(a[1], b[1])});\n \n if(a[1]<=b[1])\n i++;\n else\n j++;\n }\n \n int res[][] = new int[ans.size()][2];\n \n for(i=0;i> intervalIntersection(vector>& firstList, vector>& secondList) {\n vector> result;\n int i = 0;\n int j = 0;\n while(i < firstList.size() && j < secondList.size()){\n if((firstList[i][0] >= secondList[j][0] && firstList[i][0] <= secondList[j][1])||(secondList[j][0] >= firstList[i][0] && secondList[j][0] <= firstList[i][1]) ){\n //there is an overlap\n result.push_back( {max(firstList[i][0], secondList[j][0]), min(firstList[i][1], secondList[j][1])});\n }\n if(firstList[i][1] < secondList[j][1]){\n i++;\n }\n else{\n j++;\n }\n }\n return result;\n }\n};" }, { "title": "Maximum Product of Splitted Binary Tree", "algo_input": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.\n\nReturn the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.\n\nNote that you need to maximize the answer before taking the mod and not after taking it.\n\n \nExample 1:\n\nInput: root = [1,2,3,4,5,6]\nOutput: 110\nExplanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n\n\nExample 2:\n\nInput: root = [1,null,2,3,4,null,null,5,6]\nOutput: 90\nExplanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 5 * 104].\n\t1 <= Node.val <= 104\n\n", "solution_py": "class Solution:\n def maxProduct(self, root: Optional[TreeNode]) -> int:\n def findTotalSum(node, totalSum):\n if node is None:\n return totalSum\n totalSum = findTotalSum(node.left,totalSum)\n totalSum += node.val\n totalSum = findTotalSum(node.right,totalSum)\n return totalSum\n \n def dfs(node,maxProd,totalSum):\n if node is None:\n return maxProd,0\n if not node.left and not node.right:\n return maxProd,node.val\n maxProd, lSum = dfs(node.left,maxProd,totalSum)\n maxProd, rSum = dfs(node.right,maxProd,totalSum)\n subTreeSum = lSum+rSum+node.val\n maxProd = max(maxProd,(totalSum-lSum)*lSum,(totalSum-rSum)*rSum,(totalSum-subTreeSum)*subTreeSum)\n return maxProd, subTreeSum\n \n totalSum = findTotalSum(root, 0)\n product,_ = dfs(root,1,totalSum)\n return product % (pow(10,9)+7)", "solution_js": "var maxProduct = function(root) {\n const lefteRightSumMap = new Map();\n \n function getLeftRightSumMap(node) {\n if (node === null)\n return 0;\n\n let leftSum = getLeftRightSumMap(node.left);\n let rightSum = getLeftRightSumMap(node.right);\n \n lefteRightSumMap.set(node, {leftSum, rightSum});\n \n return leftSum + rightSum + node.val;\n }\n \n getLeftRightSumMap(root);\n \n let maxProduct = -Infinity;\n\n function getMaxProductDFS(node, parentSum) {\n if (node === null) return;\n \n const {leftSum, rightSum} = lefteRightSumMap.get(node);\n \n // cut left edge\n maxProduct = Math.max(maxProduct, leftSum * (parentSum + node.val + rightSum));\n \n // cut right edge\n maxProduct = Math.max(maxProduct, rightSum * (parentSum + node.val + leftSum));\n\n getMaxProductDFS(node.left, parentSum + node.val + rightSum);\n getMaxProductDFS(node.right, parentSum + node.val + leftSum);\n }\n \n getMaxProductDFS(root, 0);\n \n return maxProduct % (Math.pow(10, 9) + 7);\n};", "solution_java": "class Solution {\n public void findMaxSum(TreeNode node,long sum[]){\n if(node==null) return ;\n\n findMaxSum(node.left,sum);\n findMaxSum(node.right,sum);\n\n sum[0]+=node.val;\n\n }\n\n public long findProd(TreeNode node,long sum[],long []max){\n if(node==null) return 0;\n\n long left=findProd(node.left, sum, max);\n long right=findProd(node.right,sum,max);\n\n long val=left+right+node.val;\n\n max[0]=Math.max(max[0],val*(sum[0]-val));\n\n return val;\n }\n public int maxProduct(TreeNode root) {\n\n long max[]=new long[1];\n long sum[]=new long[1];\n\n findMaxSum(root,sum);\n\n long n= findProd(root,sum,max);\n\n return (int)(max[0]%((int)1e9+7));\n }\n}", "solution_c": "class Solution {\npublic:\n int mod = 1e9+7;\n unordered_map> mp;\n long long int helper(TreeNode* root){\n if(!root)\n return 0;\n long long int ls = 0,rs = 0;\n if(root->left)\n ls = helper(root->left);\n if(root->right)\n rs = helper(root->right);\n mp[root] = {ls,rs};\n return ls+rs+root->val;\n }\n long long int ans = 0;\n void helper2(TreeNode* root,long long int adon){\n if(root == NULL)\n return;\n long long int x = root->val + adon;\n ans = max(ans,max((x+mp[root].first)*mp[root].second,(x+mp[root].second)*mp[root].first));\n helper2(root->left,x+mp[root].second);\n helper2(root->right,x+mp[root].first);\n }\n int maxProduct(TreeNode* root) {\n long long int x = helper(root);\n helper2(root,0);\n return ans%mod;\n }\n};" }, { "title": "Convert Binary Number in a Linked List to Integer", "algo_input": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.\n\nReturn the decimal value of the number in the linked list.\n\nThe most significant bit is at the head of the linked list.\n\n \nExample 1:\n\nInput: head = [1,0,1]\nOutput: 5\nExplanation: (101) in base 2 = (5) in base 10\n\n\nExample 2:\n\nInput: head = [0]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tThe Linked List is not empty.\n\tNumber of nodes will not exceed 30.\n\tEach node's value is either 0 or 1.\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def getDecimalValue(self, head: ListNode) -> int:\n res = 0\n po = 0\n stack = []\n node = head\n while node:\n stack.append(node.val)\n node = node.next\n res = 0\n for i in reversed(stack):\n res += i*(2**po)\n po += 1\n return res", "solution_js": "var getDecimalValue = function(head) {\n let str = \"\"\n while(head){\n str += head.val\n head = head.next\n }\n return parseInt(str,2) //To convert binary into Integer", "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int getDecimalValue(ListNode head) {\n head = reverse(head);\n int ans = 0;\n int pow = 0;\n ListNode temp = head;\n while(temp != null){\n ans = ans + temp.val * (int) Math.pow(2,pow++);\n temp = temp.next;\n }\n\n return ans;\n }\n public ListNode reverse(ListNode head){\n ListNode prev = null;\n ListNode pres = head;\n ListNode Next = pres.next;\n\n while(pres != null){\n pres.next = prev;\n prev = pres;\n pres = Next;\n if(Next != null){\n Next = Next.next;\n }\n }\n\n head = prev;\n return head;\n }\n}", "solution_c": "class Solution {\npublic:\n int getDecimalValue(ListNode* head) {\n ListNode* temp = head;\n int count = 0;\n while(temp->next != NULL){\n count++;\n temp = temp->next;\n }\n temp = head;\n int ans = 0;\n while(count != -1){\n ans += temp->val * pow(2,count);\n count--;\n temp = temp->next;\n }\n return ans;\n }\n};" }, { "title": "Longest Subarray of 1's After Deleting One Element", "algo_input": "Given a binary array nums, you should delete one element from it.\n\nReturn the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.\n\n \nExample 1:\n\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n\n\nExample 2:\n\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n\n\nExample 3:\n\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\tnums[i] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n pre, suf = [1]*n, [1]*n\n if nums[0] == 0:pre[0] = 0\n if nums[-1] == 0:suf[-1] = 0\n \n for i in range(1, n):\n if nums[i] == 1 and nums[i-1] == 1:\n pre[i] = pre[i-1] + 1\n elif nums[i] == 0:\n pre[i] = 0\n \n for i in range(n-2, -1, -1):\n if nums[i] == 1 and nums[i+1] == 1:\n suf[i] = suf[i+1] + 1\n elif nums[i] == 0:\n suf[i] = 0\n \n ans = 0\n for i in range(n):\n if i == 0:\n ans = max(ans, suf[i+1])\n elif i == n-1:\n ans = max(ans, pre[i-1])\n else:\n ans = max(ans, pre[i-1] + suf[i+1])\n \n return ans", "solution_js": "var longestSubarray = function(nums) {\n let l = 0, r = 0;\n let longest = 0;\n // Keep track of the idx where the last zero was seen\n let zeroIdx = null;\n while (r < nums.length) {\n // If we encounter a zero\n if (nums[r] === 0) {\n // If this is the first zero encountered, then set the zeroIdx to the current r index\n if (zeroIdx === null) zeroIdx = r;\n else {\n // If we've already encountered a zero, then set the l index to the zeroIdx + 1,\n\t\t\t\t// effectively removing that zero from the subarray\n l = zeroIdx + 1;\n // Then update the zeroIdx to the current r index\n // This way there will be, at most, one zero in the subarray at all times\n zeroIdx = r;\n }\n }\n longest = Math.max(longest, r - l);\n r++;\n }\n return longest;\n};", "solution_java": "class Solution {\n public int longestSubarray(int[] nums) {\n List groups = new ArrayList<>();\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0)\n groups.add(nums[i]);\n if (nums[i] == 1) {\n int count = 0;\n while (i < nums.length && nums[i] == 1) {\n count++;\n i++;\n }\n groups.add(count);\n if (i < nums.length && nums[i] == 0)\n groups.add(0);\n }\n }\n int max = 0;\n if (groups.size() == 1) {\n return groups.get(0) - 1;\n }\n for (int i = 0; i < groups.size(); i++) {\n if (i < groups.size() - 2) {\n max = Math.max(max, groups.get(i) + groups.get(i+2));\n } else {\n max = Math.max(max, groups.get(i));\n }\n }\n \n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestSubarray(vector& nums) {\n int x=0,y=0,cnt=0;\n for(int i=0;i int:\n dp = [[1]*1001 for i in range(len(nums))]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n d = nums[j] - nums[i] + 500\n dp[j][d] = max(dp[i][d]+1,dp[j][d])\n return max([max(i) for i in dp])", "solution_js": "var longestArithSeqLength = function(nums) {\n if (nums === null || nums.length === 0) {\n return 0;\n }\n let diffMap = new Array(nums.length).fill(0).map(() => new Map());\n let maxLen = 1;\n for (let i = 0; i < nums.length; i++) {\n for (let j = 0; j < i; j++) {\n let diff = nums[i] - nums[j];\n // if prev element has an ongoing arithmetic sequence with the same common difference\n // we simply add 1 to the length of that ongoing sequence, hence diffMap[j].get(diff) + 1\n // else, we start a new arithmetic sequence, initial length is 2\n diffMap[i].set(diff, diffMap[j].get(diff) + 1 || 2);\n maxLen = Math.max(maxLen, diffMap[i].get(diff));\n }\n }\n return maxLen;\n // T.C: O(N^2)\n // S.C: O(N^2)\n};", "solution_java": "class Solution \n{\n public int longestArithSeqLength(int[] nums) \n {\n int n = nums.length;\n int longest = 0;\n Map[] dp = new HashMap[n];\n \n for (int i = 0; i < n; i++) \n {\n dp[i] = new HashMap<>();\n \n for (int j = 0; j < i; j++) \n {\n int diff = nums[i] - nums[j];\n dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1);\n longest = Math.max(longest, dp[i].get(diff));\n }\n }\n \n return longest;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestArithSeqLength(vector& nums) {\n \n int n=size(nums);\n int ans=1;\n vector> dp(n,vector(1005,1));\n \n for(int i=1;i int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)", "solution_js": "/**\n * @param {number[][]} intervals\n * @return {number}\n */\nvar intersectionSizeTwo = function(intervals) {\n const sortedIntervals = intervals.sort(sortEndsThenStarts)\n let currentTail = []\n let answer = 0\n sortedIntervals.forEach(interval => {\n const start = interval[0]\n const end = interval[1]\n const startPoint = currentTail[0]\n const lastPoint = currentTail[1]\n \n if (!currentTail.length || lastPoint < start){\n currentTail = [end -1, end]\n answer += 2\n } else if ( startPoint < start){\n currentTail = [currentTail[1], end]\n answer += 1\n }\n\n })\n return answer\n\n};\n\nfunction sortEndsThenStarts(intervalA, intervalB){\n return intervalA[1] < intervalB[1] ? -1 : 1\n}", "solution_java": "//Time Complexity O(Nlog(N)) - N is the number of intervals\n//Space Complexity O(N) - N is the number of intervals, can be reduced to O(1) if needed\nclass Solution {\n public int intersectionSizeTwo(int[][] intervals) {\n //corner case: can intervals be null or empty? No\n\n //First, sort the intervals by end, then by reverse order start\n Arrays.sort(intervals, new Comparator() {\n @Override\n public int compare(int[] a, int[] b) {\n if (a[1] == b[1]) {\n return b[0] - a[0];\n }\n return a[1] - b[1];\n }\n });\n\n //Second, for each two intervals, greedily find if the previous interval would satisfy next interval's request\n List list = new ArrayList<>(); //basically the ending set S, btw, we actually do not need this but I use it here for better intuition\n\n //add last two nums within the range\n list.add(intervals[0][1] - 1);\n list.add(intervals[0][1]);\n\n for (int i = 1; i < intervals.length; i++) {\n int lastOne = list.get(list.size() - 1);\n int lastTwo = list.get(list.size() - 2);\n\n int[] interval = intervals[i];\n int start = interval[0];\n int end = interval[1];\n\n //if overlaps at least 2\n if (lastOne >= start && lastTwo >= start) {\n continue;\n } else if (lastOne >= start) { //if overlaps 1\n list.add(end);\n } else { //if not overlapping\n list.add(end - 1);\n list.add(end);\n }\n }\n\n return list.size();\n }\n}", "solution_c": "class Solution {\npublic:\n\n // sort wrt. end value\n\n static bool compare(vector& a, vector& b)\n {\n if(a[1] == b[1])\n return a[0] < b[0];\n else\n return a[1] < b[1];\n }\n\n int intersectionSizeTwo(vector>& intervals) {\n\n int n = intervals.size();\n\n // sort the array\n\n sort(intervals.begin(), intervals.end(), compare);\n\n vector res;\n\n res.push_back(intervals[0][1] - 1);\n\n res.push_back(intervals[0][1]);\n\n for(int i = 1; i < n; i++)\n {\n int start = intervals[i][0];\n\n int end = intervals[i][1];\n\n if(start > res.back())\n {\n res.push_back(end - 1);\n\n res.push_back(end);\n }\n else if(start == res.back())\n {\n res.push_back(end);\n }\n else if(start > res[res.size() - 2])\n {\n res.push_back(end);\n }\n }\n\n return res.size();\n }\n};" }, { "title": "Binary Tree Tilt", "algo_input": "Given the root of a binary tree, return the sum of every tree node's tilt.\n\nThe tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.\n\n \nExample 1:\n\nInput: root = [1,2,3]\nOutput: 1\nExplanation: \nTilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1\n\n\nExample 2:\n\nInput: root = [4,2,9,3,5,null,7]\nOutput: 15\nExplanation: \nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\n\n\nExample 3:\n\nInput: root = [21,7,14,1,1,2,2,3,3]\nOutput: 9\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\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 def findTilt(self, root: Optional[TreeNode]) -> int:\n res = [0]\n def tilt_helper(root,res):\n if not root:\n return 0\n\n left = tilt_helper(root.left,res)\n right = tilt_helper(root.right,res)\n\n res[0] += abs(left-right)\n\n return left + right + root.val\n\n tilt_helper(root,res)\n return res[0]", "solution_js": "var findTilt = function(root) {\n function helper(node, acc) {\n if (node === null) {\n return 0;\n }\n\n const left = helper(node.left, acc);\n const right = helper(node.right, acc);\n\n acc.sum += Math.abs(left - right);\n\n return left + node.val + right;\n }\n\n let acc = { sum: 0 };\n helper(root, acc);\n\n return acc.sum;\n};", "solution_java": "class Solution {\n int max = 0;\n public int findTilt(TreeNode root) {\n loop(root);\n return max;\n }\n public int loop(TreeNode root){\n if(root==null) return 0;\n int left = loop(root.left);\n int right = loop(root.right);\n max+= Math.abs(left-right);\n return root.val+left+right;\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 \n /* We will take help of recursion\n Each function call will return the sum of subtree with root as current root\n and the tilt sum will be updated in the variable passed as reference\n */\n \n int getTiltSum(TreeNode* root, int &tiltSum){\n if(root == NULL){\n return 0;\n }\n if(root->left == NULL and root->right == NULL){ // If we have a leaf\n tiltSum+=0; // Add nothing to tilt sum\n return root->val; // return its value as sum\n }\n \n int leftSubTreeSum = getTiltSum(root->left, tiltSum); // Sum of all nodes in left\n int rightSubTreeSum = getTiltSum(root->right, tiltSum); // and right subtrees\n \n tiltSum += abs(leftSubTreeSum - rightSubTreeSum); // Update the tilt sum\n \n // return the sum of left Subtree + right subtree + current node as the sum of the \n return (root->val + leftSubTreeSum + rightSubTreeSum); // subtree with root as current node.\n \n }\n \n \n int findTilt(TreeNode* root) {\n // variable to be passed as refrence and store the result\n int tiltSum = 0;\n \n getTiltSum(root, tiltSum);\n \n return tiltSum;\n }\n};" }, { "title": "Swim in Rising Water", "algo_input": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).\n\nThe rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.\n\nReturn the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).\n\n \nExample 1:\n\nInput: grid = [[0,2],[1,3]]\nOutput: 3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.\n\n\nExample 2:\n\nInput: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\nOutput: 16\nExplanation: The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n\n\n \nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 <= n <= 50\n\t0 <= grid[i][j] < n2\n\tEach value grid[i][j] is unique.\n\n", "solution_py": "class DSU(object):\n def __init__(self, N):\n self.par = list(range(N))\n self.rnk = [0] * N\n\n def find(self, x):\n if self.par[x] != x:\n self.par[x] = self.find(self.par[x])\n return self.par[x]\n\n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n elif self.rnk[xr] < self.rnk[yr]:\n self.par[xr] = yr\n elif self.rnk[xr] > self.rnk[yr]:\n self.par[yr] = xr\n else:\n self.par[yr] = xr\n self.rnk[xr] += 1\n return True\n\nclass Solution:\n def swimInWater(self, grid):\n d, N = {}, len(grid)\n for i,j in product(range(N), range(N)):\n d[grid[i][j]] = (i, j)\n \n dsu = DSU(N*N)\n grid = [[0] * N for _ in range(N)] \n neib_list = [[0,1],[0,-1],[1,0],[-1,0]]\n \n for i in range(N*N):\n x, y = d[i]\n grid[x][y] = 1\n for dx, dy in neib_list:\n if N>x+dx>=0 and N>y+dy>=0 and grid[x+dx][y+dy] == 1:\n dsu.union((x+dx)*N + y + dy, x*N + y)\n \n if dsu.find(0) == dsu.find(N*N-1): return i", "solution_js": "const moves = [[1,0],[0,1],[-1,0],[0,-1]]\n\nvar swimInWater = function(grid) {\n let pq = new MinPriorityQueue(),\n N = grid.length - 1, ans = grid[0][0], i = 0, j = 0\n while (i < N || j < N) {\n for (let [a,b] of moves) {\n let ia = i + a, jb = j + b\n if (ia < 0 || ia > N || jb < 0 || jb > N || grid[ia][jb] > 2500) continue\n pq.enqueue((grid[ia][jb] << 12) + (ia << 6) + jb)\n grid[ia][jb] = 3000\n }\n let next = pq.dequeue().element\n ans = Math.max(ans, next >> 12)\n i = (next >> 6) & ((1 << 6) - 1)\n j = next & ((1 << 6) - 1)\n }\n return ans\n};", "solution_java": "class Solution {\n public int swimInWater(int[][] grid) {\n int len = grid.length;\n Map reverseMap = new HashMap<>();\n for (int i = 0; i < len; i++) {\n for (int j = 0; j < len; j++) {\n reverseMap.put(grid[i][j], new int[] { i, j });\n }\n }\n \n int left = grid[0][0]; // answer cannot be less than value of starting position\n int right = len * len - 1;\n \n int ans = right;\n \n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (canSwim(grid, reverseMap, mid, len)) {\n ans = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n \n return ans;\n }\n \n boolean canSwim(int[][] grid, Map reverseIndex, int ans, int len) {\n int[] x_diff = { 1, -1, 0, 0 };\n int[] y_diff = { 0, 0, 1, -1 };\n \n // BFS\n Queue container = new LinkedList<>();\n container.add(new int[] { 0, 0 });\n \n boolean[][] visited = new boolean[grid.length][grid[0].length];\n visited[0][0] = true;\n \n while (!container.isEmpty()) {\n int[] curr = container.poll();\n int currVal = grid[curr[0]][curr[1]];\n for (int i = 0; i < 4; i++) {\n int newX = curr[0] + x_diff[i];\n int newY = curr[1] + y_diff[i];\n if (isValidCell(grid, newX, newY, ans) && !visited[newX][newY]) {\n if (newX == grid.length-1 && newY == grid[0].length-1) {\n return true;\n }\n visited[newX][newY] = true;\n container.add(new int[] { newX, newY });\n }\n } \n }\n \n return false;\n }\n \n boolean isValidCell(int[][] grid, int x, int y, int ans) {\n\t // check boundary and if grid elevation is greater than evaluated answer\n return !(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] > ans);\n }\n}", "solution_c": "class Solution {\npublic:\n int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};\n bool valid(int x,int y,int n)\n {\n return ((x>=0&&x=0&&y>& grid) {\n int n=grid.size();\n int time[n][n];\n bool vis[n][n];\n for(int i=0;i> q;\n q.push({-time[0][0],0,0});\n while(!q.empty())\n {\n tuple node=q.top();\n q.pop();\n int x=get<1>(node),y=get<2>(node);\n if(vis[x][y])continue;\n vis[x][y]=true;\n for(int i=0;i<4;++i)\n {\n int xc=x+dir[i][0],yc=y+dir[i][1];\n if(!valid(xc,yc,n))continue;\n if(time[x][y]time[x][y])\n {\n time[xc][yc]=time[x][y];\n q.push({-time[xc][yc],xc,yc});\n }\n }\n }\n }\n return time[n-1][n-1];\n }\n};\n// Time: O(N*N+N*NLOG(N*N))\n// Space: O(N*N)" }, { "title": "Unique Substrings in Wraparound String", "algo_input": "We define the string s to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\", so s will look like this:\n\n\n\t\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\".\n\n\nGiven a string p, return the number of unique non-empty substrings of p are present in s.\n\n \nExample 1:\n\nInput: p = \"a\"\nOutput: 1\nExplanation: Only the substring \"a\" of p is in s.\n\n\nExample 2:\n\nInput: p = \"cac\"\nOutput: 2\nExplanation: There are two substrings (\"a\", \"c\") of p in s.\n\n\nExample 3:\n\nInput: p = \"zab\"\nOutput: 6\nExplanation: There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of p in s.\n\n\n \nConstraints:\n\n\n\t1 <= p.length <= 105\n\tp consists of lowercase English letters.\n\n", "solution_py": "def get_next(char):\n x = ord(char)-ord('a')\n x = (x+1)%26\n return chr(ord('a') + x)\nclass Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n i = 0\n n = len(p)\n map_ = collections.defaultdict(int)\n while i total + count);\n};", "solution_java": "// One Pass Counting Solution\n// 1. check cur-prev == 1 or -25 to track the length of longest continuos subtring.\n// 2. counts to track the longest continuos subtring starting with current character.\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int findSubstringInWraproundString(String p) {\n final int N = p.length();\n int res = 0, len = 1;\n int[] counts = new int[26];\n for (int i = 0; i < N; i++) {\n char ch = p.charAt(i);\n if (i > 0 && (ch - p.charAt(i-1) == 1 || ch - p.charAt(i-1) == -25)) {\n len++;\n } else {\n len = 1;\n }\n int idx = ch - 'a';\n counts[idx] = Math.max(counts[idx], len);\n }\n for (int count : counts) {\n res += count;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int findSubstringInWraproundString(string p) {\n unordered_map mp;\n\n // if the characters are not contiguous and also check whether after 'z' I am getting 'a'. If so, reset the streak to 1\n // else streak++\n\n int streak = 0;\n\n for (int i = 0; i < p.size(); i++) {\n\n // contiguous\n if (i and (p[i] - p[i - 1] == 1)) streak++;\n\n // z...a case\n else if (i and (p[i] == 'a' and p[i - 1] == 'z')) streak++;\n\n else streak = 1;\n\n mp[p[i]] = max(mp[p[i]], streak);\n }\n\n // why sum? cuz there might be multiple substrings when the streak's broken for one\n\n int ans = 0;\n for (auto x : mp) {\n ans += x.second;\n }\n\n return ans;\n }\n};" }, { "title": "LRU Cache", "algo_input": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.\n\nImplement the LRUCache class:\n\n\n\tLRUCache(int capacity) Initialize the LRU cache with positive size capacity.\n\tint get(int key) Return the value of the key if the key exists, otherwise return -1.\n\tvoid put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.\n\n\nThe functions get and put must each run in O(1) average time complexity.\n\n \nExample 1:\n\nInput\n[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\nExplanation\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4\n\n\n \nConstraints:\n\n\n\t1 <= capacity <= 3000\n\t0 <= key <= 104\n\t0 <= value <= 105\n\tAt most 2 * 105 calls will be made to get and put.\n\n", "solution_py": "class LRUCache {\n int N;\n list pages;\n unordered_map::iterator>> cache;\npublic:\n LRUCache(int capacity) : N(capacity) {\n \n }\n \n int get(int key) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n pages.push_front(key);\n cache[key].second = pages.begin();\n return cache[key].first;\n }\n \n return -1;\n }\n \n void put(int key, int value) {\n if (cache.find(key) != cache.end()) {\n pages.erase(cache[key].second);\n } else {\n if (pages.size() == N) {\n int lru = pages.back();\n cache.erase(lru);\n pages.pop_back();\n }\n }\n \n pages.push_front(key);\n cache[key] = {value, pages.begin()};\n }\n};", "solution_js": "/**\n * @param {number} capacity\n */\nvar LRUCache = function(capacity) {\n this.capacity = capacity;\n this.cache = new Map();\n};\n\n/** \n * @param {number} key\n * @return {number}\n */\nLRUCache.prototype.get = function(key) {\n if(!this.cache.has(key)){\n return -1\n }\n \n let val = this.cache.get(key);\n this.cache.delete(key);\n this.cache.set(key, val)\n return val\n};\n\n/** \n * @param {number} key \n * @param {number} value\n * @return {void}\n */\nLRUCache.prototype.put = function(key, value) {\n if(this.cache.has(key)){\n this.cache.delete(key);\n }else{\n if(this.cache.size >= this.capacity){\n let [lastElm] = this.cache.keys()\n this.cache.delete(lastElm)\n }\n }\n this.cache.set(key, value)\n \n};\n\n/** \n * Your LRUCache object will be instantiated and called as such:\n * var obj = new LRUCache(capacity)\n * var param_1 = obj.get(key)\n * obj.put(key,value)\n */", "solution_java": "class LRUCache {\n // Declare Node class for Doubly Linked List \n class Node{\n int key,value;// to store key and value \n Node next,prev; // Next and Previous Pointers\n Node(int k, int v){\n key=k;\n value=v;\n }\n }\n Node head=new Node(-1,-1); // Default values \n Node tail=new Node(-1,-1);\n Mapmp; // to store key and Node\n int cap;\n public LRUCache(int capacity) {\n // initializing in constructor\n cap=capacity;\n head.next=tail;\n tail.prev=head;\n mp=new HashMap();\n }\n \n public int get(int key) {\n // if map contains the specific key \n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n del(existing);\n ins(existing);// reinserting to keep key after the head pointer and to update LRU list\n return existing.value;\n }\n //otherwise\n return -1;\n }\n \n public void put(int key, int value) {\n // if map contains the key\n if(mp.containsKey(key)){\n Node existing=mp.get(key);\n // remove from the map and delete from the LRU list\n mp.remove(key);\n del(existing);\n }\n // if map size is equal to spcified capacity of the LRU list\n if(mp.size()==cap){\n // remove from the map and delete from the LRU list\n mp.remove(tail.prev.key);\n del(tail.prev);\n }\n Node newNode = new Node(key,value);\n ins(newNode); \n mp.put(key,head.next); \n }\n public void ins(Node newNode){\n //Insert always after the head of the linkedList\n Node temp=head.next;\n head.next=newNode;\n newNode.prev=head;\n newNode.next=temp;\n temp.prev=newNode;\n }\n public void del(Node newNode){\n //Remove the specified node using previous and next pointers\n Node pr=newNode.prev;\n Node nx=newNode.next;\n pr.next=nx;\n nx.prev=pr;\n \n }\n}", "solution_c": "class LRUCache {\npublic:\n int mx;\n class node{\n public:\n node *prev,*next;\n int key,val;\n node(int k,int v){\n key=k,val=v;\n }\n };\n unordered_map mp;\n node *head=new node(-1,-1);\n node *tail=new node(-1,-1);\n LRUCache(int capacity) {\n mx=capacity;\n mp.reserve(1024);\n mp.max_load_factor(0.25);\n\n head->next=tail;tail->prev=head;\n }\n \n void addnode(node *temp){\n node *temp1=head->next;\n head->next=temp;temp->prev=head;\n temp->next=temp1;temp1->prev=temp;\n }\n \n void deletenode(node *temp){\n node *temp1=temp->prev;\n node *temp2=temp->next;\n temp1->next=temp2;\n temp2->prev=temp1;\n }\n \n int get(int key) {\n if(mp.find(key)!=mp.end()){\n node *temp=mp[key];\n int res=temp->val;\n mp.erase(key);\n deletenode(temp);\n addnode(temp);\n mp[key]=head->next;\n return res;\n }\n return -1;\n }\n \n void put(int key, int value) {\n if(mp.find(key)!=mp.end()){\n node *temp=mp[key];\n mp.erase(key);\n deletenode(temp);\n }\n if(mp.size()==mx){\n mp.erase(tail->prev->key);\n deletenode(tail->prev);\n }\n addnode(new node(key,value));\n mp[key]=head->next;\n }\n};" }, { "title": "Largest Time for Given Digits", "algo_input": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.\n\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\n\nReturn the latest 24-hour time in \"HH:MM\" format. If no valid time can be made, return an empty string.\n\n \nExample 1:\n\nInput: arr = [1,2,3,4]\nOutput: \"23:41\"\nExplanation: The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.\n\n\nExample 2:\n\nInput: arr = [5,5,5,5]\nOutput: \"\"\nExplanation: There are no valid 24-hour times as \"55:55\" is not valid.\n\n\n \nConstraints:\n\n\n\tarr.length == 4\n\t0 <= arr[i] <= 9\n\n", "solution_py": "class Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n res = \"\"\n digit_freq = collections.Counter(arr)\n # first digit\n \n \n if 2 in arr and sum([digit_freq[d] for d in range(6)]) > 2:\n res += \"2\"\n arr.remove(2)\n else:\n for digit in [1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # can't make 24-hour time\n if len(res) == 0:\n return \"\"\n \n # second digit 0-3\n if res == \"2\":\n for digit in [3,2,1,0]:\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n # no 0-3 left in arr\n if len(res) == 1:\n return \"\"\n # second digit 0-9\n else:\n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n res += \":\"\n \n for digit in range(5, -1, -1):\n if digit in arr:\n res += str(digit)\n arr.remove(digit)\n break\n \n if len(res) == 3:\n return \"\"\n \n for digit in range(9,-1,-1):\n if digit in arr:\n res += str(digit)\n return res\n ", "solution_js": "var largestTimeFromDigits = function(arr) {\n let max=-1;\n for(let A=0; A<4; A++){\n for(let B=0; B<4; B++){\n\t\t\tif(B==A){continue};\n for(let C=0; C<4; C++){\n\t\t\t\tif(C==A||C==B||arr[C]>=6){continue};\n for(let D=0; D<4; D++){\n\t\t\t\t\tif(D==A||D==B||D==C){continue};\n let time=arr[A]*1000+arr[B]*100+arr[C]*10+arr[D];\n if(time<2400){max=Math.max(max, time));\n }\n }\n }\n }\n\t// Case1: max<0, which means NOTHING VALID -> return \"\"\n\t// Case2: max isn't 4 digits. i.e.[0,0,0,0] -> padStart to make \"0000\"\n let output=max.toString().padStart(4,0);\n return max<0? \"\": output.substr(0,2)+\":\"+output.substr(2);\n};", "solution_java": "class Solution {\n public String largestTimeFromDigits(int[] arr) {\n int[] count = new int[10];\n for (int num: arr) {\n count[num]++;\n }\n StringBuilder sb = backTrack(count, new StringBuilder());\n if (sb.length() == 4) sb.insert(2, ':');\n return sb.toString();\n \n }\n private StringBuilder backTrack(int[] count, StringBuilder sb) {\n int size = sb.length();\n int start = 0;\n if (size == 0) {\n start = 2;\n }\n if (size == 1) {\n start = sb.charAt(0) == '2' ? 3 : 9;\n }\n if (size == 2) {\n start = 5;\n }\n if (size == 3) {\n start = 9;\n }\n for (int i = start; i >= 0; i--) {\n if (count[i] == 0) continue;\n count[i]--;\n sb.append(i);\n backTrack(count, sb);\n if (sb.length() == 4) {\n return sb;\n }\n else {\n count[Character.getNumericValue(sb.charAt(sb.length() - 1))]++;\n sb.deleteCharAt(sb.length() - 1);\n }\n }\n return sb;\n }\n}", "solution_c": "class Solution {\npublic:\n string largestTimeFromDigits(vector& arr) {\n sort(arr.rbegin(), arr.rend());\n used.resize(4);\n \n string ret = \"\";\n if(!dfs(arr,0,0)) return ret;\n else\n {\n for(int i=0;i<2;i++)\n ret.push_back(ans[i] + '0');\n \n ret.push_back(':');\n \n for(int i=2;i<4;i++)\n ret.push_back(ans[i] + '0');\n }\n return ret;\n }\n \nprivate:\n vector min = {600, 60, 10, 1};\n vector ans;\n vector used;\n bool dfs(const vector& arr, int totalhour,int totalmin)\n {\n if(totalhour >= 24 * 60) return false;\n if(totalmin >= 60) return false;\n if(ans.size() == 4) return true;\n \n for(int i=0;i<4;i++)\n {\n if(used[i]) continue;\n used[i] = 1;\n \n int pos = ans.size();\n if(pos<2) totalhour += arr[i] * min[pos];\n else totalmin += arr[i] * min[pos];\n \n ans.push_back(arr[i]);\n \n if(dfs(arr,totalhour,totalmin)) return true;\n \n if(pos<2) totalhour -= arr[i] * min[pos];\n else totalmin -= arr[i] * min[pos];\n \n ans.pop_back();\n used[i] = 0;\n }\n \n return false;\n }\n};" }, { "title": "Group Anagrams", "algo_input": "Given an array of strings strs, group the anagrams together. You can return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\n \nExample 1:\nInput: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\nOutput: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\nExample 2:\nInput: strs = [\"\"]\nOutput: [[\"\"]]\nExample 3:\nInput: strs = [\"a\"]\nOutput: [[\"a\"]]\n\n \nConstraints:\n\n\n\t1 <= strs.length <= 104\n\t0 <= strs[i].length <= 100\n\tstrs[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n strs_table = {}\n\n for string in strs:\n sorted_string = ''.join(sorted(string))\n\n if sorted_string not in strs_table:\n strs_table[sorted_string] = []\n\n strs_table[sorted_string].append(string)\n\n return list(strs_table.values())", "solution_js": "var groupAnagrams = function(strs) {\n let totalResults = [];\n let grouped = new Map();\n\n for (let i=0; i < strs.length; i++) {\n let results = [];\n let res = strs[i];\n\n let sortedStr = strs[i].split('').sort().join('');\n let value = grouped.get(sortedStr);\n\n if (value !== undefined) {\n grouped.set(sortedStr, [...value, strs[i]]);\n } else {\n grouped.set(sortedStr, [strs[i]]);\n }\n }\n\n for (let [key, value] of grouped) {\n totalResults.push(grouped.get(key));\n }\n\n return totalResults;\n};", "solution_java": "class Solution {\n public List> groupAnagrams(String[] strs) {\n HashMap> hm=new HashMap<>();\n for(String s : strs)\n {\n char ch[]=s.toCharArray();\n Arrays.sort(ch);\n StringBuilder sb=new StringBuilder(\"\");\n for(char c: ch)\n {\n sb.append(c);\n }\n String str=sb.toString();\n if(hm.containsKey(str))\n {\n ArrayList temp=hm.get(str);\n temp.add(s);\n hm.put(str,temp);\n }\n else\n {\n ArrayList temp=new ArrayList<>();\n temp.add(s);\n hm.put(str,temp);\n }\n }\n System.out.println(hm);\n List> res=new ArrayList<>();\n for(ArrayList arr : hm.values())\n {\n res.add(arr);\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> groupAnagrams(vector& strs) {\n\n map> mp;\n for(int i=0;i> ans;\n for(auto it:mp)\n {\n vector flag;\n for(auto each:it.second)\n {\n flag.push_back(strs[each]);\n }\n ans.push_back(flag);\n }\n\n return ans;\n }\n};" }, { "title": "Longest Valid Parentheses", "algo_input": "Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.\n\n \nExample 1:\n\nInput: s = \"(()\"\nOutput: 2\nExplanation: The longest valid parentheses substring is \"()\".\n\n\nExample 2:\n\nInput: s = \")()())\"\nOutput: 4\nExplanation: The longest valid parentheses substring is \"()()\".\n\n\nExample 3:\n\nInput: s = \"\"\nOutput: 0\n\n\n \nConstraints:\n\n\n\t0 <= s.length <= 3 * 104\n\ts[i] is '(', or ')'.\n\n", "solution_py": "class Solution:\n def longestValidParentheses(self, s: str) -> int:\n\n maxi = 0\n stack = [-1]\n\n for i in range(len(s)) :\n if s[i] == \"(\" : stack.append(i)\n else :\n stack.pop()\n if len(stack) == 0 : stack.append(i)\n else : maxi = max(maxi, i - stack[-1])\n\n return maxi", "solution_js": "var longestValidParentheses = function(s) {\n let indexStack=[-1]\n let characterStack=[];\n let maxLength=0;\n for(let i=0;iopen) break;\n if(open==closed) len=Math.max(len,j-i+1);\n\n j++;\n }\n i++;\n }\n return len;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestValidParentheses(string s) {\n int n = s.length(), i = 0, ans = 0, k = 0;\n for(int j = 0; j < n; j++) {\n if(s[j] == '(') k++;\n else if(s[j] == ')') {\n k--;\n if(k == 0)\n ans = max(ans, j - i + 1);\n }\n if(k < 0) {\n k = 0;\n i = j + 1;\n }\n }\n k = 0, i = n - 1;\n for(int j = n - 1; j >= 0; j--) {\n if(s[j] == ')') {\n k++;\n }\n else if(s[j] == '(') {\n k--;\n if(k == 0)\n ans = max(ans, i - j + 1);\n }\n if(k < 0) {\n k = 0;\n i = j - 1;\n }\n }\n return ans;\n }\n};" }, { "title": "Word Search II", "algo_input": "Given an m x n board of characters and a list of strings words, return all words on the board.\n\nEach word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\n\n \nExample 1:\n\nInput: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\nOutput: [\"eat\",\"oath\"]\n\n\nExample 2:\n\nInput: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\nOutput: []\n\n\n \nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 <= m, n <= 12\n\tboard[i][j] is a lowercase English letter.\n\t1 <= words.length <= 3 * 104\n\t1 <= words[i].length <= 10\n\twords[i] consists of lowercase English letters.\n\tAll the strings of words are unique.\n\n", "solution_py": "class Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n solution = set()\n trie = self.make_trie(words)\n visited = set()\n for i in range(len(board)):\n for j in range(len(board[0])):\n self.dfs(i,j,board,trie,visited,\"\",solution)\n return solution\n \n def dfs(self,i,j,board,trie,visited,word,solution):\n if \"*\" in trie:\n if len(trie.keys()) == 0:\n return\n else:\n solution.add(word)\n del trie[\"*\"]\n if (i,j) in visited:\n return\n if (i < 0 or i == len(board) or j < 0 or j == len(board[0])):\n return\n if board[i][j] not in trie:\n return\n if len(trie[board[i][j]]) == 0:\n del trie[board[i][j]]\n return\n visited.add((i,j))\n neighbours = [(i,j-1),(i-1,j),(i,j+1),(i+1,j)]\n for n_x,n_y in neighbours:\n self.dfs(n_x,n_y,board,trie[board[i][j]],visited,word+board[i][j],solution) \n visited.remove((i,j))\n \n def make_trie(self,words):\n trie = {}\n for word in words:\n current = trie\n for char in word:\n if char not in current:\n current[char] = {}\n current = current[char]\n current[\"*\"] = \"*\"\n return trie", "solution_js": "const buildTrie = (words) => {\n const trie = {};\n const addToTrie = (word, index = 0, node = trie) => {\n const char = word[index];\n if(!node[char]) {\n node[char] = {};\n }\n\n if(index === word.length - 1) {\n node[char].word = word;\n return word;\n }\n\n return addToTrie(word, index + 1, node[char]);\n };\n\n words.map((word) => addToTrie(word));\n return trie;\n};\n\nconst dfs = (i, j, board, node, wordsFound = []) => {\n if(i < 0 || i >= board.length) return wordsFound;\n if(j < 0 || j >= board[board.length - 1].length) return wordsFound;\n\n const char = board[i][j];\n if(char === '#') return wordsFound;\n\n if(node[char]) {\n if(node[char].word) {\n wordsFound.push(node[char].word);\n node[char].word = null;\n }\n\n board[i][j] = '#';\n dfs(i + 1, j, board, node[char], wordsFound);\n dfs(i, j + 1, board, node[char], wordsFound);\n dfs(i - 1, j, board, node[char], wordsFound);\n dfs(i, j - 1, board, node[char], wordsFound);\n board[i][j] = char;\n }\n\n return wordsFound;\n};\n\nvar findWords = function(board, words) {\n const m = board.length;\n const n = board[m - 1].length;\n const trie = buildTrie(words);\n\n let result = [];\n for(let i = 0; i < m; i += 1) {\n for(let j = 0; j < n; j += 1) {\n result = result.concat(dfs(i, j, board, trie));\n }\n }\n return result;\n};", "solution_java": "class Solution {\n class TrieNode {\n Map children = new HashMap();\n boolean word = false;\n public TrieNode() {}\n }\n \n int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};\n \n public List findWords(char[][] board, String[] words) {\n Set res = new HashSet<>();\n TrieNode root = new TrieNode();\n int m = board.length;\n int n = board[0].length;\n \n for(String word : words){\n char[] cArr = word.toCharArray();\n TrieNode dummy = root;\n \n for(char c : cArr){\n if(!dummy.children.containsKey(c)){\n dummy.children.put(c, new TrieNode());\n }\n dummy = dummy.children.get(c);\n }\n \n dummy.word = true;\n }\n \n for(int i=0; i(res);\n }\n \n Set dfs(char[][] board, TrieNode root, int i, int j, boolean[][] visited, String word){\n Set res = new HashSet<>();\n \n if(root.word){\n res.add(word);\n root.word = false;\n }\n \n visited[i][j] = true;\n \n for(int[] dir : dirs){\n int newI = i + dir[0];\n int newJ = j + dir[1];\n \n if(newI>=0 && newI=0 && newJ result;\n\n struct Trie {\n Trie *child[26];\n bool isEndOfWord;\n string str;\n\n Trie(){\n isEndOfWord = false;\n str = \"\";\n for(int i=0; i<26; i++)\n child[i] = NULL;\n }\n };\n\n Trie *root = new Trie();\n\n void insert(string &word) {\n\n Trie *curr = root;\n\n for(int i=0; ichild[index])\n curr->child[index] = new Trie();\n\n curr = curr->child[index];\n }\n\n curr->isEndOfWord = true;\n curr->str = word;\n }\n\n void trieSearchDFS(vector>& board, Trie *curr, int i, int j, int row, int col) {\n\n if(i<0 || i>row || j<0 || j>col || board[i][j] == '@')\n return;\n\n //int index = board[i][j]-'a';\n curr = curr->child[board[i][j]-'a'];\n\n if(curr == NULL)\n return;\n\n if(curr->isEndOfWord){\n result.push_back(curr->str);\n curr->isEndOfWord = false;\n }\n\n char ch = board[i][j];\n board[i][j] = '@';\n\n if(i-1>=0)\n trieSearchDFS(board,curr,i-1,j,row,col);\n if(j+1=0)\n trieSearchDFS(board,curr,i,j-1,row,col);\n\n board[i][j] = ch;\n\n }\n\n vector findWords(vector>& board, vector& words) {\n int row = board.size();\n int col = board[0].size();\n\n for(int i=0; i int:\n # Prerequisite:\n # What is prime number. What are they just the starting. \n \n truth = [True]*n # making a list of lenght n. And keep all the values as True.\n if n<2: # as 0 & 1 are not prime numbers. \n return 0\n truth[0], truth[1] = False, False #as we added True in the truth list. So will make false for ) & 1 as they are not prime numbers.\n \n i=2 # As we know 0 & 1 are not prime.\n while i*iprime(n,true);\n for(int i = 2; i*i < n; i++){\n if(prime[i]){\n for(int j = i*i; j < n; j += i){\n prime[j] = false;\n }\n }\n }\n int cnt = 0;\n for(int i = 2; i < n; i++){\n if(prime[i]) cnt++;\n }\n return cnt;\n }\n};" }, { "title": "Decoded String at Index", "algo_input": "You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:\n\n\n\tIf the character read is a letter, that letter is written onto the tape.\n\tIf the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.\n\n\nGiven an integer k, return the kth letter (1-indexed) in the decoded string.\n\n \nExample 1:\n\nInput: s = \"leet2code3\", k = 10\nOutput: \"o\"\nExplanation: The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10th letter in the string is \"o\".\n\n\nExample 2:\n\nInput: s = \"ha22\", k = 5\nOutput: \"h\"\nExplanation: The decoded string is \"hahahaha\".\nThe 5th letter is \"h\".\n\n\nExample 3:\n\nInput: s = \"a2345678999999999999999\", k = 1\nOutput: \"a\"\nExplanation: The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1st letter is \"a\".\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 100\n\ts consists of lowercase English letters and digits 2 through 9.\n\ts starts with a letter.\n\t1 <= k <= 109\n\tIt is guaranteed that k is less than or equal to the length of the decoded string.\n\tThe decoded string is guaranteed to have less than 263 letters.\n\n", "solution_py": "class Solution:\n def decodeAtIndex(self, S: str, K: int) -> str:\n idx = {}\n acclens = [0]\n prevd = 1\n j = 0\n for i, c in enumerate(S + '1'):\n if c.isalpha():\n idx[acclens[-1] * prevd + j] = i\n j += 1\n else:\n acclens.append(acclens[-1] * prevd + j)\n prevd = int(c)\n j = 0\n k = K - 1\n for al in reversed(acclens[1:]):\n k %= al\n if k in idx:\n return S[idx[k]]\n return None # should never reach this", "solution_js": "var decodeAtIndex = function(s, k) {\n let len=0;\n let isDigit=false\n\n for(let v of s){\n if(v>='0'&&v<='9'){\n len*=+v\n isDigit=true\n }else{\n len++\n if(len===k&&!isDigit){\n return s[k-1]\n }\n }\n }\n\n for(let i=s.length-1;i>=0;i--){\n const v=s[i]\n if(v>='0'&&v<='9'){\n len=Math.ceil(len/+v) // Math.floor() wont work because we endup leaving few strings\n k%=len\n }else{\n if(k===0||k===len){\n return v\n }\n len--\n }\n }\n};", "solution_java": "class Solution {\n public String decodeAtIndex(String s, int k) {\n long sz = 0;\n for (char ch : s.toCharArray()){ // total length\n sz = Character.isDigit(ch)? sz * (ch - '0') : ++sz;\n }\n --k; // make it 0 index based.\n for (int i = s.length() - 1; true; i--){\n if (Character.isLetter(s.charAt(i)) && --sz == k){ // found!\n return \"\"+s.charAt(i);\n }else if(Character.isDigit(s.charAt(i))){\n sz /= (s.charAt(i) - '0');\n k %= sz; // we are at the end of a multplied string, we can mod k with sz.\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n string decodeAtIndex(string s, int k) {\n k--;\n struct op { string s; size_t mult; size_t total; };\n vector v;\n size_t total = 0;\n for (auto c : s) {\n if (isalpha(c)) {\n if (v.empty() || v.back().mult > 1)\n v.push_back({\"\", 1, total});\n v.back().s += c;\n v.back().total = ++total;\n } else {\n size_t m = c-'0';\n v.back().mult *= m;\n v.back().total = total *= m;\n }\n if (total > k) break;\n }\n while (!v.empty()) {\n auto [s, mult, total] = v.back();\n v.pop_back();\n size_t part = total / mult;\n k %= part;\n if (size_t i = k-part+s.size(); i < s.size())\n return {s[i]};\n }\n return \"#\";\n }\n};" }, { "title": "Compare Strings by Frequency of the Smallest Character", "algo_input": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.\n\nYou are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.\n\nReturn an integer array answer, where each answer[i] is the answer to the ith query.\n\n \nExample 1:\n\nInput: queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput: [1]\nExplanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").\n\n\nExample 2:\n\nInput: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: [1,2]\nExplanation: On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").\n\n\n \nConstraints:\n\n\n\t1 <= queries.length <= 2000\n\t1 <= words.length <= 2000\n\t1 <= queries[i].length, words[i].length <= 10\n\tqueries[i][j], words[i][j] consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n def _f(s):\n d = Counter(s)\n d =dict(sorted(d.items(), key=lambda item: item[0]))\n for x in d:\n return d[x]\n \n freq = []\n for w in words:\n n1 = _f(w)\n freq.append(n1)\n \n freq.sort(reverse=True)\n\n res = []\n for q in queries:\n n = _f(q)\n c=0\n for n1 in freq:\n if n < n1:\n c+=1\n else:\n break\n res.append(c)\n \n return res", "solution_js": "/**\n * @param {string[]} queries\n * @param {string[]} words\n * @return {number[]}\n */\nvar numSmallerByFrequency = function(queries, words) {\n let res=[]\n queries=queries.map(q=>countFrequency(q))//[3,2]\n words=words.map(w=>countFrequency(w))//[1,2,3,4]\n words = words.sort((a, b) => a - b)\n for(let i=0;i{\n freq[key]=(freq[key]||0)+1\n })\n return freq[Object.keys(freq).sort()[0]]\n}", "solution_java": "class Solution {\n public int[] numSmallerByFrequency(String[] queries, String[] words) {\n int[] ans = new int[queries.length];\n int[] freq = new int[words.length];\n for (int i = 0; i < words.length; i++) {\n freq[i] = freqOfSmallest(words[i]);\n }\n Arrays.sort(freq);\n int k = 0;\n for (String query : queries) {\n int target = freqOfSmallest(query);\n ans[k++] = binarySearch(freq, target);\n }\n return ans;\n }\n public int freqOfSmallest(String s) {\n int[] freq = new int[26];\n char min = 'z';\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n freq[c - 'a'] += 1;\n if (c < min) {\n min = c;\n }\n }\n return freq[min - 'a'];\n }\n public int binarySearch(int[] arr, int target) {\n int idx = arr.length;\n int lo = 0;\n int hi = idx - 1;\n int mid;\n while (lo <= hi) {\n mid = (lo + hi) / 2;\n if (arr[mid] <= target) {\n lo = mid + 1;\n } else {\n idx = mid;\n hi = mid - 1;\n }\n }\n return arr.length - idx;\n }\n}", "solution_c": "class Solution {\nprivate:\n int countFreq(const string &s) {\n char c = *min_element(begin(s), end(s));\n return count(begin(s), end(s), c);\n }\npublic:\n vector numSmallerByFrequency(vector& queries, vector& words) {\n vector freqs(11, 0);\n for (const auto &word : words) {\n freqs[countFreq(word)]++;\n }\n vector prefSum(12, 0);\n for (int i = 0; i < freqs.size(); i++) {\n prefSum[i+1] = prefSum[i] + freqs[i];\n }\n vector ans;\n for (const auto &q : queries) {\n int cnt = countFreq(q);\n ans.push_back(prefSum.back() - prefSum[cnt + 1]);\n }\n return ans;\n }\n};" }, { "title": "Sum of Absolute Differences in a Sorted Array", "algo_input": "You are given an integer array nums sorted in non-decreasing order.\n\nBuild and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.\n\nIn other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).\n\n \nExample 1:\n\nInput: nums = [2,3,5]\nOutput: [4,3,5]\nExplanation: Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\n\n\nExample 2:\n\nInput: nums = [1,4,6,8,10]\nOutput: [24,15,13,15,21]\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t1 <= nums[i] <= nums[i + 1] <= 104\n\n", "solution_py": "from itertools import accumulate \n\nclass Solution(object):\n def getSumAbsoluteDifferences(self, nums):\n total, n = sum(nums), len(nums) #for i, ri in zip(nums, reversed(nums)): pref.append(pref[-1] + i)\n return [(((i+1) * num) - pref) + ((total-pref) - ((n-i-1) * num)) for (i, num), pref in zip(enumerate(nums), list(accumulate(nums)))]\n ", "solution_js": "var getSumAbsoluteDifferences = function(nums) {\n const N = nums.length;\n const ans = new Array(N);\n ans[0] = nums.reduce((a, b) => a + b, 0) - (N * nums[0]);\n for (let i = 1; i < N; i++)\n ans[i] = ans[i - 1] + (nums[i] - nums[i - 1]) * i - (nums[i] - nums[i - 1]) * (N - i); \n return ans;\n};", "solution_java": "class Solution {\n public int[] getSumAbsoluteDifferences(int[] nums) {\n int n = nums.length;\n int[] res = new int[n];\n int sumBelow = 0;\n int sumTotal = Arrays.stream(nums).sum();\n\n for (int i = 0; i < n; i++) {\n int num = nums[i];\n sumTotal -= num;\n res[i] = sumTotal - (n - i - 1) * num + i * num - sumBelow;\n sumBelow += num;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector getSumAbsoluteDifferences(vector& nums) {\n vectorans(nums.size(),0);\n for(int i = 1;i int:\n n = len(arr)\n if n ==1:\n return arr[0]\n dpLeft = [-10**4-1 for _ in range(n)]\n dpLeft[0] = arr[0]\n i = 1 \n while i < n :\n dpLeft[i] = max(arr[i],dpLeft[i-1]+arr[i])\n i += 1\n dpRight = [-10**4-1 for _ in range(n)]\n dpRight[-1] = arr[-1]\n j = n-2 \n while j >= 0:\n dpRight[j] = max(arr[j],dpRight[j+1]+arr[j])\n j -= 1\n k = 0\n maxi = -10**4-1\n while k < n:\n # if we take it \n curr_maxi_with = dpRight[k] + dpLeft[k] - arr[k]\n \n if k==0:\n curr_maxi_without = dpRight[k+1]\n elif k==n-1:\n curr_maxi_without = dpLeft[k-1]\n else:\n if dpLeft[k-1]>=0 and dpRight[k+1]>=0:\n curr_maxi_without = dpRight[k+1] + dpLeft[k-1]\n else:\n curr_maxi_without = max(dpLeft[k-1],dpRight[k+1])\n \n maxi= max(maxi,curr_maxi_without, curr_maxi_with)\n k += 1\n \n return maxi ", "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\n \n\n// var maximumSum = function(arr) {\n// const len = arr.length;\n// const dp = new Array(len).fill(() => [null, null]);\n// dp[0][0] = arr[0];\n// dp[0][1] = 0;\n// let result = arr[0];\n// for(let i = 1; i < len; i++) {\n// dp[i][1] = Math.max(dp[i-1][1] + arr[i], dp[i-1][0]);\n// dp[i][0] = Math.max(dp[i-1][0] + arr[i], arr[i]);\n// result = Math.max(result, Math.max(dp[i][0], dp[i][1])); \n// }\n \n// return result;\n// };\n\n// optimization\nvar maximumSum = function(arr) {\n let noDelete = arr[0], oneDelete = 0, max = arr[0];\n for(let i = 1; i < arr.length; i++) {\n oneDelete = Math.max(oneDelete + arr[i], noDelete);\n noDelete = Math.max(noDelete + arr[i], arr[i]);\n max = Math.max(max, Math.max(noDelete, oneDelete));\n }\n return max;\n};", "solution_java": "class Solution {\n public int maximumSum(int[] arr) {\n int n = arr.length;\n int[] prefixSum = new int[n+1];\n prefixSum[0] = 0;\n int ans = (int)-1e9;\n for(int i = 1; i <= n; i++){\n prefixSum[i] = prefixSum[i-1] + arr[i-1];\n ans = Math.max(ans, arr[i-1]);\n }\n if(ans < 0) return ans; \n for(int i = 1; i <= n; i++){\n if(arr[i-1] < 0){\n int leftPrefixSum = 0;\n // find max in i to 0\n for(int j = i-1; j >= 0; j--){\n leftPrefixSum = Math.max(leftPrefixSum, prefixSum[i-1] -prefixSum[j]);\n }\n \n int rightPrefixSum = 0;\n // find max in i to n\n for(int j = i+1; j <= n; j++){\n rightPrefixSum = Math.max(rightPrefixSum, prefixSum[j] -prefixSum[i]);\n } \n ans = Math.max(ans, leftPrefixSum + rightPrefixSum);\n }\n }\n return Math.max(ans, prefixSum[n]);\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumSum(vector& arr) {\n int n = arr.size(), curr, maxi = INT_MIN;\n vector fw(n + 1, 0), bw(n + 1, 0);\n fw[0] = arr[0];\n maxi = max(maxi, fw[0]);\n \n\t\t// ith element denotes the maximum subarray sum with ith element as the last element\n for(int i = 1; i < n; ++i) {\n curr = max(arr[i], fw[i - 1] + arr[i]);\n maxi = max(maxi, curr);\n fw[i] = curr;\n }\n \n\t\t// similar to fw array, but in the backward direction\n bw[n - 1] = curr = arr[n - 1];\n for(int i = n - 2; i >= 0; --i) {\n curr = max(arr[i], bw[i + 1] + arr[i]);\n maxi = max(maxi, curr);\n bw[i] = curr;\n }\n \n int res = INT_MIN;\n for(int i = 1; i < n - 1; ++i) {\n res = max(res, fw[i - 1] + bw[i + 1]);\n }\n return max(res, maxi);\n }\n};" }, { "title": "Maximum Employees to Be Invited to a Meeting", "algo_input": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.\n\nThe employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.\n\nGiven a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.\n\n \nExample 1:\n\nInput: favorite = [2,2,1,2]\nOutput: 3\nExplanation:\nThe above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3. \n\n\nExample 2:\n\nInput: favorite = [1,2,0]\nOutput: 3\nExplanation: \nEach employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.\n\n\nExample 3:\n\nInput: favorite = [3,0,1,4,1]\nOutput: 4\nExplanation:\nThe above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.\n\n\n \nConstraints:\n\n\n\tn == favorite.length\n\t2 <= n <= 105\n\t0 <= favorite[i] <= n - 1\n\tfavorite[i] != i\n\n", "solution_py": "class Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n visited_time = [0] * n\n inpath = [False] * n\n cur_time = 1\n def get_max_len_cycle(cur) :\n nonlocal cur_time\n inpath[cur], visited_time[cur], nxt = True, cur_time, favorite[cur]\n cur_time += 1\n ret = 0 if not inpath[nxt] else visited_time[cur] - visited_time[nxt] + 1\n if visited_time[nxt] == 0 : ret = max(ret, get_max_len_cycle(nxt))\n inpath[cur] = False\n return ret\n \n ret_cycle = 0\n for i in range(n) :\n if visited_time[i] == 0 :\n ret_cycle = max(ret_cycle, get_max_len_cycle(i))\n \n ret_not_cycle = 0\n back_edge_graph = [[] for _ in range(n)]\n for i in range(n) : back_edge_graph[favorite[i]].append(i)\n def get_max_depth(cur) :\n ret = 0\n for nxt in back_edge_graph[cur] :\n if favorite[cur] != nxt :\n ret = max(ret, get_max_depth(nxt) + 1)\n return ret\n \n for i in range(n) :\n if favorite[favorite[i]] == i : ret_not_cycle += get_max_depth(i) + 1\n \n ret = max(ret_cycle, ret_not_cycle)\n return ret", "solution_js": "/**\n * @param {number[]} favorite\n * @return {number}\n */\nvar maximumInvitations = function(favorite) {\n let res = 0;\n let len = favorite.length;\n // count the number indegree\n let indegree = new Array(len).fill(0);\n // save the number relation\n let rMap = new Map();\n for(let i=0; i 0){\n let tmp = [];\n for(let i=0; i 0){\n let tmp = [];\n for(let i=0; i 0){\n for(let i=0; i 0){\n res.push(i);\n }\n }\n return res;\n}", "solution_java": "class Solution {\n public int maximumInvitations(int[] favorite) {\n List> graph = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n graph.add(new ArrayList<>());\n }\n\n int answer = 0;\n\n List> pairs = new ArrayList<>();\n for (int i = 0; i < favorite.length; i++) {\n if (i == favorite[favorite[i]]) {\n if (i < favorite[i]) {\n List pair = new ArrayList<>();\n pair.add(i);\n pair.add(favorite[i]);\n pairs.add(pair);\n }\n } else {\n graph.get(favorite[i]).add(i);\n }\n }\n\n boolean[] visited = new boolean[favorite.length];\n for (List pair: pairs) {\n answer += dfs(graph, pair.get(0), visited) + dfs(graph, pair.get(1), visited);\n }\n\n int[] counter = new int[favorite.length];\n int[] round = new int[favorite.length];\n\n int rnd = 1;\n\n int circleMax = 0;\n\n for (int i = 0; i < favorite.length; i++) {\n if (visited[i]) {\n continue;\n }\n if (round[i] != 0) {\n continue;\n }\n\n int cnt = 1;\n int j = i;\n while (counter[j] == 0) {\n counter[j] = cnt;\n round[j] = rnd;\n j = favorite[j];\n cnt++;\n }\n if (round[j] == rnd) {\n circleMax = Math.max(circleMax, cnt - counter[j]);\n }\n rnd++;\n }\n return Math.max(circleMax, answer);\n }\n\n private int dfs(List> graph, int node, boolean[] visited) {\n visited[node] = true;\n int max = 0;\n for (int neighbor: graph.get(node)) {\n max = Math.max(max, dfs(graph, neighbor, visited));\n }\n return max + 1;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> rev;\n vector es, sizeOfTwo;\n int N, ans1, ans2;\n void dfs(vector& depth, int cur, int d) {\n if (depth[cur] > 0) {\n if (d - depth[cur] == 2) sizeOfTwo.push_back(cur);\n ans1 = max(ans1, d - depth[cur]);\n return;\n }\n if (depth[cur] != -1) return;\n depth[cur] = d;\n dfs(depth, es[cur], d+1);\n depth[cur] = 0; // 0 means visited\n }\n void findAllCircules() {\n vector depth(N, -1);\n for (int i=0; i& favorite) {\n es = favorite;\n N = es.size(), ans1 = 0, ans2 = 0;\n rev.resize(N);\n for (int i=0; i int:\n ans = float('inf')\n fair = [0]*k\n def rec(i):\n nonlocal ans,fair\n if i == len(cookies):\n ans = min(ans,max(fair))\n return\n\t\t\t# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution\n\t\t\tif ans <= max(fair):\n return\n for j in range(k):\n fair[j] += cookies[i]\n rec(i+1)\n fair[j] -= cookies[i]\n rec(0)\n return ans", "solution_js": "var distributeCookies = function(cookies, k) {\n cookies.sort((a, b) => b - a);\n if(k === cookies.length) return cookies[0];\n \n const arr = new Array(k).fill(0);\n let res = Infinity;\n \n function helper(arr, cookies, level) {\n if(level === cookies.length) {\n const max = Math.max(...arr);\n res = Math.min(res, max);\n return;\n }\n const cookie = cookies[level];\n for(let i = 0; i < arr.length; i++) {\n arr[i] += cookie;\n helper(arr, cookies, level + 1);\n arr[i] -= cookie;\n }\n }\n \n helper(arr, cookies, 0);\n \n return res;\n};", "solution_java": "class Solution {\n int ans;\n int count[];\n public int distributeCookies(int[] cookies, int k) {\n ans= Integer.MAX_VALUE;\n count= new int[k];\n\n backtrack(0,cookies, k);\n return ans;\n }\n public void backtrack(int cookieNumber, int[] cookies, int k)\n {\n if(cookieNumber==cookies.length)\n {\n int max= 0;\n for(int i=0; i& nums, vector& v, int k){\n if(start==nums.size()){\n int maxm = INT_MIN;\n for(int i=0;i& nums, int k) { // nums is the cookies vector\n int n = nums.size();\n vector v(k,0); // v is to store each sum of the k subsets\n solve(0,nums,v,k);\n return ans;\n }\n};" }, { "title": "K-th Symbol in Grammar", "algo_input": "We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.\n\n\n\tFor example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.\n\n\nGiven two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.\n\n \nExample 1:\n\nInput: n = 1, k = 1\nOutput: 0\nExplanation: row 1: 0\n\n\nExample 2:\n\nInput: n = 2, k = 1\nOutput: 0\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\nExample 3:\n\nInput: n = 2, k = 2\nOutput: 1\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\n \nConstraints:\n\n\n\t1 <= n <= 30\n\t1 <= k <= 2n - 1\n\n", "solution_py": "class Solution:\n def solve(self,n,k):\n if n==1 and k==1:\n return 0 \n mid = pow(2,n-1)//2 \n if k<=mid:\n return self.solve(n-1,k) \n \n return not self.solve(n-1,k-mid)\n \n \n def kthGrammar(self,n,k):\n if self.solve(n,k):\n return 1 \n else:\n return 0 \n \n \n \n \n \n \n \n \n \n ", "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar kthGrammar = function(n, k) {\n if (n == 1 && k == 1) {\n return 0;\n }\n\n const mid = Math.pow(2, n-1) / 2;\n\n if (k <= mid) {\n return kthGrammar(n-1, k);\n } else {\n return kthGrammar(n-1, k-mid) == 1 ? 0 : 1;\n }\n};", "solution_java": "class Solution {\n public int kthGrammar(int n, int k) {\n if (n == 1 || k == 1) {\n return 0;\n }\n int length = (int) Math.pow(2, n - 1);\n int mid = length / 2;\n if (k <= mid) {\n return kthGrammar(n - 1, k);\n } else if (k > mid + 1) {\n return invert(kthGrammar(n - 1, k - mid));\n } else {\n return 1;\n }\n }\n static int invert(int x) {\n if (x == 0) {\n return 1;\n }\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n int kthGrammar(int n, int k) {\n int kthNode = pow(2, (n-1)) + (k - 1);\n vectorarr;\n while(kthNode) {\n arr.push_back(kthNode);\n kthNode /= 2;\n }\n arr[arr.size() - 1] = 0;\n for (int i = arr.size() - 2; i >= 0; i--) {\n if (arr[i] % 2 == 0) {\n arr[i] = arr[i+1];\n }\n else {\n arr[i] = 1 ^ arr[i+1];\n }\n }\n return arr[0];\n }\n};" }, { "title": "Dota2 Senate", "algo_input": "In the world of Dota2, there are two parties: the Radiant and the Dire.\n\nThe Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:\n\n\n\tBan one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.\n\tAnnounce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.\n\n\nGiven a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.\n\nThe round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.\n\nSuppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\".\n\n \nExample 1:\n\nInput: senate = \"RD\"\nOutput: \"Radiant\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\nExample 2:\n\nInput: senate = \"RDD\"\nOutput: \"Dire\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\n \nConstraints:\n\n\n\tn == senate.length\n\t1 <= n <= 104\n\tsenate[i] is either 'R' or 'D'.\n\n", "solution_py": "class Solution:\n def predictPartyVictory(self, senate: str) -> str:\n nxt = \"\"\n ar, de = senate.count('R'), senate.count('D')\n r , d = 0, 0\n while(ar and de) :\n for i in senate :\n if (i== 'R' and d == 0):\n r += 1\n nxt = nxt + 'R'\n elif (i== 'R' and d > 0):\n d -= 1\n elif (i== 'D' and r > 0):\n r -= 1\n elif(i== 'D' and r == 0):\n d += 1\n nxt = nxt + 'D'\n senate = nxt\n nxt = \"\"\n ar, de = senate.count('R'), senate.count('D')\n if (ar) :\n return 'Radiant'\n else:\n return 'Dire'", "solution_js": "var predictPartyVictory = function(senate) {\n let index = 0, RCount = 0, DCount = 0, deletion = false, delCount = 1;\n while(delCount || index < senate.length) {\n if(index >= senate.length) {\n index = 0;\n delCount = 0;\n }\n deletion = false;\n if(senate.charAt(index) == 'R') {\n if(DCount > 0) {\n senate = senate.slice(0,index)+senate.slice(index+1);\n DCount--;\n index--;\n deletion = true;\n delCount++;\n }\n else {\n RCount++;\n }\n }\n else if(senate.charAt(index) == 'D') {\n if(RCount > 0) {\n senate = senate.slice(0,index)+senate.slice(index+1);\n RCount--;\n index--;\n deletion = true;\n delCount++;\n }\n else {\n DCount++;\n }\n }\n if(index == senate.length-1) {\n if(senate.charAt(0) == 'R' && senate.charAt(index) == 'D' && DCount > 0 && !deletion) {\n senate = senate.slice(1);\n DCount--;\n index = -1;\n }\n else if(senate.charAt(0) == 'D' && senate.charAt(index) == 'R' && RCount > 0 && !deletion) {\n senate = senate.slice(1);\n RCount--;\n index = -1;\n } \n }\n index++;\n }\n return senate.charAt(0) == 'D' ? 'Dire' : 'Radiant';\n};", "solution_java": "// Two Queues Solution\n// Two queues to store the R index and D index.\n// If the senate can execute his right, the senate is alive and can execute in the next round.\n// Then we can add the senate back to the queue and process in the next round (idx + N).\n// Time complexity: O(N), each loop we add/remove 1 senate in the queue.\n// Space complexity: O(N)\nclass Solution {\n public String predictPartyVictory(String senate) {\n if (senate == null || senate.length() == 0) throw new IllegalArgumentException(\"Invalid input.\");\n final int N = senate.length();\n Queue queR = new ArrayDeque<>(); // store the R index\n Queue queD = new ArrayDeque<>(); // store the D index\n for (int i = 0; i < N; i++) {\n if (senate.charAt(i) == 'R') {\n queR.add(i);\n } else {\n queD.add(i);\n }\n }\n while (!queR.isEmpty() && !queD.isEmpty()) {\n int r = queR.poll();\n int d = queD.poll();\n if (r < d) { // R is alive in the next round.\n queR.add(r + N);\n } else { // D is alive in the next round.\n queD.add(d + N);\n }\n }\n return queR.isEmpty() ? \"Dire\" : \"Radiant\";\n }\n}", "solution_c": "class Solution {\npublic:\n string predictPartyVictory(string senate) {\n queue D, R;\n int len = senate.size();\n for (int i = 0; i < len; i++) {\n if (senate[i] == 'D') {\n D.push(i);\n }\n else {\n R.push(i);\n }\n }\n\n while (!D.empty() && !R.empty()) {\n int dIdx = D.front();\n D.pop();\n\n int rIdx = R.front();\n R.pop();\n\n if (dIdx < rIdx) {\n D.push(dIdx + len);\n }\n else {\n R.push(rIdx + len);\n }\n }\n\n return D.empty() ? \"Radiant\" : \"Dire\";\n }\n};" }, { "title": "Find the Difference", "algo_input": "You are given two strings s and t.\n\nString t is generated by random shuffling string s and then add one more letter at a random position.\n\nReturn the letter that was added to t.\n\n \nExample 1:\n\nInput: s = \"abcd\", t = \"abcde\"\nOutput: \"e\"\nExplanation: 'e' is the letter that was added.\n\n\nExample 2:\n\nInput: s = \"\", t = \"y\"\nOutput: \"y\"\n\n\n \nConstraints:\n\n\n\t0 <= s.length <= 1000\n\tt.length == s.length + 1\n\ts and t consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n c = 0\n for cs in s: c ^= ord(cs) #ord is ASCII value\n for ct in t: c ^= ord(ct)\n return chr(c) #chr = convert ASCII into character", "solution_js": "var findTheDifference = function(s, t) {\n var map = {};\n var re = \"\";\n for(let i = 0; i < t.length; i++){\n if(t[i] in map){\n map[t[i]] += 1;\n }else{\n map[t[i]] = 1;\n }\n }\n\n for(let i = 0; i < s.length; i++){\n if(s[i] in map){\n map[s[i]] -= 1;\n }\n }\n\n for(let [key, value] of Object.entries(map)){\n if(value > 0){\n let temp = re.concat(key);\n re = temp;\n }\n }\n return re;\n};", "solution_java": "class Solution {\n public char findTheDifference(String s, String t) {\n char c = 0;\n for(char cs : s.toCharArray()) c ^= cs;\n for(char ct : t.toCharArray()) c ^= ct;\n return c;\n }\n}", "solution_c": "class Solution {\npublic:\n char findTheDifference(string s, string t) {\n char c = 0;\n for(char cs : s) c ^= cs;\n for(char ct : t) c ^= ct;\n return c;\n }\n};" }, { "title": "Maximum Score From Removing Substrings", "algo_input": "You are given a string s and two integers x and y. You can perform two types of operations any number of times.\n\n\n\tRemove substring \"ab\" and gain x points.\n\n\t\n\t\tFor example, when removing \"ab\" from \"cabxbae\" it becomes \"cxbae\".\n\t\n\t\n\tRemove substring \"ba\" and gain y points.\n\t\n\t\tFor example, when removing \"ba\" from \"cabxbae\" it becomes \"cabxe\".\n\t\n\t\n\n\nReturn the maximum points you can gain after applying the above operations on s.\n\n \nExample 1:\n\nInput: s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput: 19\nExplanation:\n- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.\n\nExample 2:\n\nInput: s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput: 20\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\t1 <= x, y <= 104\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n a = 'a'\n b = 'b'\n if x < y:\n x, y = y, x\n a, b = b, a\n seen = Counter()\n ans = 0\n for c in s + 'x':\n if c in 'ab':\n if c == b and 0 < seen[a]:\n ans += x\n seen[a] -= 1\n else:\n seen[c] += 1\n else:\n ans += y * min(seen[a], seen[b])\n seen = Counter()\n\n return ans", "solution_js": "var maximumGain = function(s, x, y) {\n const n = s.length;\n \n let totPoints = 0;\n let stack;\n \n if (x > y) {\n stack = remove(s, x, \"ab\");\n s = stack.join(\"\");\n remove(s, y, \"ba\");\n \n }\n else {\n stack = remove(s, y, \"ba\");\n s = stack.join(\"\");\n remove(s, x, \"ab\");\n }\n \n return totPoints;\n \n \n function remove(str, points, match) {\n const stack = [];\n \n for (let i = 0; i < str.length; i++) {\n const char = str.charAt(i);\n \n if (stack.length > 0 && stack[stack.length - 1] + char == match) {\n totPoints += points;\n stack.pop();\n }\n else {\n stack.push(char);\n }\n }\n \n return stack;\n }\n};", "solution_java": "class Solution {\n public int maximumGain(String s, int x, int y) {\n \n int aCount = 0;\n int bCount = 0;\n int lesser = Math.min(x, y);\n int result = 0;\n \n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (c > 'b') {\n result += Math.min(aCount, bCount) * lesser;\n aCount = 0;\n bCount = 0;\n } else if (c == 'a') {\n if (x < y && bCount > 0) {\n bCount--;\n result += y;\n } else {\n aCount++;\n }\n } else {\n if (x > y && aCount > 0) {\n aCount--;\n result += x;\n } else {\n bCount++;\n };\n }\n }\n \n result += Math.min(aCount, bCount) * lesser;\n \n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int helper(string&str, char a, char b){\n int count =0;\n stack st;\n for(int i=0;iy) {\n ca = helper(s,'a','b');\n cb = helper(s,'b','a');\n }\n else {\n cb = helper(s,'b','a');\n ca = helper(s,'a','b');\n }\n return ca*x + cb*y;\n }\n};" }, { "title": "Valid Boomerang", "algo_input": "Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.\n\nA boomerang is a set of three points that are all distinct and not in a straight line.\n\n \nExample 1:\nInput: points = [[1,1],[2,3],[3,2]]\nOutput: true\nExample 2:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: false\n\n \nConstraints:\n\n\n\tpoints.length == 3\n\tpoints[i].length == 2\n\t0 <= xi, yi <= 100\n\n", "solution_py": "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n a,b,c=points\n return (b[1]-a[1])*(c[0]-b[0]) != (c[1]-b[1])*(b[0]-a[0])", "solution_js": "var isBoomerang = function(points) {\n \n // if any two of the three points are the same point return false;\n \n if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) return false;\n if (points[0][0] == points[2][0] && points[0][1] == points[2][1]) return false;\n if (points[2][0] == points[1][0] && points[2][1] == points[1][1]) return false;\n \n // if the points are in a straight line return false;\n \n let slope1 = (points[0][1] - points[1][1]) / (points[0][0] - points[1][0]);\n let slope2 = (points[1][1] - points[2][1]) / (points[1][0] - points[2][0]);\n if (points[0][0] == points[1][0] && points[0][0] === points[2][0]) return false;\n if (points[0][1] == points[1][1] && points[0][1] === points[2][1]) return false;\n \n if (slope1 === slope2) return false;\n \n return true;\n \n};", "solution_java": "class Solution {\n public boolean isBoomerang(int[][] points) {\n double a, b, c, d, area;\n a=points[0][0]-points[1][0];\n b=points[1][0]-points[2][0];\n c=points[0][1]-points[1][1];\n d=points[1][1]-points[2][1];\n area=0.5*((a*d)-(b*c));\n return area!=0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isBoomerang(vector>& points) {\n if (points.size()<=2) return false;\n int x0=points[0][0], y0=points[0][1];\n int x1=points[1][0], y1=points[1][1];\n int x2=points[2][0], y2=points[2][1];\n int dx1=x1-x0, dy1=y1-y0;\n int dx2=x2-x1, dy2=y2-y1;\n if (dy1*dx2==dy2*dx1) return false;\n return true;\n }\n};" }, { "title": "Regions Cut By Slashes", "algo_input": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions.\n\nGiven the grid grid represented as a string array, return the number of regions.\n\nNote that backslash characters are escaped, so a '\\' is represented as '\\\\'.\n\n \nExample 1:\n\nInput: grid = [\" /\",\"/ \"]\nOutput: 2\n\n\nExample 2:\n\nInput: grid = [\" /\",\" \"]\nOutput: 1\n\n\nExample 3:\n\nInput: grid = [\"/\\\\\",\"\\\\/\"]\nOutput: 5\nExplanation: Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.\n\n\n \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 <= n <= 30\n\tgrid[i][j] is either '/', '\\', or ' '.\n\n", "solution_py": "class Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n n=len(grid)\n dots=n+1\n par=[0]*(dots*dots)\n rank=[0]*(dots*dots)\n self.count=1\n\n def find(x):\n if par[x]==x:\n return x\n temp=find(par[x])\n par[x]=temp\n return temp\n def union(x,y):\n lx=find(x)\n ly=find(y)\n if lx!=ly:\n if rank[lx]>rank[ly]:\n par[ly]=lx\n elif rank[lx] rank[rj]) root[rj] = ri;\n else if (rank[ri] < rank[rj]) root[ri] = rj;\n else root[ri] = rj, rank[rj]++;\n }\n\t// get how many unique unions\n this.getUnoinCount = function() {\n for (var i = 0; i < n; i++) this.find(i);\n return new Set(root).size;\n }\n}\n\nfunction getKeys(i, j, n) {\n var val = i * n + j;\n val *= 2;\n\t// left and right part key of grid[i][j]\n return [val, val + 1];\n}\n\n/**\n * @param {string[]} grid\n * @return {number}\n */\nvar regionsBySlashes = function(grid) {\n var n = grid.length;\n if (n === 1) return grid[0][0] === ' ' ? 1 : 2;\n var ds = new DS(n * n * 2);\n for (var i = 0; i < n; i++) {\n for (var j = 0; j < n; j++) {\n var [left, right] = getKeys(i, j, n);\n\t\t\t// When this cell is ' ', union left and right.\n if (grid[i][j] === ' ') ds.union(left, right);\n\t\t\t// if have upper neighbor\n if (i !== 0) {\n var [upLeft, upRight] = getKeys(i - 1, j, n);\n\t\t\t\t// For upper neighbor, if it's '/', we should choose right part to union, if '\\', choose left.\n var upKey = grid[i - 1][j] === '\\\\' ? upLeft : upRight;\n\t\t\t\t// For current cell, if it's '/', we should choose left part to union, if '\\', choose right.\n var curKey = grid[i][j] === '/' ? left : right;\n ds.union(upKey, curKey);\n }\n\t\t\t// if have left neighbor\n if (j !== 0) {\n var [leftLeft, leftRight] = getKeys(i, j - 1, n);\n\t\t\t\t// just choose the right part of the left neighbor\n var leftKey = leftRight;\n\t\t\t\t// just choose the left part of the current cell\n var curKey = left;\n ds.union(leftKey, curKey);\n }\n }\n }\n return ds.getUnoinCount();\n};", "solution_java": "class Solution {\n int[] parent;\n int[] rank;\n \n public int regionsBySlashes(String[] grid) {\n parent = new int[4*grid.length*grid.length];\n rank = new int[4*grid.length*grid.length];\n \n for(int i=0;i 0){\n int obno = (i-1) * grid.length + j;\n unionHelper(4*bno + 0 , 4*obno + 2);\n }\n \n if(j > 0){\n int obno = i * grid.length + (j-1);\n unionHelper(4*bno + 3 , 4*obno + 1);\n }\n \n }\n }\n \n int count = 0;\n \n for(int i=0;i>& g, vector>& vis, int i, int j){\n for(int d = 0; d<4; ++d){\n int x = i + dir[d][0];\n int y = j + dir[d][1];\n if( x >= 0 && y >= 0 && x < g.size() && y < g.size() && \n vis[x][y] == -1 && g[x][y] == 1){\n vis[x][y] = 1;\n dfs(g, vis, x, y);\n }\n }\n }\n int regionsBySlashes(vector& grid) {\n int n = grid.size();\n vector> g(3*n, vector (3*n, 1)); \n for(int i = 0; i < n; ++i){\n for(int j = 0; j< n; ++j){\n if(grid[i][j] == '\\\\'){\n for(int k = 0; k < 3; ++k) g[3*i+k][3*j+k] = 0;\n }\n else if(grid[i][j] == '/'){\n for(int k = 0; k < 3; ++k) g[3*i+k][3*j+ 2-k] = 0;\n }\n }\n }\n int count = 0;\n vector> vis(3*n, vector (3*n, -1));\n \n for(int i = 0; i < 3*n; ++i){\n for(int j = 0; j < 3*n; ++j){\n if(vis[i][j] == -1 && g[i][j] == 1){ //cout< int:\n mask = 0\n index = defaultdict(lambda:float('-inf'),{0:-1})\n res = 0\n for i,c in enumerate(s):\n mask ^= (1<<(ord(c)-ord('0')))\n if index[mask] == float('-inf'):\n index[mask] = i\n res = max(res, i-index[mask])\n\t\t\t#when the palindrome has one odd numbers of digits\n for j in range(10):\n tmp_mask = mask^(1<map=new HashMap<>();\n map.put(0,-1);\n \n int state=0;\n int ans=0;\n for(int i=0;i map;\n int mask = 0, maxL = 0;\n map[mask] = -1;\n\n for(int i=0; i List[int]:\n result = [label]\n\n #determine level of label\n #O(log n)\n level, nodeCount = 1, 1\n while label >= nodeCount * 2:\n nodeCount *= 2\n level += 1\n\n #Olog(n) time\n while label > 1:\n #compute max and min node\n maxNode, minNode = 2**level-1, 2**(level-1)\n\n parent = ((maxNode + minNode) - label) // 2\n\n #slightly costly operation\n result = [parent] + result\n\n label = parent\n level -= 1\n\n return result", "solution_js": "var pathInZigZagTree = function(label) {\n //store highest and lowest value for each level\n let levels = [[1,1]] //to reduce space complexity we will fill the levels array with out output as we go\n let totalNodes = 1\n let nodesInLastRow = 1\n \n //Calculate which level the label lies in\n while (totalNodes < label) { \n let lowest = totalNodes + 1\n \n nodesInLastRow = nodesInLastRow * 2\n totalNodes += nodesInLastRow\n \n let highest = totalNodes\n \n levels.push([lowest, highest])\n }\n \n\n let index = levels.length\n let childBoundaries = levels[levels.length -1]\n levels[levels.length -1] = label\n \n //Work bottom up, for each level, calculate the value based on the child and the child boundaries boundaries\n for (let i=levels.length-2; i>=0; i--) {\n let childLevel = i+2 //2 because i is index of 0, so 1 is to preset it to 1...n and then and second one is parent level\n let childValue = levels[i+1] \n \n let inversionCalculation = Math.abs((childBoundaries[0] + childBoundaries[1]) - childValue)\n \n childBoundaries = levels[i]\n \n levels[i] = Math.floor(inversionCalculation/2) \n }\n \n return levels\n};", "solution_java": "class Solution {\n \n \n \n \n public List pathInZigZagTree(int label) \n {\n int level, upper, parent, i = label;\n double min, max;\n List ans = new ArrayList ();\n \n ans.add(i);\n \n while( i> 1)\n {\n level = (int)(Math.log(i) / Math.log(2));\n upper = level -1;\n min = Math.pow(2.0, upper);\n max = Math.pow(2.0, level) - 1;\n parent = (int)(min + max) - i/2; \n \n ans.add(0, parent);\n i = parent;\n }\n \n return ans;\n \n \n }\n}", "solution_c": "class Solution\n{\npublic:\n vector pathInZigZagTree(int label)\n {\n vector v;\n int n = 0, num = label;\n while (label)\n {\n n++;\n label = label >> 1;\n }\n\n int l, r, c, ans;\n for (int i = n; i >= 2; i--)\n {\n\n r = pow(2, i) - 1;\n l = pow(2, i - 1);\n c = r - num;\n ans = l + c;\n if ((n + i) % 2)\n {\n v.push_back(ans);\n }\n else\n {\n v.push_back(num);\n }\n num /= 2;\n }\n v.push_back(1);\n sort(v.begin(), v.end());\n return v;\n }\n};" }, { "title": "Longest Word in Dictionary", "algo_input": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.\n\nIf there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.\n\nNote that the word should be built from left to right with each additional character being added to the end of a previous word. \n\n \nExample 1:\n\nInput: words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput: \"world\"\nExplanation: The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\n\n\nExample 2:\n\nInput: words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput: \"apple\"\nExplanation: Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 1000\n\t1 <= words[i].length <= 30\n\twords[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestWord(self, words: List[str]) -> str:\n TrieNode = lambda: defaultdict(TrieNode)\n root = TrieNode()\n for i,s in enumerate(words):\n cur = root\n for c in s: cur=cur[c]\n cur['$']=i\n\n ans = ''\n st = list(root.values())\n while st:\n cur = st.pop()\n if '$' in cur:\n w = words[cur['$']]\n if len(ans) result.length ? word : result;\n } else {\n let has = trie.search(word.slice(0, word.length-1));\n if (has) {\n trie.insert(word);\n result = word.length > result.length ? word : result;\n }\n }\n }\n \n return result;\n};", "solution_java": "class Solution {\n private class Node{\n Node[] sub;\n Node(){\n sub = new Node[26];\n }\n }\n Node root;\n StringBuilder ans;\n private void buildTire(String word){\n Node temp = root;\n int n = word.length();\n for(int i = 0; i < n-1; i++){\n int index = word.charAt(i)-'a';\n if(temp.sub[index] == null) return;\n temp = temp.sub[index];\n }\n int index = word.charAt(n-1)-'a';\n temp.sub[index] = new Node();\n \n if(word.length() > ans.length())\n ans = new StringBuilder(word);\n }\n public String longestWord(String[] words) {\n this.ans = new StringBuilder();\n this.root = new Node();\n PriorityQueue pq = new PriorityQueue<>();\n pq.addAll(Arrays.asList(words));\n while(!pq.isEmpty()) buildTire(pq.poll());\n return ans.toString();\n }\n}", "solution_c": "struct node{\n int end=0;\n node* adj[26];\n};\n\nclass Solution {\npublic:\n string longestWord(vector& words) {\n auto root = new node();\n auto insert = [&](string&s, int ind){\n node* cur = root;\n int i;\n for(char&c:s){\n i=c - 'a';\n if(!cur->adj[i])cur->adj[i] = new node();\n cur=cur->adj[i];\n }\n cur->end=ind;\n };\n\n int ind = 0;\n for(string&s : words) insert(s,++ind);\n\n stack st;\n st.push(root);\n string ans = \"\";\n while(!st.empty()){\n node* cur = st.top();st.pop();\n if(cur->end>0 || cur==root){\n if(cur!=root){\n string word = words[cur->end-1];\n if(word.size()>ans.size() ||\n (word.size()==ans.size() && wordadj[j])st.push(cur->adj[j]);\n }\n }\n return ans;\n }\n};" }, { "title": "Optimal Division", "algo_input": "You are given an integer array nums. The adjacent integers in nums will perform the float division.\n\n\n\tFor example, for nums = [2,3,4], we will evaluate the expression \"2/3/4\".\n\n\nHowever, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.\n\nReturn the corresponding expression that has the maximum value in string format.\n\nNote: your expression should not contain redundant parenthesis.\n\n \nExample 1:\n\nInput: nums = [1000,100,10,2]\nOutput: \"1000/(100/10/2)\"\nExplanation:\n1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant, since they don't influence the operation priority. So you should return \"1000/(100/10/2)\".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n\n\nExample 2:\n\nInput: nums = [2,3,4]\nOutput: \"2/(3/4)\"\n\n\nExample 3:\n\nInput: nums = [2]\nOutput: \"2\"\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 10\n\t2 <= nums[i] <= 1000\n\tThere is only one optimal division for the given iput.\n\n", "solution_py": "class Solution(object):\n def optimalDivision(self, nums):\n\n A = list(map(str, nums))\n \n \n if len(A) <= 2:\n \n return '/'.join(A)\n \n \n return A[0] + '/(' + '/'.join(A[1:]) + ')'", "solution_js": "var optimalDivision = function(nums) {\n\tconst { length } = nums;\n\tif (length === 1) return `${nums[0]}`;\n\tif (length === 2) return nums.join('/');\n\n\treturn nums.reduce((result, num, index) => {\n\t\tif (index === 0) return `${num}/(`;\n\t\tif (index === length - 1) return result + `${num})`;\n\t\treturn result + `${num}/`;\n\t}, '');\n};", "solution_java": "class Solution {\n public String optimalDivision(int[] nums) {\n \n if(nums.length==1){\n return nums[0] + \"\";\n }else if(nums.length==2){\n StringBuilder sb=new StringBuilder();\n sb.append(nums[0] + \"/\" + nums[1]);\n return sb.toString();\n }\n \n StringBuilder sb=new StringBuilder();\n sb.append(nums[0]);\n sb.append(\"/(\");\n for(int i=1;i& nums) {\n string s=\"\";\n if(nums.size()==1)\n return to_string(nums[0]);\n if(nums.size()==2)\n return to_string(nums[0])+'/'+to_string(nums[1]);\n for(int i=0;i int:\n word_dict = defaultdict(list)\n numMatch = 0\n # add words into bucket with key as order of the first letter\n for w in words:\n word_dict[ord(w[0])-ord('a')].append(w)\n # loop through the characters in s\n for c in s:\n qualified = word_dict[ord(c)-ord('a')]\n word_dict[ord(c)-ord('a')] = []\n for q in qualified:\n # if the word starts with the specified letter. i.e this is the last letter of the word\n if len(q) == 1:\n numMatch += 1\n else:\n word_dict[ord(q[1])-ord('a')].append(q[1:])\n return numMatch", "solution_js": "var numMatchingSubseq = function(s, words) {\n let subsequence = false;\n let count = 0;\n let prevIdx, idx \n for(const word of words) {\n prevIdx = -1;\n idx = -1;\n subsequence = true;\n for(let i = 0; i < word.length; i++) {\n idx = s.indexOf(word[i], idx + 1);\n if(idx > prevIdx) {\n prevIdx = idx;\n } else {\n subsequence = false;\n break;\n }\n }\n if(subsequence) count++;\n }\n return count;\n};", "solution_java": "class Solution {\n public int numMatchingSubseq(String s, String[] words) {\n int count = 0;\n Map map = new HashMap<>();\n for(String word : words){\n if(!map.containsKey(word)){\n map.put(word, 1);\n }\n else{\n map.put(word, map.get(word)+1);\n }\n }\n for(String word : map.keySet()){\n if(isSeq(word, s)){\n count += map.get(word);\n }\n }\n return count;\n }\n public boolean isSeq(String s1, String s2){\n int s1ind = 0;\n int s2ind = 0;\n int counter = 0;\n if(s1.length() > s2.length()){\n return false;\n }\n while(s1ind < s1.length() && s2ind < s2.length()){\n if(s1.charAt(s1ind) == s2.charAt(s2ind)){\n counter++;\n s1ind++;\n s2ind++;\n }\n else{\n s2ind++;\n }\n }\n return counter == s1.length();\n }\n}", "solution_c": "class Solution {\npublic:\n int numMatchingSubseq(string s, vector& words) {\n int ct=0;\n unordered_mapm;\n \n for(int i=0;ifirst;\n \n int z=0;\n \n for(int i=0;isecond;\n \n } \n return ct;\n }\n};" }, { "title": "Counting Words With a Given Prefix", "algo_input": "You are given an array of strings words and a string pref.\n\nReturn the number of strings in words that contain pref as a prefix.\n\nA prefix of a string s is any leading contiguous substring of s.\n\n \nExample 1:\n\nInput: words = [\"pay\",\"attention\",\"practice\",\"attend\"], pref = \"at\"\nOutput: 2\nExplanation: The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".\n\n\nExample 2:\n\nInput: words = [\"leetcode\",\"win\",\"loops\",\"success\"], pref = \"code\"\nOutput: 0\nExplanation: There are no strings that contain \"code\" as a prefix.\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length, pref.length <= 100\n\twords[i] and pref consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(word.find(pref) == 0 for word in words)", "solution_js": "var prefixCount = function(words, pref) {\n return words.filter(word => word.slice(0, pref.length) === pref).length;\n};", "solution_java": "class Solution {\n public int prefixCount(String[] words, String pref) {\n int c = 0;\n for(String s : words) {\n if(s.indexOf(pref)==0) \n c++;\n }\n return c; \n }\n}", "solution_c": "class Solution {\npublic:\n int prefixCount(vector& words, string pref) {\n int c=0;\n for(auto word:words){\n int b=0;\n for(int i=0;i a and p -> b.\"\"\"\n return (a[0] - p[0]) * (b[1] - p[1]) \\\n - (a[1] - p[1]) * (b[0] - p[0])\n\n def _convex_hull_monotone_chain(self, points):\n \"\"\"Compute the convex hull of a list of points.\n \n Use Andrew's Monotone Chain algorithm, which is similar to Graham Scan,\n except that it doesn't require sorting the points by angle. This algorithm\n takes O(N log(N)) time, where N is len(points).\n \"\"\"\n # Ensure all points are unique, and sort lexicographically.\n points = list(sorted(set(points)))\n \n # If there are fewer than three points, they must form a hull.\n if len(points) <= 2:\n return points\n \n # Compute the lower and upper portion of the hull.\n lower, upper = [], []\n for out, it in ((lower, points), (upper, reversed(points))):\n for p in it:\n while len(out) >= 2 and self.cross(out[-2], out[-1], p) > 0:\n out.pop()\n out.append(p)\n\n # Concatenate the upper and lower hulls. Remove the last point from each\n # because those points are duplicated in both upper and lower.\n return lower[:-1] + upper[:-1]\n\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Find the convex hull of a collection of points.\n Return a list of indices of points forming the hull in clockwise order,\n starting with the leftmost point.\n \"\"\"\n # Convert input points to tuples.\n points = [tuple(p) for p in trees]\n ans = set()\n for point in self._convex_hull_monotone_chain(points):\n ans.add(point)\n return ans", "solution_js": "const outerTrees = (trees) => {\n trees.sort((x, y) => {\n if (x[0] == y[0]) return x[1] - y[1];\n return x[0] - y[0];\n });\n let lower = [], upper = [];\n for (const tree of trees) {\n while (lower.length >= 2 && cmp(lower[lower.length - 2], lower[lower.length - 1], tree) > 0) lower.pop();\n while (upper.length >= 2 && cmp(upper[upper.length - 2], upper[upper.length - 1], tree) < 0) upper.pop();\n lower.push(tree);\n upper.push(tree);\n\n }\n return [...new Set(lower.concat(upper))];\n};\n\nconst cmp = (p1, p2, p3) => {\n let [x1, y1] = p1;\n let [x2, y2] = p2;\n let [x3, y3] = p3;\n return (y3 - y2) * (x2 - x1) - (y2 - y1) * (x3 - x2);\n};", "solution_java": "class Solution {\n public static class Pair {\n int x;\n int y;\n \n Pair(int x, int y) {\n this.x = x;\n this.y = y;\n }\n \n }\n public int[][] outerTrees(int[][] trees) {\n List points=new ArrayList<>();\n for(int[] point:trees){\n points.add(new Pair(point[0],point[1])); \n }\n\n List res=new ArrayList<>();\n if(points.size()==1){\n return trees;\n }\n int n=points.size();\n Collections.sort(points,(a,b)->a.y==b.y?a.x-b.x:a.y-b.y);\n HashSet> dup=new HashSet<>();\n Stack hull=new Stack<>();\n \n hull.push(points.get(0));\n hull.push(points.get(1));\n \n for(int i=2;i=0;i--){\n Pair top=hull.pop();\n while(!hull.isEmpty()&&ccw(hull.peek(),top,points.get(i))<0){\n top=hull.pop();\n }\n hull.push(top);\n hull.push(points.get(i));\n }\n\n for(Pair p:hull){\n ArrayList tmp=new ArrayList<>();\n tmp.add(p.x);\n tmp.add(p.y);\n if(dup.contains(tmp))continue;\n dup.add(tmp);\n res.add(p);\n }\n\n int[][] ans=new int[res.size()][2];\n int i=0;\n for(Pair p:res){\n ans[i][0]=p.x;\n ans[i][1]=p.y;\n i++;\n }\n \n return ans;\n \n }\n\n public int ccw(Pair a,Pair b,Pair c){\n double cp=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\n if(cp<0)return -1;\n else if(cp>0)return 1;\n else return 0;\n }\n}", "solution_c": "class Solution {\n public:\n vector> outerTrees(vector>& trees) {\n if (trees.size() <= 1) return trees;\n\n int origin = 0;\n for (int i = 0; i < trees.size(); ++i) {\n if (trees[origin][1] > trees[i][1] || trees[origin][1] == trees[i][1] && trees[origin][0] > trees[i][0]) {\n origin = i;\n }\n }\n swap(trees[0], trees[origin]);\n sort(trees.begin() + 1, trees.end(), [&](const vector& lhs, const vector& rhs) -> bool {\n int result = cross(trees[0], lhs, rhs);\n if (result != 0) return result > 0;\n return norm(trees[0], lhs) < norm(trees[0], rhs);\n });\n\n // deal with cases that the last k points are on one line\n int pos = trees.size() - 2;\n while (pos > 0 && cross(trees[0], trees.back(), trees[pos]) == 0) {\n --pos;\n }\n reverse(trees.begin() + pos + 1, trees.end());\n\n vector> ans = {trees[0], trees[1]};\n for (int i = 2; i < trees.size(); ++i) {\n int cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);\n while (cross_result < 0) {\n ans.pop_back();\n cross_result = cross(ans[ans.size() - 2], ans[ans.size() - 1], trees[i]);\n }\n ans.push_back(trees[i]);\n }\n return ans;\n }\n\n private:\n inline double norm(const vector& o, const vector& x) {\n int xx = x[0] - o[0];\n int yy = x[1] - o[1];\n return sqrt(xx * xx + yy * yy);\n }\n\n inline int cross(const vector& x, const vector& y, const vector& z) {\n return (y[0] - x[0]) * (z[1] - y[1]) - (y[1] - x[1]) * (z[0] - y[0]);\n }\n};" }, { "title": "Excel Sheet Column Number", "algo_input": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.\n\nFor example:\n\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n\n\n \nExample 1:\n\nInput: columnTitle = \"A\"\nOutput: 1\n\n\nExample 2:\n\nInput: columnTitle = \"AB\"\nOutput: 28\n\n\nExample 3:\n\nInput: columnTitle = \"ZY\"\nOutput: 701\n\n\n \nConstraints:\n\n\n\t1 <= columnTitle.length <= 7\n\tcolumnTitle consists only of uppercase English letters.\n\tcolumnTitle is in the range [\"A\", \"FXSHRXW\"].\n\n", "solution_py": "def let_to_num(char):\n abc = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n return abc.index(char) + 1\n\nclass Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n ans = 0\n for i in range(len(columnTitle)):\n ans *= 26\n ans += let_to_num(columnTitle[i])\n return ans", "solution_js": "/**\n * @param {string} columnTitle\n * @return {number}\n */\nvar titleToNumber = function(columnTitle) {\n /*\n one letter: result between 1-26.\n two letter: result between 26^1 + 1 -> 26^2 + digit. 27 - 702. All the combinations of A-Z and A-Z. \n */\n \n let sum = 0;\n for (let letter of columnTitle) {\n let d = letter.charCodeAt(0) - 'A'.charCodeAt(0) + 1;\n sum = sum * 26 + d;\n }\n \n return sum;\n};", "solution_java": "class Solution {\n public int titleToNumber(String columnTitle) {\n int n = columnTitle.length();\n int pow = 0;\n int res = 0;\n for(int i = n-1; i >= 0; i--) {\n char c = columnTitle.charAt(i);\n res += (c - 64) * Math.pow(26, pow);\n pow++;\n }\n\n return res;\n }\n}", "solution_c": "\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n int titleToNumber(string columnTitle) {\n int result = 0;\n for(char c : columnTitle)\n {\n\t\t\t//d = s[i](char) - 'A' + 1 (we used s[i] - 'A' to convert the letter to a number like it's going to be C)\n\n int d = c - 'A' + 1;\n result = result * 26 + d;\n }\n return result;\n }\n};" }, { "title": "Fancy Sequence", "algo_input": "Write an API that generates fancy sequences using the append, addAll, and multAll operations.\n\nImplement the Fancy class:\n\n\n\tFancy() Initializes the object with an empty sequence.\n\tvoid append(val) Appends an integer val to the end of the sequence.\n\tvoid addAll(inc) Increments all existing values in the sequence by an integer inc.\n\tvoid multAll(m) Multiplies all existing values in the sequence by an integer m.\n\tint getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.\n\n\n \nExample 1:\n\nInput\n[\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\nOutput\n[null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n\nExplanation\nFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20\n\n\n \nConstraints:\n\n\n\t1 <= val, inc, m <= 100\n\t0 <= idx <= 105\n\tAt most 105 calls total will be made to append, addAll, multAll, and getIndex.\n\n", "solution_py": "def egcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = egcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\ndef modinv(a, m):\n g, x, y = egcd(a, m)\n return x % m\n\nmod = 1000000007\n\nclass Fancy(object):\n\n def __init__(self):\n self.seq = []\n self.addC = 0\n self.mulC = 1\n \n def append(self, val):\n \"\"\"\n :type val: int\n :rtype: None\n \"\"\"\n self.seq.append([val, self.mulC, self.addC])\n \n\n def addAll(self, inc):\n \"\"\"\n :type inc: int\n :rtype: None\n \"\"\"\n self.addC = (self.addC%mod + inc%mod)%mod\n\n def multAll(self, m):\n \"\"\"\n :type m: int\n :rtype: None\n \"\"\"\n self.mulC = (self.mulC%mod * m%mod)%mod\n self.addC = (self.addC%mod * m%mod)%mod\n \n\n def getIndex(self, idx):\n \"\"\"\n :type idx: int\n :rtype: int\n \"\"\"\n if(idx >= len(self.seq)):\n return -1\n \n mulCo = self.seq[idx][1]\n addCo = self.seq[idx][2]\n val = self.seq[idx][0]\n \n inv = modinv(mulCo, mod)\n a = (self.mulC%mod * inv%mod)%mod\n val = (val%mod * a%mod)%mod\n b = (addCo%mod * a%mod)%mod\n val = (val%mod - b%mod)%mod\n val = (val%mod + self.addC%mod)%mod\n \n return val", "solution_js": "var Fancy = function() {\n this.sequence = [];\n this.appliedOps = [];\n this.ops = [];\n this.modulo = Math.pow(10, 9) + 7;\n};\n\n/**\n * @param {number} val\n * @return {void}\n */\nFancy.prototype.append = function(val) {\n this.sequence.push(val);\n this.appliedOps.push(this.ops.length);\n};\n\n/**\n * @param {number} inc\n * @return {void}\n */\nFancy.prototype.addAll = function(inc) {\n this.ops.push(['add', inc]);\n};\n\n/**\n * @param {number} m\n * @return {void}\n */\nFancy.prototype.multAll = function(m) {\n this.ops.push(['mult', m]);\n};\n\n/**\n * @param {number} idx\n * @return {number}\n */\nFancy.prototype.getIndex = function(idx) {\n if (idx >= this.sequence.length) {\n return -1;\n }\n\n while (this.appliedOps[idx] < this.ops.length) {\n const [operation, value] = this.ops[this.appliedOps[idx]];\n this.appliedOps[idx]++;\n\n if (operation === 'mult') {\n this.sequence[idx] = (this.sequence[idx] * value) % this.modulo;\n }\n\n if (operation === 'add') {\n this.sequence[idx] = (this.sequence[idx] + value) % this.modulo;\n }\n }\n\n return this.sequence[idx];\n};\n\n/**\n * Your Fancy object will be instantiated and called as such:\n * var obj = new Fancy()\n * obj.append(val)\n * obj.addAll(inc)\n * obj.multAll(m)\n * var param_4 = obj.getIndex(idx)\n */", "solution_java": "class Fancy {\n private ArrayList lst;\n private ArrayList add;\n private ArrayList mult;\n private final long MOD = 1000000007;\n\n public Fancy() {\n lst = new ArrayList<>();\n add = new ArrayList<>();\n mult = new ArrayList<>();\n add.add(0L);\n mult.add(1L);\n }\n\n public void append(int val) {\n lst.add((long) val);\n int l = add.size();\n add.add(add.get(l - 1));\n mult.add(mult.get(l - 1));\n }\n\n public void addAll(int inc) {\n int l = add.size();\n add.set(l - 1, add.get(l - 1) + inc);\n }\n\n public void multAll(int m) {\n int l = add.size();\n add.set(l - 1, (add.get(l - 1) * m) % MOD);\n mult.set(l - 1, (mult.get(l - 1) * m) % MOD);\n }\n\n public int getIndex(int idx) {\n if (idx >= lst.size()) return -1;\n\n int l = add.size();\n long m = (mult.get(l - 1) * inverse(mult.get(idx))) % MOD;\n long a = (add.get(l - 1) - (add.get(idx) * m) % MOD + MOD) % MOD;\n return (int) (((lst.get(idx) * m) % MOD + a) % MOD);\n }\n\n long inverse(long a) {\n return pow(a, MOD - 2);\n }\n\n long pow(long a, long n) {\n if (n == 0) return 1;\n if (n % 2 == 0) {\n long t = pow(a, n / 2);\n return (t * t) % MOD;\n } else {\n return (pow(a, n - 1) * a) % MOD;\n }\n }\n}", "solution_c": "int mod97 = 1000000007;\n/**\nCalculates multiplicative inverse\n*/\nunsigned long modPow(unsigned long x, int y) {\n unsigned long tot = 1, p = x;\n for (; y; y >>= 1) {\n if (y & 1)\n tot = (tot * p) % mod97;\n p = (p * p) % mod97;\n }\n return tot;\n }\nclass Fancy {\npublic:\n unsigned long seq[100001];\n unsigned int length = 0;\n unsigned long increment = 0;\n unsigned long mult = 1;\n Fancy() {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n }\n \n void append(int val) {\n seq[length++] = (((mod97 + val - increment)%mod97) * modPow(mult, mod97-2))%mod97;\n }\n void addAll(int inc) {\n increment = (increment+ inc%mod97)%mod97;\n }\n \n void multAll(int m) {\n mult = (mult* m%mod97)%mod97;\n increment = (increment* m%mod97)%mod97;\n }\n \n int getIndex(int idx) {\n \n if (idx >= length){\n return -1;\n }else{\n return ((seq[idx] * mult)%mod97+increment)%mod97;\n }\n }\n};" }, { "title": "Replace Elements in an Array", "algo_input": "You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].\n\nIt is guaranteed that in the ith operation:\n\n\n\toperations[i][0] exists in nums.\n\toperations[i][1] does not exist in nums.\n\n\nReturn the array obtained after applying all the operations.\n\n \nExample 1:\n\nInput: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\nOutput: [3,2,7,1]\nExplanation: We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].\n\n\nExample 2:\n\nInput: nums = [1,2], operations = [[1,3],[2,1],[3,2]]\nOutput: [2,1]\nExplanation: We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\tm == operations.length\n\t1 <= n, m <= 105\n\tAll the values of nums are distinct.\n\toperations[i].length == 2\n\t1 <= nums[i], operations[i][0], operations[i][1] <= 106\n\toperations[i][0] will exist in nums when applying the ith operation.\n\toperations[i][1] will not exist in nums when applying the ith operation.\n\n", "solution_py": "class Solution:\n def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:\n replacements = {}\n for x, y in reversed(operations):\n replacements[x] = replacements.get(y, y)\n for idx, val in enumerate(nums):\n if val in replacements:\n nums[idx] = replacements[val]\n return nums", "solution_js": "/**\n * @param {number[]} nums\n * @param {number[][]} operations\n * @return {number[]}\n */\nvar arrayChange = function(nums, operations) {\n let map = new Map()\n\n for(let i = 0; i < nums.length; i++){\n let num = nums[i]\n map.set(num, i)\n }\n\n for(let op of operations){\n let key = op[0]\n let value = op[1]\n\n // if key exists\n if(map.has(key)){\n const idx = map.get(key)\n map.set(value, idx)\n map.delete(key)\n }\n }\n\n for(let [key, idx] of map){\n nums[idx] = key\n }\n\n return nums\n\n};", "solution_java": "class Solution {\n public int[] arrayChange(int[] nums, int[][] operations) {\n Map map = new HashMap<>();\n for(int i=0;i arrayChange(vector& nums, vector>& operations) {\n for (int i = 0; i < nums.size(); ++i)\n m[nums[i]] = i;\n for (auto &op : operations) {\n nums[m[op[0]]] = op[1];\n m[op[1]] = m[op[0]];\n }\n return nums;\n}\n};" }, { "title": "Two City Scheduling", "algo_input": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.\n\nReturn the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n\n \nExample 1:\n\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n\n\nExample 2:\n\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\n\n\nExample 3:\n\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n\n\n \nConstraints:\n\n\n\t2 * n == costs.length\n\t2 <= costs.length <= 100\n\tcosts.length is even.\n\t1 <= aCosti, bCosti <= 1000\n\n", "solution_py": "class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n n = len(costs)\n m = n // 2\n \n @lru_cache(None)\n def dfs(cur, a):\n\t\t\t# cur is the current user index\n\t\t\t# `a` is the number of people travel to city `a`\n\t\t\t\n if cur == n:\n return 0\n \n\t\t\t# people to b city\n b = cur - a\n ans = float('inf')\n \n\t\t\t# the number of people to `a` city number did not reach to limit, \n\t\t\t# then current user can trval to city `a`\n\t\t\t\n if a < m:\n ans = min(dfs(cur+1, a+1)+costs[cur][0], ans)\n \n\t\t\t# the number of people to `b` city number did not reach to limit\n\t\t\t# then current user can trval to city `b`\n if b < m:\n ans = min(dfs(cur+1, a)+costs[cur][1], ans)\n \n return ans\n \n return dfs(0, 0)", "solution_js": "/**\n * @param {number[][]} costs\n * @return {number}\n */\nvar twoCitySchedCost = function(costs) {\n // TC: O(nlogn) and O(1) extra space\n let n=costs.length;\n let countA=0,countB=0,minCost=0;\n \n // sorted in descending order by their absolute diff\n costs=costs.sort((a,b)=>{\n let diffA=Math.abs(a[0] - a[1]);\n let diffB=Math.abs(b[0] - b[1]);\n return diffB-diffA;\n });\n \n for(let i=0;i Integer.compare(c2[1] - c2[0], c1[1] - c1[0]));// biggest to smallest\n int minCost = 0; \n int n = costs.length;\n for (int i = 0; i < n; i++) {\n minCost += i < n/2? costs[i][0] : costs[i][1];//First half -> A; Last half -> B 259 + 184 + 577 + 54 + 667 + 118\n }\n return minCost;\n }\n}", "solution_c": "class Solution {\npublic:\n int twoCitySchedCost(vector>& costs) {\n sort(costs.begin(), costs.end(), [](const vector &curr, const vector &next){ // CUSTOM COMPARATOR\n return (curr[0]-curr[1]) < (next[0]-next[1]); // (comparing cost of sending to A - cost to B)\n });\n // original: [[10,20],[30,200],[400,50],[30,20]] \n // after sort: [[30,200],[10,20],[30,20],[400,50]]\n // to do: a a b b\n \n int sum = 0;\n for(int i=0; i str:\n stack=[]\n res=''\n for i in range(len(s)):\n if len(stack)==0:\n stack.append([s[i],1])\n elif stack[-1][0]==s[i]:\n stack[-1][1]=stack[-1][1]+1\n else:\n stack.append([s[i],1])\n if stack[-1][1]==k:\n stack.pop()\n for i in range(len(stack)):\n res+=stack[i][0]*stack[i][1]\n return res", "solution_js": "var removeDuplicates = function(s, k) {\n const stack = []\n for(const c of s){\n const obj = {count: 1, char: c}\n if(!stack.length){\n stack.push(obj)\n continue\n }\n const top = stack[stack.length-1]\n if(top.char === obj.char && obj.count + top.count === k){\n let count = k\n while(count > 1){\n stack.pop()\n count--\n }\n }else if(top.char === obj.char){\n obj.count+=top.count\n stack.push(obj)\n }else{\n stack.push(obj)\n }\n }\n return stack.reduce((a,b)=> a+b.char, '')\n};", "solution_java": "class Solution\n{\n public String removeDuplicates(String s, int k)\n {\n int i = 0 ;\n StringBuilder newString = new StringBuilder(s) ;\n int[] count = new int[newString.length()] ;\n while( i < newString.length() )\n {\n if( i == 0 || newString.charAt(i) != newString.charAt( i - 1 ) )\n {\n count[i] = 1 ;\n }\n else\n {\n count[i] = count[ i - 1 ] + 1 ;\n if( count[i] == k )\n {\n newString.delete( i - k + 1 , i + 1 ) ;\n i = i - k ;\n }\n }\n i++ ;\n }\n return newString.toString() ;\n }\n}", "solution_c": "#define pp pair< int , char > \n\nclass Solution {\npublic:\n string removeDuplicates(string s, int k) {\n \n int n=s.size();\n \n stack< pp > stk;\n \n int i=0;\n \n while(i int:\n roman = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n\n sum = 0;\n for i in range(0, len(s) - 1):\n curr = roman[s[i]]\n nxt = roman[s[i + 1]]\n if curr < nxt:\n sum -= curr\n else:\n sum += curr\n sum += roman[s[-1]]\n return sum", "solution_js": "var romanToInt = function(s) {\n const sym = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n }\n\n let result = 0;\n\n for (let i = 0; i < s.length; i++) {\n const cur = sym[s[i]];\n const next = sym[s[i + 1]];\n\n if (cur < next) {\n result += next - cur;\n i++;\n } else {\n result += cur;\n }\n }\n\n return result;\n};", "solution_java": "class Solution {\n public int romanToInt(String s) {\n int res=0;\n // Let s = \"IV\" after traversing string res will be 6\n // Let s= \"IX\" after traversing string res will be 11\n for(int i=0;i T = { { 'I' , 1 },\n { 'V' , 5 },\n { 'X' , 10 },\n { 'L' , 50 },\n { 'C' , 100 },\n { 'D' , 500 },\n { 'M' , 1000 } };\n int sum = T[s.back()];\n for (int i = s.length() - 2; i >= 0; --i){\n if (T[s[i]] < T[s[i + 1]]) sum -= T[s[i]];\n else sum += T[s[i]];\n }\n return sum;\n }\n};" }, { "title": "Palindrome Number", "algo_input": "Given an integer x, return true if x is palindrome integer.\n\nAn integer is a palindrome when it reads the same backward as forward.\n\n\n\tFor example, 121 is a palindrome while 123 is not.\n\n\n \nExample 1:\n\nInput: x = 121\nOutput: true\nExplanation: 121 reads as 121 from left to right and from right to left.\n\n\nExample 2:\n\nInput: x = -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n\n\nExample 3:\n\nInput: x = 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n\n\n \nConstraints:\n\n\n\t-231 <= x <= 231 - 1\n\n\n \nFollow up: Could you solve it without converting the integer to a string?", "solution_py": "class Solution(object):\n def isPalindrome(self,x):\n return str(x) == str(x)[::-1]", "solution_js": "var isPalindrome = function(x) {\n if(x < 0 || x % 10 === 0 && x !== 0) return false\n\n let num = x\n let rev_x = 0\n\n while(x > 0){\n let digit = Math.floor(x % 10)\n rev_x = Math.floor(rev_x * 10 + digit)\n x = Math.floor(x / 10)\n }\n return num === rev_x\n};", "solution_java": "class Solution {\n public boolean isPalindrome(int x) {\n int sum = 0;\n int X = x;\n\n while(x > 0){\n sum = 10 * sum + x % 10;\n x /= 10;\n }\n\n return sum == X;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPalindrome(int x) {\n if (x < 0) {\n return false;\n }\n\n long long reversed = 0;\n long long temp = x;\n\n while (temp != 0) {\n int digit = temp % 10;\n reversed = reversed * 10 + digit;\n temp /= 10;\n }\n\n return (reversed == x);\n }\n};" }, { "title": "Number of Good Leaf Nodes Pairs", "algo_input": "You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.\n\nReturn the number of good leaf node pairs in the tree.\n\n \nExample 1:\n\nInput: root = [1,2,3,null,4], distance = 3\nOutput: 1\nExplanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\n\n\nExample 2:\n\nInput: root = [1,2,3,4,5,6,7], distance = 3\nOutput: 2\nExplanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\n\n\nExample 3:\n\nInput: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput: 1\nExplanation: The only good pair is [2,5].\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 210].\n\t1 <= Node.val <= 100\n\t1 <= distance <= 10\n\n", "solution_py": "class Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n adjList=defaultdict(list)\n leaves=[]\n ct=0\n \n [#undirected graph two way using parent and node in postorder style]\n def dfs(node, parent):\n if node:\n if not node.left and not node.right:\n leaves.append(node)\n adjList[node].append(parent)\n adjList[parent].append(node)\n dfs(node.left,node)\n dfs(node.right,node)\n \n [#construct graph and get all the leaves]\n dfs(root, None)\n \n #bfs from each leaf till we find another leaf\n for leaf in leaves:\n q=deque([(leaf,0)] )\n seen=set()\n while q:\n curr,dist = q.popleft()\n seen.add(curr)\n if dist>distance:\n break \n for nbr in adjList[curr]:\n if nbr and nbr not in seen:\n if nbr in leaves and dist+1<=distance:\n ct+=1\n q.append((nbr,dist+1))\n \n return ct//2", "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 * @param {number} distance\n * @return {number}\n */\nvar countPairs = function(root, distance) {\n var graph = new Map()\n var leaves = new Map()\n function dfs(root, parent) {\n if (!root) return \n if (!root.left && !root.right) {\n leaves.set(root, true)\n }\n\n graph.set(root, [])\n if (root.left) {\n graph.get(root).push(root.left)\n }\n if (root.right) {\n graph.get(root).push(root.right)\n }\n if (parent) {\n graph.get(root).push(parent)\n }\n dfs(root.left, root)\n dfs(root.right, root)\n } \n\n dfs(root, null)\n\n var visited = new Map()\n var count = 0\n\n function bfs(start, dis) {\n visited.set(start, true)\n var queue = [graph.get(start).filter(node => !visited.has(node))]\n\n var innerVisited = new Map()\n\n while (queue.length) {\n var curLevelNodes = queue.shift()\n\n if (!curLevelNodes.length) break\n if (dis === 0) break\n\n var nextLevelNodes = []\n for (var i = 0; i < curLevelNodes.length; i++) {\n var curLevelNode = curLevelNodes[i]\n\n innerVisited.set(curLevelNode, true)\n\n if (leaves.has(curLevelNode)) {\n count++\n }\n\n nextLevelNodes.push(\n ...graph\n .get(curLevelNode)\n .filter(node => \n !visited.has(node) && \n !innerVisited.has(node)\n )\n )\n \n }\n queue.push(nextLevelNodes)\n dis--\n }\n }\n\n leaves.forEach((value, leaf) => {\n bfs(leaf, distance)\n })\n\n return count\n};", "solution_java": "class Solution {\n static int res;\n public int countPairs(TreeNode root, int distance) {\n res=0;\n rec(root,distance);\n return res;\n }\n static List rec(TreeNode root,int dist){\n if(root==null){\n return new LinkedList();\n }\n List left=rec(root.left,dist);\n List right=rec(root.right,dist);\n if(left.size()==0&&right.size()==0){\n List temp=new LinkedList<>();\n temp.add(1);\n return temp;\n }\n for(int i:left){\n for(int j:right){\n if(i+j<=dist){\n res++;\n }\n }\n }\n List temp=new LinkedList<>();\n for(int i:left){\n temp.add(i+1);\n }\n for(int i:right){\n temp.add(i+1);\n }\n return temp;\n }\n}", "solution_c": "class Solution {\n vector leaves;\n unordered_map pof;\n void makeGraph(unordered_map &pof, TreeNode* root){\n if(!root) return;\n if(!root->left && !root->right){\n leaves.push_back(root);\n return;\n }\n if(root->left) pof[root->left]=root;\n if(root->right) pof[root->right]=root;\n makeGraph(pof, root->left);\n makeGraph(pof, root->right);\n }\npublic:\n int countPairs(TreeNode* root, int distance) {\n leaves={};\n makeGraph(pof, root);\n int ans=0;\n queue> q;\n for(auto &l: leaves){\n q.push({l, 0}); \n unordered_set isVis;\n while(q.size()){\n auto [cur, dist]=q.front();\n q.pop();\n if(isVis.count(cur) || dist>distance) continue;\n isVis.insert(cur);\n if(!cur->left && !cur->right && cur!=l && dist<=distance){\n ans++;\n continue;\n }\n if(cur->left && !isVis.count(cur->left)) q.push({cur->left, dist+1});\n if(cur->right && !isVis.count(cur->right)) q.push({cur->right, dist+1});\n if(pof.count(cur) && !isVis.count(pof[cur])) q.push({pof[cur], dist+1});\n }\n }\n return ans>>1;\n }\n};" }, { "title": "Single Element in a Sorted Array", "algo_input": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.\n\nReturn the single element that appears only once.\n\nYour solution must run in O(log n) time and O(1) space.\n\n \nExample 1:\nInput: nums = [1,1,2,3,3,4,4,8,8]\nOutput: 2\nExample 2:\nInput: nums = [3,3,7,7,10,11,11]\nOutput: 10\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n return self.b_search(nums)[0]\n \n def b_search(self, nums):\n if len(nums) == 1:\n return nums\n mid = len(nums)//2\n a = nums[:mid]\n b = nums[mid:]\n\t\t\n\t\t# check if last & first element of the two sub lists are same\n if a[-1] == b[0]:\n a = a[:-1]\n b = b[1:]\n\t\t\n\t\t# ignore the sub list with even number of elements\n if len(a)%2:\n return self.b_search(a)\n else:\n return self.b_search(b)", "solution_js": "var singleNonDuplicate = function(nums) {\n var start = 0;\n var end = nums.length - 1\n // to check one element\n if (nums.length == 1) return nums[start]\n while(start <= end) {\n if(nums[start] != nums[start + 1]) {\n return nums[start] }\n\n if(nums[end] != nums[end - 1]) {\n return nums[end]\n }\n // increment two point\n start = start + 2;\n end = end - 2;\n\n }\n};", "solution_java": "class Solution {\n public int singleNonDuplicate(int[] nums) {\n if(nums.length==1) return nums[0];\n int l = 0;\n int h = nums.length-1;\n \n while(l& nums) {\n int ans=0;\n for(int i=0; i int:\n cost.sort(reverse=True)\n res, i, N = 0, 0, len(cost)\n while i < N:\n res += sum(cost[i : i + 2])\n i += 3\n return res", "solution_js": "var minimumCost = function(cost) {\n if (cost.length < 3) {\n return cost.reduce((prev, cur) => prev + cur);\n }\n\n cost.sort((a, b) => b - a);\n let count = 0;\n let sum = 0;\n\n for (const num of cost) {\n if (count === 2) {\n count = 0;\n continue;\n }\n sum += num;\n count++;\n }\n\n return sum;\n};", "solution_java": "class Solution {\n /** Algorithm\n * 1. Sort the cost array.\n * 2. In a loop, start from the back and buy items n, n-1 to get n-2 for free.\n * 3. Decrement the position by 3 and continue. stop when you reach 1.\n * 4. From 1, add the remaining 1 or 2 items.\n *\n */\n public int minimumCost(int[] cost) {\n int minCost = 0;\n int index = cost.length -1;\n Arrays.sort(cost);\n // add items in pairs of 2, the 3rd one getting it for free.\n while (index > 1) {\n minCost += cost[index] + cost[index -1];\n index -= 3;\n }\n // add the remaining 1, 2 items, if any.\n while(index >= 0) {\n minCost += cost[index--];\n }\n return minCost;\n }\n}", "solution_c": "//Solution 01:\nclass Solution {\npublic:\n int minimumCost(vector& cost) {\n int n = cost.size();\n int i = n-1, ans = 0;\n\n if(n <= 2){\n for(auto x: cost)\n ans += x;\n return ans;\n }\n\n sort(cost.begin(), cost.end());\n\n while(i>=1){\n ans += cost[i] + cost[i-1];\n if(i-1 == 0 || i-1 == 1) return ans;\n i = i-3;\n }\n ans += cost[0];\n\n return ans;\n }\n};" }, { "title": "Check Completeness of a Binary Tree", "algo_input": "Given the root of a binary tree, determine if it is a complete binary tree.\n\nIn a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n\n \nExample 1:\n\nInput: root = [1,2,3,4,5,6]\nOutput: true\nExplanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\n\n\nExample 2:\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: false\nExplanation: The node with value 7 isn't as far left as possible.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t1 <= Node.val <= 1000\n\n", "solution_py": "class Solution:\n\tdef isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n\t\t# if not root: return True\n\t\tdef node_count(root):\n\t\t\tif not root: return 0\n\t\t\treturn 1 + node_count(root.left) + node_count(root.right)\n\n\t\tdef isCBT(root,i,count):\n\t\t\tif not root: return True\n\t\t\tif i>=count: return False\n\t\t\treturn isCBT(root.left,2*i+1,count) and isCBT(root.right,2*i+2,count)\n\n\n\t\treturn isCBT(root,0,node_count(root))", "solution_js": "var isCompleteTree = function(root) {\nlet queue = [root];\nlet answer = [root];\nwhile(queue.length > 0) {\n let current = queue.shift();\n if(current) {\n queue.push(current.left);\n answer.push(current.left);\n queue.push(current.right);\n answer.push(current.right);\n }\n}\n\nconsole.log(\"queue\", queue);\n\nwhile(answer.length > 0 ) {\n let current = answer.shift();\n if(current === null) break;\n}\nconsole.log(\"answer after shifting\", answer);\n let flag = true;\n for(let current of answer) {\n if(current !== null) {\n flag = false;\n break\n }\n}\n\nreturn flag\n};", "solution_java": "class Solution {\n public boolean isCompleteTree(TreeNode root) {\n boolean end = false;\n Queue queue = new LinkedList<>();\n queue.offer(root);\n while(!queue.isEmpty()) {\n TreeNode currentNode = queue.poll();\n if(currentNode == null) {\n end = true;\n } else {\n if(end) {\n return false;\n }\n queue.offer(currentNode.left);\n queue.offer(currentNode.right);\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isComplete = true;\n\n // Returns min, max height of node\n pair helper(TreeNode *root){\n // NULL is of height zero\n if(root == NULL){\n return {0, 0};\n }\n\n // Moving to its children\n pair lst = helper(root->left);\n pair rst = helper(root->right);\n\n // Height of rst is greater than lst or\n // There are levels which are not filled other than the last level (diff between levels > 1)\n if(rst.second > lst.first || lst.second - rst.first > 1){\n isComplete = false;\n }\n\n return {min(lst.first, rst.first)+1, max(lst.second, rst.second)+1};\n }\n\n bool isCompleteTree(TreeNode* root) {\n helper(root);\n return isComplete;\n }\n};" }, { "title": "Distinct Subsequences", "algo_input": "Given two strings s and t, return the number of distinct subsequences of s which equals t.\n\nA string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., \"ACE\" is a subsequence of \"ABCDE\" while \"AEC\" is not).\n\nThe test cases are generated so that the answer fits on a 32-bit signed integer.\n\n \nExample 1:\n\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from S.\nrabbbit\nrabbbit\nrabbbit\n\n\nExample 2:\n\nInput: s = \"babgbag\", t = \"bag\"\nOutput: 5\nExplanation:\nAs shown below, there are 5 ways you can generate \"bag\" from S.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag\n\n \nConstraints:\n\n\n\t1 <= s.length, t.length <= 1000\n\ts and t consist of English letters.\n\n", "solution_py": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n if len(t) > len(s):\n return 0\n ls, lt = len(s), len(t)\n res = 0\n dp = [[0] * (ls + 1) for _ in range(lt + 1)]\n for j in range(ls + 1):\n dp[-1][j] = 1\n for i in range(lt - 1, -1, -1):\n for j in range(ls -1 , -1, -1):\n dp[i][j] = dp[i][j + 1]\n if s[j] == t[i]:\n\n dp[i][j] += dp[i + 1][j + 1]\n return dp[0][0]", "solution_js": "var numDistinct = function(s, t) {\n const n = s.length;\n\n const memo = {};\n const dfs = (index = 0, subsequence = '') => {\n if(subsequence === t) return 1;\n if(n - index + 1 < t.length - subsequence.length) return 0;\n if(index === n) return 0;\n\n const key = `${index}-${subsequence}`;\n if(key in memo) return memo[key];\n\n memo[key] = t[subsequence.length] !== s[index] ? 0 : dfs(index + 1, subsequence + s[index]);\n memo[key] += dfs(index + 1, subsequence);\n return memo[key];\n }\n\n return dfs();\n};", "solution_java": "class Solution {\n // We assume that dp[i][j] gives us the total number of distinct subsequences for the string s[0 to i] which equals string t[0 to j]\n int f(int i,int j,String s,String t,int dp[][]){\n //If t gets exhausted then all the characters in t have been matched with s so we can return 1 (we found a subsequence)\n if(j<0)\n return 1;\n // if s gets exhausted then there are characters remaining in t which are yet to be matched as s got exhausted they could not be matched so there is no distinct subsequence\n if(i<0){\n return 0;\n }\n if(dp[i][j]!=-1)\n return dp[i][j];\n //If both the characters in s[i] and t[j] match then we have two case\n //1) Either consider the i'th character of s and find the remaining distinct subsequences of s[0 to i-1] which equals t[0 to j-1] set i.e. f(i-1,j-1)\n //2) Do not consider s[i] so we are still at the same j'th character of t as we had not been considering s[i] matched with t[j] we check distinct subsequences of t[0 to j] in s[0 to i-1] i.e. f(i-1,j)\n if(s.charAt(i)==t.charAt(j)){\n dp[i][j]= f(i-1,j-1,s,t,dp)+f(i-1,j,s,t,dp);\n }\n // If both of them do not match then we consider the 2nd case of matching characters\n else{\n dp[i][j]=f(i-1,j,s,t,dp);\n } \n return dp[i][j];\n }\n public int numDistinct(String s, String t) {\n int n=s.length();\n int m=t.length();\n int dp[][]=new int[n][m];\n for(int i=0;i> &dp){\n if(j >= t.size()) return 1;\n if(i >= s.size() || t.size() - j > s.size() - i) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n int res = 0;\n for(int k = i; k < s.size(); k++){\n if(s[k] == t[j]) res += solve(s, t, k+1, j+1, dp); \n }\n return dp[i][j] = res;\n }\n \n int numDistinct(string s, string t) {\n if(s.size() == t.size()) return s == t;\n vector> dp(s.size(), vector (t.size(), -1));\n return solve(s, t, 0 , 0, dp);\n }\n};" }, { "title": "Number of Substrings Containing All Three Characters", "algo_input": "Given a string s consisting only of characters a, b and c.\n\nReturn the number of substrings containing at least one occurrence of all these characters a, b and c.\n\n \nExample 1:\n\nInput: s = \"abcabc\"\nOutput: 10\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\" and \"abc\" (again). \n\n\nExample 2:\n\nInput: s = \"aaacb\"\nOutput: 3\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"aaacb\", \"aacb\" and \"acb\". \n\n\nExample 3:\n\nInput: s = \"abc\"\nOutput: 1\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 5 x 10^4\n\ts only consists of a, b or c characters.\n\n", "solution_py": "class Solution:\n def numberOfSubstrings(self, s: str) -> int:\n start = 0\n end = 0\n counter = 0\n store = {'a' : 0, 'b' : 0, 'c' : 0}\n\n for end in range(len(s)):\n store[s[end]] += 1\n\n while store['a'] > 0 and store['b'] > 0 and store['c'] > 0:\n counter += (len(s) - end)\n store[s[start]] -= 1\n start += 1\n\n return counter", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar numberOfSubstrings = function(s) {\n let ans = 0;\n let map = {};\n for(let i = 0, l = 0; i < s.length; i++) {\n const c = s[i];\n map[c] = (map[c] || 0) + 1;\n\n while(Object.keys(map).length == 3) {\n ans += s.length - i;\n map[s[l]]--;\n if(map[s[l]] == 0) {\n delete map[s[l]];\n }\n l++;\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int numberOfSubstrings(String s) {\n int a = 0, b = 0, c = 0, count = 0;\n for (int i = 0; i < s.length(); i++) {\n switch (s.charAt(i)) {\n case 'a': ++a; break;\n case 'b': ++b; break;\n case 'c': ++c; break;\n }\n if (a > 0 && b > 0 && c > 0) {\n while (a > 0 && b > 0 && c > 0) {\n char farLeft = s.charAt(i - a - b - c + 1);\n switch (farLeft) {\n case 'a': {\n --a;\n count += doCount(s, i);\n break;\n }\n case 'b': {\n --b;\n count += doCount(s, i);\n break;\n }\n case 'c': {\n --c;\n count += doCount(s, i);\n break;\n }\n }\n }\n }\n }\n return count;\n }\n\n private int doCount(String s, int i) {\n int count = 0;\n int n = s.length() - i;\n if (n > 0) {\n count += n;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfSubstrings(string s) {\n int i=0,j=0;\n int n = s.size();\n map mp;\n int count=0;\n while(j List[List[str]]:\n # move stones to right, row by row\n for i in range(len(box)):\n stone = 0\n for j in range(len(box[0])):\n if box[i][j] == '#': # if a stone\n stone += 1\n box[i][j] = '.'\n elif box[i][j] == '*': # if a obstacle\n for m in range(stone):\n box[i][j-m-1] = '#'\n stone = 0\n # if reaches the end of j, but still have stone\n if stone != 0:\n for m in range(stone):\n box[i][j-m] = '#'\n \n # rotate box, same as leetcode #48\n box[:] = zip(*box[::-1])\n \n return box", "solution_js": "var rotateTheBox = function(box) {\n for(let r=0; r= 0; i--) {\n for (int j = 0; j < row; j++) {\n if (res[i][j] == '#') {\n int curRow = i;\n while (curRow+1 < col && res[curRow+1][j] == '.') {\n curRow++;\n }\n if (curRow != i) {\n res[curRow][j] = '#';\n res[i][j] = '.';\n }\n }\n }\n }\n return res;\n }\n }", "solution_c": "class Solution {\npublic:\n vector> rotateTheBox(vector>& box) {\n int m = box.size();\n int n = box[0].size();\n\n vector> ans(n,vector(m,'.'));\n\n for(int i=0;i=0;--j)\n {\n if(box[i][j] == '#')\n {\n ans[--k][i] = '#';\n }\n else if(box[i][j] == '*')\n {\n k = j;\n ans[j][i] = '*';\n }\n }\n }\n for(int i=0;i int:\n alphabets = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n COL = 6\n index = { c:(i//COL, i%COL) for i, c in enumerate(alphabets)}\n def dist(a, b):\n return abs(index[a][0] - index[b][0]) + abs(index[a][1] - index[b][1])\n @cache\n def dfs(lhand, rhand, i):\n if i == len(word): return 0\n res = float('inf')\n res = min(res, dfs(word[i], rhand, i+1)) if lhand == -1 else min(res, dist(lhand, word[i])+dfs(word[i], rhand, i+1))\n res = min(res, dfs(lhand, word[i],i+1)) if rhand == -1 else min(res, dist(word[i], rhand) + dfs(lhand, word[i], i+1))\n return res\n return dfs(-1, -1, 0)", "solution_js": "const dist = function(from, to){\n if(from==-1) return 0; \n const d1 = Math.abs((from.charCodeAt(0)-65)%6-(to.charCodeAt(0)-65)%6),\n d2 = Math.abs(Math.floor((from.charCodeAt(0)-65)/6)-Math.floor((to.charCodeAt(0)-65)/6));\n return d1 + d2;\n}\nvar minimumDistance = function(word) {\n\n const dp = new Map();\n \n const dfs = function(i, lpos, rpos){\n if(i==word.length) \n return 0;\n const key = [i,lpos,rpos].join(',');\n if(dp.get(key)) \n return dp.get(key);\n dp.set(key, Math.min(dist(lpos,word[i])+dfs(i+1,word[i],rpos), dist(rpos,word[i])+dfs(i+1,lpos,word[i])));\n return dp.get(key);\n }\n return dfs(0, -1, -1);\n};", "solution_java": "class Solution {\n HashMap pos;\n int [][][]memo;\n int type(String word,int index,char finger1,char finger2){\n if (index==word.length()) return 0;\n int ans=9999999;\n if (memo[index][finger1-'A'][finger2-'A']!=-1) return memo[index][finger1-'A'][finger2-'A'];\n if (finger1=='['){\n \n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2));\n }\n else{\n \n Integer [] prev=pos.get(finger1);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,word.charAt(index),finger2)+dist);\n }\n if (finger2=='['){\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index)));\n }\n else{\n Integer [] prev=pos.get(finger2);\n Integer [] curr=pos.get(word.charAt(index));\n int dist=Math.abs(prev[0]-curr[0])+Math.abs(prev[1]-curr[1]);\n ans=Math.min(ans,type(word,index+1,finger1,word.charAt(index))+dist);\n }\n memo[index][finger1-'A'][finger2-'A']=ans;\n return ans;\n }\n public int minimumDistance(String word) {\n pos=new HashMap();\n for (int i=0;i<26;i++){\n Integer [] coord={i/6,i%6};\n pos.put((char)('A'+i),coord);\n }\n memo=new int [word.length()]['z'-'a'+3]['z'-'a'+3];\n for (int[][] row : memo) {\n for (int[] rowColumn : row) {\n Arrays.fill(rowColumn, -1);\n }\n }\n return type(word,0,'[','[');\n }\n}", "solution_c": "class Solution {\npublic:\n string alpha = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n unordered_map> m;\n int distCalc(char a, char b) {\n pair p_a = m[a];\n pair p_b = m[b];\n \n int x_diff = abs(p_a.first - p_b.first);\n int y_diff = abs(p_a.second - p_b.second);\n \n return x_diff + y_diff;\n }\n int dp[301][27][27];\n int minDist(string word, int i, char finger1_char, char finger2_char) {\n if(i == word.size()) return 0;\n \n if(dp[i][finger1_char - 'A'][finger2_char - 'A'] != -1) return dp[i][finger1_char - 'A'][finger2_char - 'A'];\n \n //finger1\n int op1 = (finger1_char == '[' ? 0 : distCalc(finger1_char, word[i])) + minDist(word, i + 1, word[i], finger2_char);\n \n //finger2\n int op2 = (finger2_char == '[' ? 0 : distCalc(finger2_char, word[i])) + minDist(word, i + 1, finger1_char, word[i]);\n \n return dp[i][finger1_char - 'A'][finger2_char - 'A'] = min(op1, op2);\n }\n int minimumDistance(string word) {\n //each letter has choice to be clicked by finger 1 or 2\n \n int row = -1;\n for(int i = 0; i < alpha.length(); i++) {\n int col = i % 6;\n if(col == 0) row++;\n m[alpha[i]] = {row, col};\n }\n memset(dp, -1, sizeof(dp));\n return minDist(word, 0, '[', '[');\n }\n};" }, { "title": "Binary Number with Alternating Bits", "algo_input": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n\n \nExample 1:\n\nInput: n = 5\nOutput: true\nExplanation: The binary representation of 5 is: 101\n\n\nExample 2:\n\nInput: n = 7\nOutput: false\nExplanation: The binary representation of 7 is: 111.\n\nExample 3:\n\nInput: n = 11\nOutput: false\nExplanation: The binary representation of 11 is: 1011.\n\n \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n bin_n = bin(n)[2:]\n for i in range(len(bin_n)-1):\n if bin_n[i] == '0' and bin_n[i+1] == '0':\n return False\n \n if bin_n[i] == '1' and bin_n[i+1] == '1':\n return False\n \n return True", "solution_js": "/**\n * @param {number} n\n * @return {boolean}\n */\nvar hasAlternatingBits = function(n) {\n let previous;\n while (n) {\n const current = n & 1;\n if (previous === current) return false;\n previous = current;\n n >>>= 1;\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean hasAlternatingBits(int n) {\n int flag = 1;\n if(n % 2 == 0) flag = 0;\n return bin(n / 2, flag);\n }\n public boolean bin(int n, int flag) {\n if(flag == n % 2) return false;\n if(n == 0) return true;\n else return bin(n / 2, n % 2);\n }\n}", "solution_c": "class Solution {\npublic:\n const static uint32_t a = 0b10101010101010101010101010101010;\n bool hasAlternatingBits(int n) {\n return ((a >> __builtin_clz(n)) ^ n) == 0;\n }\n};" }, { "title": "Implement strStr()", "algo_input": "Implement strStr().\n\nGiven two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n\nClarification:\n\nWhat should we return when needle is an empty string? This is a great question to ask during an interview.\n\nFor the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().\n\n \nExample 1:\n\nInput: haystack = \"hello\", needle = \"ll\"\nOutput: 2\n\n\nExample 2:\n\nInput: haystack = \"aaaaa\", needle = \"bba\"\nOutput: -1\n\n\n \nConstraints:\n\n\n\t1 <= haystack.length, needle.length <= 104\n\thaystack and needle consist of only lowercase English characters.\n\n", "solution_py": "class Solution(object):\n def strStr(self, haystack, needle):\n if needle == '':\n return 0\n else:\n return self.search_substring(haystack, needle)\n\n def search_substring(self, haystack, needle):\n len_substring = len(needle)\n for i in range(len(haystack)):\n if haystack[i: i + len_substring] == needle:\n return i\n return -1", "solution_js": "var strStr = function(haystack, needle) {\n return haystack.indexOf(needle)\n};", "solution_java": "class Solution {\n public int strStr(String haystack, String needle) {\n \n if(needle.length()>haystack.length()) {\n return -1;\n } \n if(needle.length()==haystack.length()) {\n if(haystack.equals(needle)) {\n return 0;\n }\n return -1;\n }\n \n \n int i=0;\n int j=0;\n while(i bool:\n m, n = len(board), len(board[0])\n W = len(word)\n \n def valid(x, y):\n return 0 <= x < m and 0 <= y < n\n \n def place(x, y, word, direction):\n dx, dy = direction\n for c in word:\n if not valid(x, y) or board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != c):\n return False\n x, y = x+dx, y+dy\n return True\n \n \n for x in range(m):\n for y in range(n):\n if board[x][y] == '#' or (board[x][y] != ' ' and board[x][y] != word[0]):\n continue\n \n # left to right\n if (not valid(x, y-1) or board[x][y-1] == '#') and (not valid(x, y+W) or board[x][y+W] == '#') and place(x, y, word, [0, 1]):\n return True\n \n # right to left\n if (not valid(x, y+1) or board[x][y+1] == '#') and (not valid(x, y-W) or board[x][y-W] == '#') and place(x, y, word, [0, -1]):\n return True\n \n # top to bottom\n if (not valid(x-1, y) or board[x-1][y] == '#') and (not valid(x+W, y) or board[x+W][y] == '#') and place(x, y, word, [1, 0]):\n return True\n \n\t\t\t\t# bottom to top\n if (not valid(x+1, y) or board[x+1][y] == '#') and (not valid(x-W, y) or board[x-W][y] == '#') and place(x, y, word, [-1, 0]):\n return True\n \n return False", "solution_js": "/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\nvar placeWordInCrossword = function(board, word) {\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n if (i === 0 || board[i - 1][j] === '#') {\n if (match(getFill(i, j, false))) {\n return true;\n }\n }\n if (j === 0 || board[i][j - 1] === '#') {\n if (match(getFill(i, j, true))) {\n return true;\n }\n }\n }\n }\n return false;\n\n function getFill(x, y, goRight) {\n if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && board[x][y] !== '#') {\n return goRight ? board[x][y] + getFill(x, y + 1, goRight) : board[x][y] + getFill(x + 1, y, goRight);\n }\n return '';\n }\n\n function match(str) {\n if (str.length !== word.length) {\n return false;\n }\n let fromLeft = true;\n let fromRight = true;\n let l = 0;\n let r = str.length - 1;\n for (let each of word) {\n if (!fromLeft && !fromRight) {\n return false;\n }\n if (fromLeft) {\n if (each !== str[l] && str[l] !== ' ') {\n fromLeft = false;\n }\n l++;\n }\n if (fromRight) {\n if (each !== str[r] && str[r] !== ' ') {\n fromRight = false;\n }\n r--;\n }\n }\n return fromLeft || fromRight;\n }\n};", "solution_java": "class Solution {\n public boolean placeWordInCrossword(char[][] board, String word) {\n String curr = \"\";\n\n Trie trie = new Trie();\n\n // Insert all horizontal strings\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n if (board[i][j] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[i][j];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n // Insert all vertical strings\n for (int i = 0; i < board[0].length; i++) {\n for (int j = 0; j < board.length; j++) {\n if (board[j][i] == '#') {\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n else {\n curr += board[j][i];\n }\n }\n insertIntoTrie(trie, curr);\n curr = \"\";\n }\n\n return trie.isPresent(word);\n }\n\n // Insert string and reverse of string into the trie\n private void insertIntoTrie(Trie trie, String s) {\n trie.insert(s);\n StringBuilder sb = new StringBuilder(s);\n sb.reverse();\n trie.insert(sb.toString());\n }\n\n class TrieNode {\n Map children;\n boolean isEnd;\n\n TrieNode() {\n children = new HashMap<>();\n isEnd = false;\n }\n\n }\n\n class Trie {\n TrieNode root;\n\n Trie() {\n root = new TrieNode();\n }\n\n void insert(String s) {\n TrieNode curr = root;\n\n for (int i = 0; i < s.length(); i++)\n {\n char c = s.charAt(i);\n if (!curr.children.containsKey(c)) {\n curr.children.put(c, new TrieNode());\n }\n\n curr = curr.children.get(c);\n }\n\n curr.isEnd = true;\n }\n\n boolean isPresent(String key) {\n TrieNode curr = root;\n return helper(key, 0, root);\n\n }\n\n boolean helper(String key, int i, TrieNode curr) {\n if (curr == null)\n return false;\n\n if (i == key.length())\n return curr.isEnd;\n\n char c = key.charAt(i);\n return helper(key, i + 1, curr.children.get(c)) || helper(key, i + 1, curr.children.get(' '));\n\n }\n }\n}", "solution_c": "class Solution {\npublic:\n bool placeWordInCrossword(vector>& board, string word) {\n int m = board.size();\n int n = board[0].size();\n for(int i = 0 ; i < m ; i++){\n for(int j = 0 ; j < n; j++){\n if(board[i][j] != '#'){\n if(valid(board, i-1, j) && check(board, word, i, j, 0, true, 1)) return true;\n if(valid(board, i+1, j) && check(board, word, i, j, 0, true, -1)) return true;\n if(valid(board, i, j-1) && check(board, word, i, j, 0, false, 1)) return true;\n if(valid(board, i, j+1) && check(board, word, i, j, 0, false, -1)) return true;\n }\n }\n }\n return false;\n }\n\n bool check(vector>& board, string &word, int x, int y, int pos, bool vertical, int inc){\n if(pos == word.size()){\n if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;\n return board[x][y] == '#';\n }\n if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return false;\n if(board[x][y] == '#') return false;\n if(board[x][y] != ' ' && board[x][y] != word[pos]) return false;\n int newx = x + vertical * inc;\n int newy = y + (!vertical) * inc;\n return check(board, word, newx, newy, pos+1, vertical, inc);\n }\n\n bool valid(vector>& board, int x, int y){\n if(x < 0 || y < 0 || x >= board.size() || y >= board[0].size()) return true;\n return board[x][y] == '#';\n }\n};" }, { "title": "Delete the Middle Node of a Linked List", "algo_input": "You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.\n\nThe middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.\n\n\n\tFor n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.\n\n\n \nExample 1:\n\nInput: head = [1,3,4,7,1,2,6]\nOutput: [1,3,4,1,2,6]\nExplanation:\nThe above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node. \n\n\nExample 2:\n\nInput: head = [1,2,3,4]\nOutput: [1,2,4]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.\n\n\nExample 3:\n\nInput: head = [2,1]\nOutput: [2]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 105].\n\t1 <= Node.val <= 105\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head: return head\n if head and not head.next: return None\n\n prev = ListNode(0, head)\n slow = fast = head\n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n\n prev.next = slow.next\n return head", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\n// Two Pointer: Fast & Slow | O(N) | O(1)\nvar deleteMiddle = function(head) {\n if (!head.next) return null;\n\n let prev = head;\n let slow = head;\n let fast = head.next;\n let size = 2;\n\n while (fast && fast.next) {\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n size += fast ? 2 : 1;\n }\n\n if (size % 2 === 0) slow.next = slow.next.next;\n else prev.next = slow.next;\n\n return head;\n};", "solution_java": "class Solution {\n public ListNode deleteMiddle(ListNode head) {\n // Base Condition\n if(head == null || head.next == null) return null;\n // Pointers Created\n ListNode fast = head;\n ListNode slow = head;\n ListNode prev = head;\n\n while(fast != null && fast.next != null){\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n }\n prev.next = slow.next;\n return head;\n }\n}", "solution_c": "**Intution**- we know that we can find middle node using two pointer fast and slow. \n After we iterate through linkedlist slow pointer is our middle node and since we need to delete it\n we only need pointer to its previous node and then just simply put next to next node in previous node.\n Woahh ! you are done with deleting middle NODE;\n\nclass Solution {\npublic:\n\tListNode* deleteMiddle(ListNode* head) {\n\t\t if(head->next==nullptr) return nullptr;\n\t\t ListNode *f=head;\n\t\t ListNode *s=head,*prev;\n\t\t while(f!=nullptr && f->next!=nullptr){\n\t\t\t f=f->next->next;\n\t\t\t prev=s;\n\t\t\t s=s->next;\n\t\t }\n\t\tprev->next=prev->next->next;\n\t\treturn head;\n\t}\n};" }, { "title": "Minimum Number of Work Sessions to Finish the Tasks", "algo_input": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.\n\nYou should finish the given tasks in a way that satisfies the following conditions:\n\n\n\tIf you start a task in a work session, you must complete it in the same work session.\n\tYou can start a new task immediately after finishing the previous one.\n\tYou may complete the tasks in any order.\n\n\nGiven tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.\n\nThe tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].\n\n \nExample 1:\n\nInput: tasks = [1,2,3], sessionTime = 3\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.\n\n\nExample 2:\n\nInput: tasks = [3,1,3,1,1], sessionTime = 8\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.\n\n\nExample 3:\n\nInput: tasks = [1,2,3,4,5], sessionTime = 15\nOutput: 1\nExplanation: You can finish all the tasks in one work session.\n\n\n \nConstraints:\n\n\n\tn == tasks.length\n\t1 <= n <= 14\n\t1 <= tasks[i] <= 10\n\tmax(tasks[i]) <= sessionTime <= 15\n\n", "solution_py": "class Solution:\n def minSessions(self, tasks, T):\n n = len(tasks)\n\n @lru_cache(None)\n def dp(mask):\n if mask == 0: return (1, 0)\n ans = (float(\"inf\"), float(\"inf\"))\n for j in range(n):\n if mask & (1< T)\n ans = min(ans, (pieces + full, tasks[j] + (1-full)*last)) \n return ans\n\n return dp((1< Array(16).fill(-1));\n \n const solve = (mask, time) => {\n if (mask === (1 << n) - 1) {\n return 1;\n }\n \n if (dp[mask][time] !== -1) {\n return dp[mask][time];\n }\n \n let min = Infinity;\n for (let i = 0; i < n; ++i) {\n if (mask & (1 << i)) {\n continue;\n }\n\n if (time >= tasks[i]) {\n min = Math.min(\n min,\n solve(mask | (1 << i), time - tasks[i]),\n );\n } else {\n min = Math.min(\n min,\n 1 + solve(mask | (1 << i), sessionTime - tasks[i]),\n );\n }\n }\n \n dp[mask][time] = min;\n return min;\n }\n \n return solve(0, sessionTime);\n};", "solution_java": "// Java Solution\nclass Solution {\n public int minSessions(int[] tasks, int sessionTime) {\n int n = tasks.length, MAX = Integer.MAX_VALUE;\n int[][] dp = new int[1< d2[0]) return d2;\n if(d1[0] < d2[0]) return d1;\n if(d1[1] > d2[1]) return d2;\n\n return d1;\n }\n}", "solution_c": "// C++ Solution\nclass Solution {\npublic:\n int minSessions(vector& tasks, int sessionTime) {\n const int N = tasks.size();\n const int INF = 1e9;\n vector> dp(1 << N, {INF, INF});\n dp[0] = {0, INF};\n for(int mask = 1; mask < (1 << N); ++mask) {\n pair best = {INF, INF};\n for(int i = 0; i < N; ++i) {\n if(mask & (1 << i)) {\n pair cur = dp[mask ^ (1 << i)];\n if(cur.second + tasks[i] > sessionTime) {\n cur = {cur.first + 1, tasks[i]};\n } else\n cur.second += tasks[i];\n best = min(best, cur);\n }\n }\n dp[mask] = best;\n }\n return dp[(1 << N) - 1].first;\n }\n};" }, { "title": "Longest Well-Performing Interval", "algo_input": "We are given hours, a list of the number of hours worked per day for a given employee.\n\nA day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.\n\nA well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.\n\nReturn the length of the longest well-performing interval.\n\n \nExample 1:\n\nInput: hours = [9,9,6,0,6,6,9]\nOutput: 3\nExplanation: The longest well-performing interval is [9,9,6].\n\n\nExample 2:\n\nInput: hours = [6,6,6]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= hours.length <= 104\n\t0 <= hours[i] <= 16\n\n", "solution_py": "class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n #accumulative count\n #+1 when > 8, -1 when less than 8. \n #find strictly increasing length.\n \n p = [] #number of tiring days vs not\n c = 0\n for e in hours:\n if e > 8:\n c +=1\n else:\n c-=1\n \n p.append(c)\n \n \n \n #for every moment: we want earliest moment which could be positive overall tiring days.\n a = []\n #a is sorted by tiringnes. At day 8 have -2, want earliest point that could get us to at least 1.\n #so up until that point we have -3, -4, etc, and we want earliest out of it to get longest well performing interval. Which is when prefix comes in.\n \n a1 =[]\n for i in range(len(p)):\n a.append([p[i], i])\n a1.append(p[i])\n \n a1.sort() #bisectable list\n a.sort()\n \n prefix = []\n currearly = float('inf')\n for t, day in a:\n currearly = min(currearly, day)\n prefix.append(currearly)\n \n \n res = 0\n \n # print(p)\n \n for i in range(len(hours)):\n if p[i] > 0:\n res = max(res, i + 1) \n \n else:\n #find earliest \n #value must be less than -1-p[i] \n loc = bisect_right(a1, -1+p[i]) #bisect right means anything before this is less than or equals to\n \n \n \n if loc == 0: #the rightmost place to put it is at the beginning...\n \n continue\n \n \n else:\n earliest = prefix[loc - 1]\n \n if earliest >= i: continue\n \n interval = i - earliest #notice: we're not including the starting index, since its also technically being removed!\n\n # print(\"From day\", earliest, \"to\", i)\n \n res = max(res, interval)\n \n \n \n return res\n \n \n \n ", "solution_js": "var longestWPI = function(hours) {\n var dp = new Array(hours.length).fill(0);\n for(i=0;i0 && hours[i]<=8){\n dp[i]=dp[i-1]-1;\n continue;\n }\n let tiring = 0;\n for(j=i;j8) tiring++;\n else tiring--;\n if(tiring>0) dp[i] = Math.max(dp[i], j-i+1);\n }}\n return Math.max(...dp);\n};", "solution_java": "// Brute Force Approach : PrefixSum ((Tiring - Non Tiring) Days) + Checking All Sliding Windows (Lengths 1 To n)\n// For Longest Well Performing Interval/Window\n// T.C. = O(n^2) , S.C. = O(n)\nclass Solution {\n \n public int longestWPI(int[] hours) {\n int n = hours.length;\n \n int[] prefixSumTiringDaysMinusNonTiringDaysArr = new int[n + 1];\n prefixSumTiringDaysMinusNonTiringDaysArr[0] = 0;\n \n int prefixSumTiringDaysCount = 0;\n int prefixSumNonTiringDaysCount = 0;\n \n for (int i = 0 ; i < n ; i++) {\n int noOfHoursWorkedToday = hours[i];\n \n if (noOfHoursWorkedToday > 8) {\n prefixSumTiringDaysCount++;\n }\n else {\n prefixSumNonTiringDaysCount++;\n }\n \n prefixSumTiringDaysMinusNonTiringDaysArr[i + 1] = prefixSumTiringDaysCount - prefixSumNonTiringDaysCount;\n // System.out.print(prefixSumTiringDaysMinusNonTiringDaysArr[i] + \" \");\n }\n // System.out.println(prefixSumTiringDaysMinusNonTiringDaysArr[n]);\n \n int longestLengthOfContinuousPositiveSequence = 0;\n \n for (int currentSlidingWindowLength = 1 ; currentSlidingWindowLength <= n ; currentSlidingWindowLength++) {\n // System.out.print(currentSlidingWindowLength + \" - \");\n for (int i = 0 ; i <= n - currentSlidingWindowLength ; i++) {\n int j = i + currentSlidingWindowLength - 1;\n // System.out.print(i + \",\" + j + \" \");\n int currentIntervalNoOfTiringDaysMinusNonTiringDays = prefixSumTiringDaysMinusNonTiringDaysArr[j + 1] - prefixSumTiringDaysMinusNonTiringDaysArr[i];\n if (currentIntervalNoOfTiringDaysMinusNonTiringDays > 0) { // => currentInterval = Well Performing Interval\n longestLengthOfContinuousPositiveSequence = Math.max(currentSlidingWindowLength, longestLengthOfContinuousPositiveSequence);\n }\n }\n // System.out.println();\n }\n // System.out.println();\n \n int lengthOfLongestWellPerformingInterval = longestLengthOfContinuousPositiveSequence;\n \n return lengthOfLongestWellPerformingInterval;\n }\n \n}", "solution_c": "class Solution {\npublic:\n\tint longestWPI(vector& hours) {\n int n = hours.size();\n\t\tint ans = 0;\n\t\tint ct = 0;\n\t\tunordered_map m;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tif (hours[i] > 8) ct++;\n\t\t\telse ct--;\n\t\t\tif (ct > 0) ans = max(ans, i + 1);\n\t\t\telse {\n\t\t\t\tif (m.find(ct) == m.end()) m[ct] = i;\n\t\t\t\tif (m.find(ct - 1) != m.end()) ans = max(ans, i - m[ct - 1]);\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n};" }, { "title": "Shortest Subarray with Sum at Least K", "algo_input": "Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.\n\nA subarray is a contiguous part of an array.\n\n \nExample 1:\nInput: nums = [1], k = 1\nOutput: 1\nExample 2:\nInput: nums = [1,2], k = 4\nOutput: -1\nExample 3:\nInput: nums = [2,-1,2], k = 3\nOutput: 3\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-105 <= nums[i] <= 105\n\t1 <= k <= 109\n\n", "solution_py": "# 1. we can not use sliding window to solve the problem, because the numbers in nums can be negative, \n# the numbers in sliding window are not always incrementing\n# ex [8,-4,3,1,6], 10\n\n# 2. prefixsum2 - prefixsum1 >= k is used to find a subarray whose sum >= k.\n# 3. monotonic queue is used to keep the prefix sums are in the incrementing order\n# 4. If the diffenence between the cur and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n\nclass Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n prefixsum = [0]\n monoq = deque()\n minLen = float('inf')\n # to calculate prefix sum\n for n in nums:\n prefixsum.append(n+prefixsum[-1])\n for idx, cur in enumerate(prefixsum):\n while monoq and prefixsum[monoq[-1]] >= cur: monoq.pop() # to maintain monotonic queue\n\n # If the diffenence between the head and the tail of monotonic queue is greater than or equal to k, we can find the shortest length of the subarray at this time.\n while monoq and cur-prefixsum[monoq[0]]>=k: \n minLen = min(minLen, idx-monoq.popleft())\n monoq.append(idx)\n return -1 if minLen == float('inf') else minLen", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar DoublyLinkedList = function(sum = \"DUMMY\", index = \"DUMMY\") {\n this.property = {sum, index}\n this.prev = null\n this.next = null\n}\n\nDoublyLinkedList.prototype.deque = function() {\n const dequeNode = this.next\n\n this.next = dequeNode.next\n dequeNode.next.prev = this\n\n dequeNode.next = null\n dequeNode.prev = null\n return dequeNode\n}\n\nDoublyLinkedList.prototype.pop = function() {\n const dequeNode = this.prev\n\n this.prev = dequeNode.prev\n dequeNode.prev.next = this\n\n dequeNode.next = null\n dequeNode.prev = null\n return dequeNode\n}\n\nDoublyLinkedList.prototype.push = function(node) {\n const prev = this.prev\n const next = this\n\n node.prev = prev\n node.next = next\n\n prev.next = node\n next.prev = node\n}\n\nvar shortestSubarray = function(nums, k) {\n // Steps :-\n // Initalize 3 vaiables :- sum = 0, subArrayLength = Infinity, queue -> []\n\n const dummyHead = new DoublyLinkedList()\n const dummyTail = new DoublyLinkedList()\n dummyHead.next = dummyTail\n dummyTail.prev = dummyHead\n\n let queueSize = 0\n\n let subArraySize = Number.MAX_SAFE_INTEGER\n let sum = 0\n for (let i = 0; i < nums.length; i++) {\n sum += nums[i]\n\n // Gives one possible answer, if sum is greater than or\n // equal to k\n if (sum >= k)\n subArraySize = Math.min(subArraySize, i+1)\n\n let lastDequeued\n\n // Reduce the queue from left till the sum of elements from\n // first index of queue till last index of queue is less than k\n // Each time we constantly update the lastdequeued element\n // As the last lastdequeued will satisfy sum - lastDequeued.sum >= k\n // Thus the range would be i-lastDequeued.property.index\n // (without lastDequeued.property.index)\n while (queueSize > 0 && sum - dummyHead.next.property.sum >= k) {\n queueSize--\n lastDequeued = dummyHead.deque()\n }\n\n // Using the lastDequeued value to check\n if (lastDequeued !== undefined) {\n subArraySize = Math.min(subArraySize, i-lastDequeued.property.index)\n }\n\n // Maintaining the monotonic queue\n while (queueSize > 0 && sum <= dummyTail.prev.property.sum) {\n queueSize--\n dummyTail.pop()\n }\n\n const newNode = new DoublyLinkedList(sum, i)\n\n dummyTail.push(newNode)\n queueSize++\n }\n return subArraySize === Number.MAX_SAFE_INTEGER ? -1 : subArraySize\n};", "solution_java": "class Solution {\n public int shortestSubarray(int[] nums, int k) {\n \n TreeMap maps = new TreeMap<>();\n long sum = 0l;\n int min = nums.length + 1;\n\t\t \n maps.put(0l, -1);\n \n for(int i = 0; i < nums.length; i++) {\n sum += nums[i];ntry(sum - k) != null) \n\t\t\t min = Math.min(min, i - maps.floorEntry(sum - k).getValue()); \n while(!maps.isEmpty() && maps.lastEntry().getKey() >= sum) \n\t\t\t maps.remove(maps.lastEntry().getKey());\n \n maps.put(sum, i);\n }\n \n return min == (nums.length + 1) ? -1 : min;\n }\n}", "solution_c": "class Solution {\npublic:\n //2-pointer doesnt work on neg elements\n //Using mono deque to solve sliding window\n int shortestSubarray(vector& nums, int k) {\n int n = nums.size();\n int minsize = INT_MAX;\n vector prefixsum(n,0);\n deque dq;\n\n prefixsum[0] = nums[0];\n for(int i = 1;i=k)\n minsize = min(minsize,i+1);\n\n while(!dq.empty() && prefixsum[i]-prefixsum[dq.front()]>=k){\n minsize = min(minsize,i-dq.front());\n dq.pop_front();\n }\n\n while(!dq.empty() && prefixsum[i]<=prefixsum[dq.back()]){\n dq.pop_back();\n }\n\n dq.push_back(i);\n }\n return (minsize==INT_MAX) ? -1 : minsize;\n }\n};" }, { "title": "Find XOR Sum of All Pairs Bitwise AND", "algo_input": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.\n\n\n\tFor example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.\n\n\nYou are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.\n\nConsider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.\n\nReturn the XOR sum of the aforementioned list.\n\n \nExample 1:\n\nInput: arr1 = [1,2,3], arr2 = [6,5]\nOutput: 0\nExplanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\n\n\nExample 2:\n\nInput: arr1 = [12], arr2 = [4]\nOutput: 4\nExplanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n\n\n \nConstraints:\n\n\n\t1 <= arr1.length, arr2.length <= 105\n\t0 <= arr1[i], arr2[j] <= 109\n\n", "solution_py": "class Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n def xor_lis(lis): return functools.reduce(lambda a,b : a^b,lis)\n return xor_lis(arr1) & xor_lis(arr2)", "solution_js": "var getXORSum = function(arr1, arr2) {\n // (x & 2) xor (x & 3) =[ !(x&2) & (x&3) ] OR [ (x&2) & !(x&3) ]\n\t// = [ (!x || !2 ) & (x&3) ] OR [ (x&2) & (!x || !3) ]\n // = [ (!x || !2) & x & 3 ] OR [ x & 2 & (!x || !3) ]\n // = (!2 & x & 3 ) || (x & 2 & !3)\n // = x & [ (!2 & 3) || (!3 & 2) ]\n // = x & (2 XOR 3)\n // const ans = (2 XOR 3 XOR....) in arr2\n // The same principle: x, y,z... in arr1\n // res = (x & ans) XOR (y & ans) XOR .....\n // = ans & (x XOR y XOR z .......)\n // Finally: res = (XOR: arr1) AND (XOR: arr2);\n var xor1 = arr1.reduce((acc,cur)=>acc^cur);\n var xor2 = arr2.reduce((acc,cur)=>acc^cur);\n return xor1 & xor2;\n};", "solution_java": "class Solution {\n\n public int getXORSum(int[] arr1, int[] arr2) {\n int[] x = (arr1.length < arr2.length ? arr2 : arr1);\n int[] y = (arr1.length < arr2.length ? arr1 : arr2);\n int xorSumX = 0;\n for (int xi : x) {\n xorSumX ^= xi;\n }\n int answer = 0;\n for (int yj : y) {\n answer ^= (yj & xorSumX);\n }\n return answer;\n }\n\n}", "solution_c": "class Solution {\npublic:\n // this code is basically pure mathematics, mainly distributive property with AND and XOR\n \n int getXORSum(vector& arr1, vector& arr2) {\n int m=arr1.size();\n int n=arr2.size();\n long int ans1=0,ans2=0;\n for(int i=0;i List[int]:\n return list(str(int(\"\".join(map(str,num)))+k))", "solution_js": "var addToArrayForm = function(num, k) {\n const length = num.length;\n let digit = 0, index = length-1;\n while(k > 0 || digit > 0) {\n if(index >= 0) {\n digit = digit + num[index] + k%10;\n num[index] = digit%10;\n }\n else {\n digit = digit + k%10;\n num.unshift(digit%10);\n }\n digit = digit > 9 ? 1 : 0;\n k = parseInt(k/10);\n index--;\n }\n if(digit) num.unshift(digit);\n return num;\n};", "solution_java": "class Solution {\n public List addToArrayForm(int[] num, int k) {\n List res = new ArrayList<>();\n \n int i = num.length;\n while(--i >= 0 || k > 0) {\n if(i >= 0)\n k += num[i];\n \n res.add(k % 10);\n k /= 10;\n }\n Collections.reverse(res);\n \n return res;\n }\n}", "solution_c": "Time: O(max(n,Log k)) Space: O(1)\n\nclass Solution {\npublic:\n vector addToArrayForm(vector& num, int k) {\n vector res;\n int i=size(num)-1;\n int c=0,sum;\n while(i>=0){\n sum=num[i]+k%10+c;\n res.push_back(sum%10);\n c=sum/10;\n k/=10;i--;\n }\n while(k){\n sum=k%10+c;\n res.push_back(sum%10);\n c=sum/10;\n k/=10;\n }\n if(c)\n res.push_back(c);\n reverse(begin(res),end(res));\n return res;\n }\n};\n\n--> Approach 2 \n\nclass Solution {\npublic:\n vector addToArrayForm(vector& num, int k) {\n vector res;\n int i=size(num)-1;\n int sum;\n while(i>=0){\n sum=num[i]+k;\n res.push_back(sum%10);\n k=sum/10;i--;\n }\n while(k){\n res.push_back(k%10);\n k/=10;\n }\n reverse(begin(res),end(res));\n return res;\n }\n};" }, { "title": "Best Team With No Conflicts", "algo_input": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.\n\nHowever, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.\n\nGiven two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.\n\n \nExample 1:\n\nInput: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput: 34\nExplanation: You can choose all the players.\n\n\nExample 2:\n\nInput: scores = [4,5,6,5], ages = [2,1,2,1]\nOutput: 16\nExplanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\n\n\nExample 3:\n\nInput: scores = [1,2,3,5], ages = [8,9,10,1]\nOutput: 6\nExplanation: It is best to choose the first 3 players. \n\n\n \nConstraints:\n\n\n\t1 <= scores.length, ages.length <= 1000\n\tscores.length == ages.length\n\t1 <= scores[i] <= 106\n\t1 <= ages[i] <= 1000\n\n", "solution_py": "class Solution(object):\n def bestTeamScore(self, scores, ages):\n \"\"\"\n :type scores: List[int]\n :type ages: List[int]\n :rtype: int\n \"\"\"\n l = len(scores)\n mapped = [[ages[i], scores[i]] for i in range(l)]\n mapped = sorted(mapped, key = lambda x : (x[0], x[1]))\n dp = [i[1] for i in mapped]\n\n for i in range(l):\n for j in range(0, i):\n if mapped[j][1] <= mapped[i][1]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n elif mapped[i][0] == mapped[j][0]:\n dp[i] = max(dp[i], mapped[i][1] + dp[j])\n\n return max(dp)", "solution_js": "var bestTeamScore = function(scores, ages) {\n const players = scores.map((score, index) => ({ score, age: ages[index] }))\n .sort((a,b) => a.score === b.score ? a.age - b.age : a.score - b.score);\n let memo = new Array(scores.length).fill(0).map(_ => new Array());\n return dfs(0, 0);\n \n function dfs(maxAge, index) {\n if (index === players.length) {\n return 0;\n }\n \n if (memo[index][maxAge] !== undefined) {\n return memo[index][maxAge];\n }\n \n let max = 0;\n let currentPlayer = players[index];\n\n // cannot take because I'm too young and better than an old guy in my team\n if (currentPlayer.age < maxAge) {\n memo[index][maxAge] = dfs(maxAge, index + 1)\n return memo[index][maxAge];\n }\n \n // take\n max = Math.max(max, currentPlayer.score + dfs(Math.max(maxAge, currentPlayer.age), index + 1));\n \n // not take\n max = Math.max(max, dfs(maxAge, index + 1));\n \n memo[index][maxAge] = max;\n return max;\n }\n};", "solution_java": "class Solution {\n public int bestTeamScore(int[] scores, int[] ages) {\n int n = scores.length;\n // combine the arrays for ease in processing\n int[][] combined = new int[n][2];\n for (int i = 0; i < n; i++) {\n combined[i][0] = ages[i];\n combined[i][1] = scores[i];\n }\n \n // sort the arrays by age and scores\n Arrays.sort(combined, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n \n\t\t// find max answer between all possible teams\n int ans = 0;\n for (int i = 0; i < n; i++)\n ans = Math.max(ans, recurse(combined, i));\n \n return ans;\n }\n \n private int recurse(int[][] combined, int cur) {\n // base case\n if (cur == -1)\n return 0;\n \n // try teaming player with others if no conflict found\n int ans = 0;\n for (int prev = 0; prev < cur; prev++) {\n if (combined[cur][0] == combined[prev][0] || combined[cur][1] >= combined[prev][1])\n ans = Math.max(ans, recurse(combined, prev));\n }\n \n // add score of current player\n ans += combined[cur][1];\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[1005][1005];\n int bestTeamScore(vector& scores, vector& ages) {\n vector>grp;\n for(int i=0;i>&grp , int i , int n , int maxiAge)\n {\n if(i==n)\n return 0;\n if(dp[i][maxiAge]!=-1)\n return dp[i][maxiAge];\n // score is already greater than previous socre we need to check age \n // if current age is greater than previous maxiAge then two choices\n if(grp[i][1]>=maxiAge)\n {\n return dp[i][maxiAge] = max(grp[i][0]+recur(grp,i+1,n,grp[i][1]),recur(grp,i+1,n,maxiAge));\n }\n return dp[i][maxiAge] = recur(grp,i+1,n,maxiAge);\n }\n};" }, { "title": "Reduce Array Size to The Half", "algo_input": "You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.\n\nReturn the minimum size of the set so that at least half of the integers of the array are removed.\n\n \nExample 1:\n\nInput: arr = [3,3,3,3,5,5,5,2,2,7]\nOutput: 2\nExplanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\n\n\nExample 2:\n\nInput: arr = [7,7,7,7,7,7]\nOutput: 1\nExplanation: The only possible set you can choose is {7}. This will make the new array empty.\n\n\n \nConstraints:\n\n\n\t2 <= arr.length <= 105\n\tarr.length is even.\n\t1 <= arr[i] <= 105\n\n", "solution_py": "class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n n = len(arr)\n half = n // 2\n \n c = Counter(arr)\n s = 0\n ans = 0\n \n for num, occurances in c.most_common():\n s += occurances\n ans += 1\n if s >= half:\n return ans\n return ans", "solution_js": "var minSetSize = function(arr) {\n let halfSize = arr.length / 2;\n const numsCount = Object.values(getNumsCount(arr)).sort((a, b) => b - a); // get the frequencies in an array sorted in descending order\n let setSize = 0;\n if (numsCount[0] >= halfSize) return 1; // if the highest frequency is greater than or equal to half of the array size, then you already have your smallest set size of 1\n for (let i = 0; i < numsCount.length; i++) {\n let numCount = numsCount[i];\n if (halfSize > 0) {\n setSize++;\n halfSize -= numCount;\n } else {\n return setSize;\n };\n };\n};\n\nvar getNumsCount = function (arr) {\n let eleCounts = {};\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n if (!eleCounts[num]) {\n eleCounts[num] = 1;\n } else {\n eleCounts[num]++;\n };\n };\n return eleCounts;\n};", "solution_java": "class Solution {\n public int minSetSize(int[] arr) {\n int size=arr.length;\n int deletedSize=0;\n int countIteration=0;\n Map hashMap=new HashMap<>();\n Queue> queue=new PriorityQueue<>((a,b)->b.getValue()-a.getValue());\n \n for(int i=0;i entry:hashMap.entrySet())\n {\n queue.add(entry);\n }\n \n while(!queue.isEmpty())\n {\n int totalOccurence=queue.poll().getValue();\n deletedSize+=totalOccurence; \n countIteration++;\n if(deletedSize>=size/2)\n return countIteration;\n \n }\n return countIteration;\n }\n}", "solution_c": "class Solution {\npublic:\n int minSetSize(vector& arr) {\n const int n=1e5+10 ;\n int a[n]={0} ;\n for(int i=0 ;i maxh ;\n for(int i=0; i bool:\n self.parent = {}\n self.findParent(root)\n parent = self.parent[x]\n node = root if root.val == x else parent.left if parent and parent.left and parent.left.val == x else parent.right\n up = self.traverse(parent,{node:True})\n left = self.traverse(node.left,{node:True})\n right = self.traverse(node.right,{node:True})\n return (up > left + right) or (left > up + right) or (right > up + left)", "solution_js": "var left, right, val;\nvar btreeGameWinningMove = function(root, n, x) {\n function count(node) {\n if (node == null)\n return 0;\n var l = count(node.left);\n var r = count(node.right);\n if (node.val == val) {\n left = l;\n right = r;\n }\n return l + r + 1;\n }\n val = x;\n count(root);\n return Math.max(n - left - right - 1, Math.max(left, right)) > n / 2;\n};", "solution_java": "\tclass Solution {\n\tint xkaLeft=0,xkaRight=0;\n\tpublic int size(TreeNode node, int x)\n\t{\n\t\tif(node==null)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\tint ls=size(node.left,x);\n\t\tint rs=size(node.right,x);\n\n\t\tif(node.val==x)\n\t\t{\n\t\t\txkaLeft=ls;\n\t\t\txkaRight=rs;\n\t\t}\n\n\t\treturn ls+rs+1;\n\t}\n\tpublic boolean btreeGameWinningMove(TreeNode root, int n, int x) {\n\n\t\tsize(root,x);\n\t\tint parent=n-(xkaLeft+xkaRight+1);\n\t\tint max=Math.max(parent,Math.max(xkaRight,xkaLeft));\n\t\tif(max>n/2)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}", "solution_c": "class Solution {\npublic:\n // nodex means \"node with val = x\" \n // Idea behind this is to block either nodex's parent or it's left child or right child. Block means we will chose that node as nodey. Why? because it will devide the tree in two parts, one for player 1 and other for player 2. Then we have to just take the maximum no of nodes we can get, from these three nodes as head, and if max is greater than n/2, means we can will.\n TreeNode *nodex, *parentx;\n Solution(){\n nodex = NULL;\n parentx = NULL;\n }\n int count(TreeNode *root)\n {\n if (root == NULL)\n return 0;\n int a = count(root->left);\n int b = count(root->right);\n return a + b + 1;\n }\n bool findx(TreeNode *root, int x)\n {\n if (root == NULL)\n return false;\n parentx = root;\n if (root->val == x)\n {\n nodex = root;\n return true; \n }\n bool a = findx(root->left, x);\n if (a)\n return true;\n bool b = findx(root->right, x);\n return b;\n }\n bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n findx(root, x); // Find the node which has val = x\n int p = n - count(nodex); // Count the no of nodes of blue color, if we decide to take parent of nodex as nodey\n int r = count(nodex->right); // Count the no of nodes of blue color, if we decide to take right child of nodex as nodey\n int l = count(nodex->left); // Count the no of nodes of blue color, if we decide to take left child of nodex as nodey\n int mx = max(p,r);\n mx = max(mx, l); // max of all three possible scenarios\n if (mx > n/2)\n return true;\n else\n return false;\n }\n};" }, { "title": "Word Search", "algo_input": "Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n\nThe word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.\n\n \nExample 1:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\nOutput: true\n\n\nExample 2:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\nOutput: true\n\n\nExample 3:\n\nInput: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\nOutput: false\n\n\n \nConstraints:\n\n\n\tm == board.length\n\tn = board[i].length\n\t1 <= m, n <= 6\n\t1 <= word.length <= 15\n\tboard and word consists of only lowercase and uppercase English letters.\n\n\n \nFollow up: Could you use search pruning to make your solution faster with a larger board?\n", "solution_py": "class Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n m = len(board)\n n = len(board[0])\n \n marked = set() # visited by the dfs\n def dfs(cell: Tuple[int, int], wp: int) -> bool:\n i = cell[0]\n j = cell[1]\n \n if wp == len(word):\n return True\n \n # Get appropriate neighbours and perform dfs on them\n # When going on dfs, we mark certain cells, we should remove # \n #them from the marked list after we return from the dfs\n marked.add((i,j))\n neibs = [(i - 1, j), (i, j - 1), (i + 1, j), (i, j + 1)]\n for x, y in neibs:\n if (\n x < 0 or y < 0 or\n x >= m or y >= n or\n (x, y) in marked or\n board[x][y] != word[wp]\n ):\n continue\n \n if dfs((x,y), wp + 1):\n return True\n \n marked.remove((i,j))\n return False\n \n \n for i in range(m):\n for j in range(n):\n if board[i][j] == word[0]:\n if dfs((i,j), 1):\n return True\n \n return False", "solution_js": "/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\n\nlet visited\n\nconst getNeighbours=([i,j],board)=>{\n let arr=[];\n if(i>0 && !visited[i-1][j])arr.push([i-1,j])\n if(j>0 && !visited[i][j-1])arr.push([i,j-1])\n if(i+1{\n if(word[index]!==board[i][j])return false;\n if(word.length-1===index)return true;\n visited[i][j]=true;\n let neighbours=getNeighbours([i,j],board,word,index)||[];\n\n for(let k=0;k=board.length || cd>=board[0].length\n || vis[rd][cd]==true ||\n board[rd][cd]!=word.charAt(idx)) continue;\n boolean is=isexist(rd,cd,board,vis,idx+1,word);\n if(is) return true;\n }\n vis[r][c]=false;\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool solve(int i,int j,int &m,int &n,vector> &board,string &str,int s){\n if(s>=str.length()){\n return true;\n }\n if(i<0||j<0||i>=m||j>=n||board[i][j]=='#'){\n return false;\n }\n char c = board[i][j];\n board[i][j] = '#';\n bool a = false;\n if(c==str[s])\n a = solve(i+1,j,m,n,board,str,s+1)||solve(i-1,j,m,n,board,str,s+1)||solve(i,j-1,m,n,board,str,s+1) || solve(i,j+1,m,n,board,str,s+1);\n board[i][j] = c;\n return a;\n }\n bool exist(vector>& board, string word) {\n int i,j,m=board.size(),n=board[0].size();\n for(i = 0; i < m; i++){\n for(j = 0; j < n; j++){\n if(board[i][j]==word[0] && solve(i,j,m,n,board,word,0)){\n return true;\n }\n }\n }\n return false;\n }\n};" }, { "title": "Subsets II", "algo_input": "Given an integer array nums that may contain duplicates, return all possible subsets (the power set).\n\nThe solution set must not contain duplicate subsets. Return the solution in any order.\n\n \nExample 1:\nInput: nums = [1,2,2]\nOutput: [[],[1],[1,2],[1,2,2],[2],[2,2]]\nExample 2:\nInput: nums = [0]\nOutput: [[],[0]]\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 10\n\t-10 <= nums[i] <= 10\n\n", "solution_py": "class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n ans = []\n nums.sort()\n def subset(p, up):\n if len(up) == 0:\n if p not in ans:\n ans.append(p)\n return \n ch = up[0]\n subset(p+[ch], up[1:])\n subset(p, up[1:])\n subset([], nums)\n return ans", "solution_js": "var subsetsWithDup = function(nums) {\n let result = [];\n //sort the nums to avoid duplicates;\n nums.sort((a,b) => a -b);\n result.push([]);\n\n let startIdx = 0;\n let endIdx = 0;\n\n for(let i =0; i 0 && nums[i] === nums[i-1]){\n startIdx = endIdx +1;\n }\n endIdx = result.length - 1;\n\n for(let j = startIdx; j< endIdx+1; j++){\n let set1 = result[j].slice(0);\n set1.push(current);\n result.push(set1);\n }\n }\n\n return result;\n\n};", "solution_java": "class Solution {\n public List> subsetsWithDup(int[] nums) {\n // Sort the input array to handle duplicates properly\n Arrays.sort(nums);\n // Start the recursion with an empty prefix list\n return subset(new ArrayList(), nums);\n }\n \n // Recursive function to generate subsets\n public List> subset(ArrayList prefix, int[] nums) {\n List> result = new ArrayList<>();\n \n // Base case: If there are no elements in nums, add the current prefix to result\n if (nums.length == 0) {\n result.add(new ArrayList<>(prefix));\n return result;\n }\n \n // Include the first element of nums in the prefix\n ArrayList withCurrent = new ArrayList<>(prefix);\n withCurrent.add(nums[0]);\n \n // Recursive call with the first element included\n List> left = subset(withCurrent, Arrays.copyOfRange(nums, 1, nums.length));\n \n List> right = new ArrayList<>();\n \n // Check for duplicates in the prefix and decide whether to include the first element again\n if (prefix.size() > 0 && prefix.get(prefix.size() - 1) == nums[0]) {\n // If the current element is a duplicate, don't include it in the prefix\n // This avoids generating duplicate subsets\n } else {\n // If the current element is not a duplicate, include it in the prefix\n right = subset(prefix, Arrays.copyOfRange(nums, 1, nums.length));\n }\n \n // Combine the subsets with and without the current element\n left.addAll(right);\n return left;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> ans;\n void recur(vector& nums, int i, vector vec){\n if(i > nums.size()){\n return;\n }\n for(int j = i; j < nums.size(); j++){\n vec.push_back(nums[j]);\n\n vector temp = vec;\n sort(vec.begin(), vec.end());\n\n if(find(ans.begin(), ans.end(), vec) == ans.end()){\n ans.push_back(vec);\n }\n\n recur(nums, j + 1, vec);\n\n //can't just pop_back any need to pop_back the one we added\n vec = temp;\n vec.pop_back();\n }\n }\n\n vector> subsetsWithDup(vector& nums) {\n vector vec;\n ans.push_back(vec);\n recur(nums, 0, vec);\n\n return ans;\n }\n};" }, { "title": "Score of Parentheses", "algo_input": "Given a balanced parentheses string s, return the score of the string.\n\nThe score of a balanced parentheses string is based on the following rule:\n\n\n\t\"()\" has score 1.\n\tAB has score A + B, where A and B are balanced parentheses strings.\n\t(A) has score 2 * A, where A is a balanced parentheses string.\n\n\n \nExample 1:\n\nInput: s = \"()\"\nOutput: 1\n\n\nExample 2:\n\nInput: s = \"(())\"\nOutput: 2\n\n\nExample 3:\n\nInput: s = \"()()\"\nOutput: 2\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 50\n\ts consists of only '(' and ')'.\n\ts is a balanced parentheses string.\n\n", "solution_py": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n \n level = 0\n result = 0\n prev = \"\"\n \n for c in s: \n if c == \"(\":\n level += 1\n if c == \")\":\n if prev == \"(\":\n result += 2 ** (level - 1)\n level -= 1 \n prev = c\n \n return result", "solution_js": "var scoreOfParentheses = function(s) {\n let len = s.length, pwr = 0, ans = 0;\n\n for (let i = 1; i < len; i++){\n if (s.charAt(i) === \"(\"){\n pwr++;\n }\n else if (s.charAt(i-1) === \"(\"){\n ans += 1 << pwr--;\n }\n else{\n pwr--;\n }\n }\n\n return ans;\n}", "solution_java": "class Solution {\n public int scoreOfParentheses(String s) {\n Stack st = new Stack<>();\n int score = 0;\n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(ch == '('){\n st.push(score);\n score = 0;\n }\n else {\n score = st.pop() + Math.max(2 * score, 1);\n }\n }\n return score;\n }\n}", "solution_c": "class Solution {\npublic:\n int scoreOfParentheses(string s) {\n stack st;\n int score = 0;\n for(int i = 0; i < s.size(); i++){\n if(s[i] == '('){\n st.push(score);\n score = 0;\n }\n else {\n score = st.top() + max(2 * score, 1);\n st.pop();\n }\n }\n return score;\n }\n};" }, { "title": "Implement Magic Dictionary", "algo_input": "Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.\n\nImplement the MagicDictionary class:\n\n\n\tMagicDictionary() Initializes the object.\n\tvoid buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.\n\tbool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.\n\n\n \nExample 1:\n\nInput\n[\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n[[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]\nOutput\n[null, null, false, true, false, false]\n\nExplanation\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([\"hello\", \"leetcode\"]);\nmagicDictionary.search(\"hello\"); // return False\nmagicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\nmagicDictionary.search(\"hell\"); // return False\nmagicDictionary.search(\"leetcoded\"); // return False\n\n\n \nConstraints:\n\n\n\t1 <= dictionary.length <= 100\n\t1 <= dictionary[i].length <= 100\n\tdictionary[i] consists of only lower-case English letters.\n\tAll the strings in dictionary are distinct.\n\t1 <= searchWord.length <= 100\n\tsearchWord consists of only lower-case English letters.\n\tbuildDict will be called only once before search.\n\tAt most 100 calls will be made to search.\n\n", "solution_py": "class MagicDictionary:\n\n\tdef __init__(self):\n\t\tTrieNode = lambda : defaultdict(TrieNode)\n\t\tself.root = TrieNode()\n\n\tdef buildDict(self, dictionary: List[str]) -> None:\n\t\tfor s in dictionary:\n\t\t\tcur = self.root\n\t\t\tfor c in s: cur = cur[ord(c)-ord('a')]\n\t\t\tcur['$']=True\n\n\tdef search(self, searchWord: str) -> bool:\n\t\tdef find(i,cur,mis):\n\t\t\tif i==len(searchWord) and mis==0: return('$' in cur)\n\t\t\tif mis < 0: return False\n\t\t\tif i==len(searchWord) and mis!=0: return False\n\t\t\tind = ord(searchWord[i])-ord('a')\n\t\t\tans = False\n\t\t\tfor j in range(26):\n\t\t\t\tif j in cur:\n\t\t\t\t\tif(j!=ind):\n\t\t\t\t\t\tans |= find(i+1,cur[j],mis-1)\n\t\t\t\t\telse: ans |= find(i+1,cur[j],mis)\n\t\t\treturn ans\n\t\t\t\n\t\treturn find(0,self.root,1)", "solution_js": "function TrieNode(){\n this.children = new Map()\n this.endOfWord = false;\n}\n\nvar MagicDictionary = function() {\n this.root = new TrieNode()\n};\n\nMagicDictionary.prototype.buildDict = function(dictionary) {\n for(let word of dictionary){\n let curr = this.root\n for(let letter of word){\n let map = curr.children\n if(!map.has(letter)) map.set(letter, new TrieNode())\n curr = map.get(letter)\n }\n curr.endOfWord = true\n }\n};\n\nMagicDictionary.prototype.search = function(searchWord){\n return dfs(this.root, searchWord, 0, 0)\n}\n\nfunction dfs(root, str, i, count){\n if(count>1) return false\n if(i==str.length) return count == 1 && root.endOfWord\n\t\n for(let [char, node] of root.children){\n let c = 0;\n if(char != str[i]) c = 1\n if(dfs(node, str, i+1, count+c)) return true;\n }\n return false\n}", "solution_java": "class MagicDictionary {\n private String[] dictionary;\n \n public MagicDictionary() {}\n \n public void buildDict(String[] dictionary) {\n this.dictionary = dictionary;\n }\n \n public boolean search(String searchWord) {\n for (String dictWord: this.dictionary) {\n if (this.match(searchWord, dictWord, 1))\n return true;\n }\n \n return false;\n }\n \n private boolean match(String s, String t, int expectedDiff) {\n if (s.length() != t.length())\n return false;\n \n int diff = 0;\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) != t.charAt(i))\n diff++;\n if (diff > expectedDiff)\n return false;\n }\n \n return diff == expectedDiff;\n }\n}\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dictionary);\n * boolean param_2 = obj.search(searchWord);\n */", "solution_c": "struct node{\n\tbool end = false;\n\tnode *children[26];\n};\n\nclass MagicDictionary {\npublic:\n\n\tnode* root;\n\tvoid insert(string&s){\n\t\tnode* cur = root;\n\t\tfor(char&c : s){\n\t\t\tif(!cur->children[c-'a']){\n\t\t\t\tcur->children[c-'a'] = new node();\n\t\t\t}\n\t\t\tcur = cur->children[c-'a'];\n\t\t}\n\t\tcur->end=true;\n\t}\n\tMagicDictionary() {\n\t\troot = new node();\n\t}\n\n\tvoid buildDict(vector dictionary) {\n\t\tfor(string&s : dictionary)insert(s);\n\t}\n\t\n\tbool find(int i, string& s,node* cur, int mismatch){\n\t\tif(i == s.size() and mismatch==0) return cur->end;\n\t\tif(mismatch<0)return false;\n\t\tif((!cur || i == s.size()) and mismatch!=0) return false;\n\n\t\tint ind = s[i]-'a';\n\t\tbool ans = false;\n\t\tfor(int j=0;j<26;j++){\n\t\t\tif(cur->children[j]){\n\t\t\t\tif(j!=ind){\n\t\t\t\t\tans |= find(i+1,s,cur->children[j],mismatch-1);\n\t\t\t\t}else{\n\t\t\t\t\tans |= find(i+1,s,cur->children[j],mismatch);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\tbool search(string searchWord) {\n\t\treturn find(0,searchWord,root,1);\n\t}\n};" }, { "title": "Reorder Routes to Make All Paths Lead to the City Zero", "algo_input": "There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.\n\nRoads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.\n\nThis year, there will be a big event in the capital (city 0), and many people want to travel to this city.\n\nYour task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.\n\nIt's guaranteed that each city can reach city 0 after reorder.\n\n \nExample 1:\n\nInput: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput: 3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\nExample 2:\n\nInput: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput: 2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\nExample 3:\n\nInput: n = 3, connections = [[1,0],[2,0]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t2 <= n <= 5 * 104\n\tconnections.length == n - 1\n\tconnections[i].length == 2\n\t0 <= ai, bi <= n - 1\n\tai != bi\n\n", "solution_py": "from collections import defaultdict\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n count, stack, visited = 0, [ 0 ], set() #Add root node to stack\n neighbours = defaultdict(list) #To store neighbours\n\t\tadjacency = defaultdict(list) #To store adjacency\n for i, j in connections:\n adjacency[i].append(j)\n neighbours[i].append(j)\n neighbours[j].append(i)\n while stack:\n current = stack.pop()\n if current in visited:\n continue\n else:\n visited.add(current)\n for i in neighbours[current]:\n if i in visited:\n continue\n if current not in adjacency[i]:\n count += 1\n stack.append(i)\n return count", "solution_js": "var minReorder = function(n, connections) {\n // from: (, [])\n // to: (, [])\n const from = new Map(), to = new Map();\n\n // Function to insert in values in map\n const insert = (map, key, value) => {\n if(map.has(key)){\n const arr = map.get(key);\n arr.push(value);\n map.set(key, arr);\n } else {\n map.set(key, [value]);\n }\n }\n\n // Set all values in both maps\n for(const [a,b] of connections){\n insert(from, a, b);\n insert(to, b, a);\n }\n\n // Queue: cities to visit\n const queue = [0], visited = new Set();\n let count = 0;\n\n while(queue.length) {\n const cur = queue.shift(); // First element in queue\n\n // Check values in first map\n if(from.has(cur)){\n for(const x of from.get(cur)){\n // If visited, do nothing else add to queue\n if(visited.has(x)) continue;\n queue.push(x);\n count++; // Change direction of this path\n }\n }\n\n if(to.has(cur)){\n // If visited, do nothing else add to queue\n for(const x of to.get(cur)){\n if(visited.has(x)) continue;\n queue.push(x);\n }\n }\n\n visited.add(cur); // Mark city as visited\n }\n\n return count\n};", "solution_java": "class Solution {\n int dfs(List> al, boolean[] visited, int from) {\n int change = 0;\n visited[from] = true;\n for (var to : al.get(from))\n if (!visited[Math.abs(to)])\n change += dfs(al, visited, Math.abs(to)) + (to > 0 ? 1 : 0);\n return change; \n }\n public int minReorder(int n, int[][] connections) {\n List> al = new ArrayList<>();\n for(int i = 0; i < n; ++i) \n al.add(new ArrayList<>());\n for (var c : connections) {\n al.get(c[0]).add(c[1]);\n al.get(c[1]).add(-c[0]);\n }\n return dfs(al, new boolean[n], 0);\n }\n}", "solution_c": "class Solution {\npublic:\n vector Radj[50001],adj[50001] ,visited;\n int bfs(){\n int edges = 0 ;\n queue q ;\n q.push(0) ;\n\n while(q.size()){\n auto src = q.front() ; q.pop() ;\n visited[src] = 1 ;\n\n for(auto &nbr : adj[src]){\n if(visited[nbr]) continue ;\n //this connection needs reverse orientation\n ++edges ;\n q.push(nbr) ;\n }\n\n for(auto &nbr : Radj[src]){\n if(visited[nbr]) continue ;\n q.push(nbr) ;\n }\n }\n\n return edges ;\n }\n int minReorder(int n, vector>& connections) {\n visited.resize(n,0);\n for(auto &x : connections) adj[x[0]].push_back(x[1]) , Radj[x[1]].push_back(x[0]);\n return bfs() ;\n }\n};" }, { "title": "Find the Difference of Two Arrays", "algo_input": "Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:\n\n\n\tanswer[0] is a list of all distinct integers in nums1 which are not present in nums2.\n\tanswer[1] is a list of all distinct integers in nums2 which are not present in nums1.\n\n\nNote that the integers in the lists may be returned in any order.\n\n \nExample 1:\n\nInput: nums1 = [1,2,3], nums2 = [2,4,6]\nOutput: [[1,3],[4,6]]\nExplanation:\nFor nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].\n\nExample 2:\n\nInput: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput: [[3],[]]\nExplanation:\nFor nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 1000\n\t-1000 <= nums1[i], nums2[i] <= 1000\n\n", "solution_py": "class Solution(object):\n def findDifference(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[List[int]]\n \"\"\"\n a = []\n for i in range(len(nums1)):\n if nums1[i] not in nums2:\n a.append(nums1[i])\n b = []\n for i in range(len(nums2)):\n if nums2[i] not in nums1:\n b.append(nums2[i])\n\n c = [list(set(a))] + [list(set(b))]\n\n return c", "solution_js": "var findDifference = function(nums1, nums2) {\n const s1 = new Set(nums1);\n const s2 = new Set(nums2);\n\n const a1 = [...s1].filter(x => !s2.has(x));\n const a2 = [...s2].filter(x => !s1.has(x));\n\n return [a1, a2];\n};", "solution_java": "class Solution {\n public List> findDifference(int[] nums1, int[] nums2) {\n Set set1 = new HashSet<>(); // create 2 hashsets\n Set set2 = new HashSet<>();\n for(int num : nums1){ set1.add(num); } // add nums1 elements to set1\n for(int num : nums2){ set2.add(num); } // add nums2 elements to set2\n\n List> resultList = new ArrayList<>(); // Initialize result list with 2 empty sublists that we will return\n resultList.add(new ArrayList<>());\n resultList.add(new ArrayList<>());\n\n for(int num : set1){ // just iterate to all elements of set1\n if(!set2.contains(num)){ resultList.get(0).add(num); } // add those elements to first sublist of result list, which are not in set2.\n }\n for(int num : set2){ // just iterate to all elements of set2\n if(!set1.contains(num)){ resultList.get(1).add(num); } // add those elements to first sublist of result list, which are not in set1\n }\n return resultList;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> findDifference(vector& nums1, vector& nums2) {\n\t//unordered_set is implemented using a hash table where keys are hashed into indices of a hash table\n\t// all operations take O(1) on average\n unordered_set n1;\n unordered_set n2;\n for(int i=0;i ans1;\n\t\tvector> ans;\n for(int x:n1)\n {\n if(n2.find(x)==n2.end())\n ans1.push_back(x);\n }\n\t\tans.push_back(ans1);\n\t\tans1.clear();\n for(int x:n2)\n {\n if(n1.find(x)==n1.end())\n ans1.push_back(x);\n }\n ans.push_back(ans1);\n return ans;\n }\n};" }, { "title": "New 21 Game", "algo_input": "Alice plays the following game, loosely based on the card game \"21\".\n\nAlice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.\n\nAlice stops drawing numbers when she gets k or more points.\n\nReturn the probability that Alice has n or fewer points.\n\nAnswers within 10-5 of the actual answer are considered accepted.\n\n \nExample 1:\n\nInput: n = 10, k = 1, maxPts = 10\nOutput: 1.00000\nExplanation: Alice gets a single card, then stops.\n\n\nExample 2:\n\nInput: n = 6, k = 1, maxPts = 10\nOutput: 0.60000\nExplanation: Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.\n\n\nExample 3:\n\nInput: n = 21, k = 17, maxPts = 10\nOutput: 0.73278\n\n\n \nConstraints:\n\n\n\t0 <= k <= n <= 104\n\t1 <= maxPts <= 104\n\n", "solution_py": "class Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n dp = collections.deque([float(i <= n) for i in range(k, k + maxPts)])\n s = sum(dp)\n for i in range(k):\n dp.appendleft(s / maxPts)\n s += dp[0] - dp.pop()\n\n return dp[0]", "solution_js": "var new21Game = function(n, k, maxPts) {\n if (k+maxPts <= n || k===0) return 1;\n\n let dp = [];\n dp[0] = 1;\n dp[1] = 1/maxPts;\n\n for (let i = 2; i <= n; i++) {\n dp[i] = 0;\n\n if (i <= k) {\n dp[i] = (1 + 1/maxPts) * dp[i-1];\n } else {\n dp[i] = dp[i-1];\n }\n if (i > maxPts) {\n dp[i] -= dp[i-maxPts-1] / maxPts;\n }\n }\n\n return dp.reduce((acc, cur, idx) => {\n if (idx >= k) {\n acc += cur;\n }\n return acc;\n }, 0)\n};", "solution_java": "class Solution {\n public double new21Game(int n, int k, int maxPts) {\n double[] dp = new double[k + maxPts];\n dp[0] = 1;\n for (int i = 0; i < k; i++){\n for (int j = 1; j <= maxPts; j++){\n dp[i + j] += dp[i] * 1.0 / maxPts;\n }\n }\n\n double ans = 0;\n for (int i = k; i < k + maxPts && i <= n; i++){\n ans += dp[i];\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n double new21Game(int n, int k, int maxPts) {\n if(k==0 || n>=k+maxPts-1)\n return (double) 1;\n vector dp(n+1);\n dp[0]=1;\n double sum = 0;\n for(int i=0; i=maxPts)\n sum-=dp[i-maxPts];\n \n dp[i+1] = sum/maxPts;\n }\n double ret = 0;\n for(int i=k; i<=n; i++)\n ret+=dp[i];\n return ret;\n }\n};" }, { "title": "Walking Robot Simulation", "algo_input": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:\n\n\n\t-2: Turn left 90 degrees.\n\t-1: Turn right 90 degrees.\n\t1 <= k <= 9: Move forward k units, one unit at a time.\n\n\nSome of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.\n\nReturn the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).\n\nNote:\n\n\n\tNorth means +Y direction.\n\tEast means +X direction.\n\tSouth means -Y direction.\n\tWest means -X direction.\n\n\n \nExample 1:\n\nInput: commands = [4,-1,3], obstacles = []\nOutput: 25\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.\n\n\nExample 2:\n\nInput: commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput: 65\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.\n\n\nExample 3:\n\nInput: commands = [6,-1,-1,6], obstacles = []\nOutput: 36\nExplanation: The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.\n\n\n \nConstraints:\n\n\n\t1 <= commands.length <= 104\n\tcommands[i] is either -2, -1, or an integer in the range [1, 9].\n\t0 <= obstacles.length <= 104\n\t-3 * 104 <= xi, yi <= 3 * 104\n\tThe answer is guaranteed to be less than 231.\n\n", "solution_py": "class Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n obs = set(tuple(o) for o in obstacles)\n x = y = a = out = 0\n move = {0:(0,1), 90:(1,0), 180:(0,-1), 270:(-1,0)}\n for c in commands:\n if c == -1:\n a += 90\n elif c == -2:\n a -= 90\n else:\n direction = a % 360\n dx, dy = move[direction]\n for _ in range(c):\n if (x + dx, y + dy) in obs:\n break\n x += dx\n y += dy\n out = max(out, x**2 + y**2)\n return out", "solution_js": "/**\n * @param {number[]} commands\n * @param {number[][]} obstacles\n * @return {number}\n */\nvar robotSim = function(commands, obstacles) { \n let result = 0;\n let currentPosition = [0, 0];\n let currentDirection = 'top';\n const mySet = new Set();\n \n // This is to have a O(1) check instead of doing a linear scan\n obstacles.forEach(obs => {\n mySet.add(`${obs[0]},${obs[1]}`);\n }); // O(m)\n \n for (let i = 0; i < commands.length ; i++) { // O(n)\n const move = commands[i];\n if (move === -1) {\n if (currentDirection === 'top') {\n currentDirection = 'right';\n } else if (currentDirection === 'right') {\n currentDirection = 'down';\n } else if (currentDirection === 'down') {\n currentDirection = 'left';\n } else {\n currentDirection = 'top';\n }\n }\n \n if (move === -2) {\n if (currentDirection === 'top') {\n currentDirection = 'left';\n } else if (currentDirection === 'left') {\n currentDirection = 'down';\n } else if (currentDirection === 'down') {\n currentDirection = 'right';\n } else {\n currentDirection = 'top';\n }\n }\n \n if (move > 0) {\n for (let i = 0; i < move; i++) { O(move)\n const isY = (currentDirection === 'top' || currentDirection === 'down');\n const isPositive = (currentDirection === 'top' || currentDirection === 'right');\n \n const newPosition = [currentPosition[0] + (!isY ? isPositive? 1: -1 : 0), currentPosition[1] + (isY ? isPositive ? 1 : -1 : 0)];\n const positionString = `${newPosition[0]},${newPosition[1]}`;\n\n if (!mySet.has(positionString)) {\n currentPosition = newPosition;\n result = Math.max(result, (Math.pow(currentPosition[0], 2) + Math.pow(currentPosition[1], 2)));\n } else {\n break;\n }\n }\n }\n }\n return result;\n};", "solution_java": "class Solution {\n public int robotSim(int[] commands, int[][] obstacles) {\n int dir = 0; // states 0north-1east-2south-3west\n int farthestSofar = 0;\n\n int xloc = 0;\n int yloc = 0;\n\n Set set = new HashSet<>();\n for (int[] obs : obstacles) {\n set.add(obs[0] + \",\" + obs[1]);\n }\n\n int steps;\n\n for(int i: commands){\n\n if( i == -1){//turn right 90\n dir++;\n }\n else if (i == -2){//turn left 90\n dir--;\n }\n else{//move forward value of i baring no obsticals\n dir = dir%4;\n if (dir== -1){\n dir = 3;\n }\n else if(dir == -3){\n dir = 1;\n }\n else if(dir == -2){\n dir = 2;\n }\n // dir %4 = -1 -> 3\n // dir %4 = -2 -> 2\n // dir %4 = -3 -> 1\n if(dir == 0){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc+1))) {\n yloc++;\n steps++;\n }\n }\n else if (dir == 1){\n steps = 0;\n while (steps < i && !set.contains((xloc+1) + \",\" + (yloc))) {\n xloc++;\n steps++;\n }\n }\n else if (dir == 2){\n steps = 0;\n while (steps < i && !set.contains((xloc) + \",\" + (yloc-1))) {\n yloc--;\n steps++;\n }\n }\n else{ //case dir == 3\n steps = 0;\n while (steps < i && !set.contains((xloc-1) + \",\" + (yloc))) {\n xloc--;\n steps++;\n }\n }\n }\n farthestSofar = Math.max(farthestSofar, xloc*xloc + yloc*yloc);\n }\n return farthestSofar;\n }\n}", "solution_c": "class Solution {\npublic:\n\n //N--> left(-2):W, right(-1):E\n //S--> left:E, right:W\n //E--> left:N, right:S\n //W--> left:S, right:N\n\n vector> change= { //for direction change\n {3,2},\n {2,3},\n {0,1},\n {1,0}\n };\n\n vector> sign = { //signs for x and y coordinates movement\n {0,1},//North\n {0,-1},//south\n {1,0},//east\n {-1,0}//west\n };\n\n int robotSim(vector& commands, vector>& obstacles) {\n set> s;\n for(int i = 0;i=1){\n int signx = sign[direction][0];\n int signy = sign[direction][1];\n while(commands[i]){\n xi += signx;\n yi += signy;\n if(s.count({xi,yi})){\n xi -= signx;\n yi -= signy;\n break;\n }\n commands[i]--;\n }\n }\n else{\n direction = change[direction][commands[i]+2];\n }\n ans = max(ans,xi*xi+yi*yi);\n }\n return ans;\n }\n};" }, { "title": "Minimum Path Sum", "algo_input": "Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.\n\nNote: You can only move either down or right at any point in time.\n\n \nExample 1:\n\nInput: grid = [[1,3,1],[1,5,1],[4,2,1]]\nOutput: 7\nExplanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.\n\n\nExample 2:\n\nInput: grid = [[1,2,3],[4,5,6]]\nOutput: 12\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 200\n\t0 <= grid[i][j] <= 100\n\n", "solution_py": "class Solution:\n\n def minPathSum(self, grid: List[List[int]]) -> int:\n prev=[0]*len(grid[0])\n for i in range(len(grid)):\n temp=[0]*len(grid[0])\n for j in range(len(grid[0])):\n if i==0 and j==0:\n temp[j]=grid[i][j]\n continue\n if i>0:\n lft=grid[i][j]+prev[j]\n else:\n lft=grid[i][j]+1000\n if j>0:\n up=grid[i][j]+temp[j-1]\n else:\n up=grid[i][j]+1000\n temp[j]=min(up,lft)\n prev=temp\n return prev[-1]\n \n ", "solution_js": "var minPathSum = function(grid) {\n let row = grid.length;\n let col = grid[0].length;\n\n for(let i = 1; i < row; i++) {\n grid[i][0] += grid[i-1][0];\n }\n for(let j = 1; j < col; j++) {\n grid[0][j] += grid[0][j-1];\n }\n for(let i = 1; i < row; i++) {\n for(let j = 1; j < col; j++) {\n grid[i][j] += Math.min(grid[i-1][j], grid[i][j-1]);\n }\n }\n return grid[row-1][col-1];\n};", "solution_java": "class Solution {\n public int minPathSum(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[] dp = new int[n];\n dp[0] = grid[0][0];\n\n for(int i=1;i>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n vector> dp(n,vector(m,0));\n for(int i=0;i List[int]:\n answer = []\n \n for i in range(0, len(nums), 2):\n for j in range(0, nums[i]):\n answer.append(nums[i + 1])\n \n return answer", "solution_js": "var decompressRLElist = function(nums) {\n let solution = [];\n for(let i = 0;i arr = new ArrayList<>();\n for (int i = 0; i+1 < nums.length; i += 2) {\n for (int j = 0; j < nums[i]; ++j) {\n arr.add(nums[i+1]);\n }\n }\n int[] res = new int[arr.size()];\n for (int i = 0; i < res.length; ++i) res[i] = arr.get(i);\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n\tvector decompressRLElist(vector& nums) {\n\n\t\tvector ans;\n\n\t\tfor(int i=0 ; i List[List[int]]:\n self.final_list = []\n def subset(final_list,curr_list,listt,i):\n if i == len(listt):\n final_list.append(curr_list)\n return\n else:\n subset(final_list,curr_list,listt,i+1)\n subset(final_list,curr_list+[listt[i]],listt,i+1)\n subset(self.final_list,[],nums,0)\n return self.final_list", "solution_js": "var subsets = function(nums) {\n \n const res = [];\n \n const dfs = (i, slate) => {\n \n if(i == nums.length){\n \n res.push(slate.slice());\n \n return;\n \n }\n \n\t\t// take the current number into the subset.\n slate.push(nums[i]);\n dfs(i + 1, slate);\n slate.pop();\n \n\t\t// ignore the current number.\n dfs(i + 1, slate); \n \n }\n \n dfs(0, []);\n \n return res;\n \n};", "solution_java": "class Solution {\n \n private static void solve(int[] nums, int i, List temp, List> subset){\n \n if(i == nums.length){\n subset.add(new ArrayList(temp));\n return;\n }\n \n temp.add(nums[i]);\n solve(nums, i + 1, temp, subset);\n \n temp.remove(temp.size() - 1);\n solve(nums, i + 1, temp, subset);\n }\n \n public List> subsets(int[] nums) {\n List> subset = new ArrayList();\n List temp = new ArrayList<>();\n \n if(nums.length == 0) return subset;\n\n int startInd = 0;\n \n solve(nums, startInd, temp, subset);\n \n return subset;\n }\n}", "solution_c": "class Solution {\n void subsetGenerator (vector nums, int n, vector> &ans, int i, vector subset)\n {\n \n if(i>=n) //Base Case\n\t\t{ \n ans.push_back(subset); //the subset obatined is pushed into ans\n return ;\n }\n //including the element at index i and then calling the recursive function\n subset.push_back(nums[i]);\n solve(nums,n,ans,i+1,subset);\n \n\t\t\n //excluding the element at index i and then calling the recursive function\n subset.pop_back();\n solve(nums,n,ans,i+1,subset);\n \n }\npublic:\n\n vector> subsets(vector& nums) {\n\t int i=0; // index is initialized to 0 as we start from the first element\n int n=nums.size(); // size of the vector nums\n\t\tvector subset; // this vector will store each subset which is generated\n vector> ans; // will store all the subsets generated\n \n subsetGenerator(nums, n, ans, i, subset);\n\t\n return ans;\n }\n};" }, { "title": "Restore The Array", "algo_input": "A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.\n\nGiven the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: s = \"1000\", k = 10000\nOutput: 1\nExplanation: The only possible array is [1000]\n\n\nExample 2:\n\nInput: s = \"1000\", k = 10\nOutput: 0\nExplanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n\n\nExample 3:\n\nInput: s = \"1317\", k = 2000\nOutput: 8\nExplanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of only digits and does not contain leading zeros.\n\t1 <= k <= 109\n\n", "solution_py": "\"\"\"\n \"1317\"\n[1, 3, 1, 7] -> [1] * nums(317, k)\n[1, 3, 17] \n[1, 31, 7]\n[1, 317] \n[13, 1, 7] -> [13] * nums(17, k)\n[13, 17]\n[131, 7]\n[1317]\n\n\n \"2020\" k = 30\n[2000] x\n[2, 020] x\n[20, 20]\n\n \"67890\" k = 90\n\n[6, 7890] x\n[6, 7, 8, 9, 0] x\n[6, 7, 8, 90] OK\n[6, 78, 90] OK\n[67, 8, 90] OK\n[67, 89, 0] x\n[678, 90] x\nbreak because 678 > k (90), so neither 678, 6789 would be possible numbers\n\n\"\"\"\n\n\n\nclass Solution:\n def num_arrays(self, s, k, memo):\n if not s:\n return 0\n memo_ans = memo.get(s)\n if memo_ans is not None:\n return memo_ans\n \n num = int(s)\n if num <= k:\n counter = 1\n else:\n counter = 0\n \n for i in range(len(s) - 1):\n # Stop when the number to the right side of the array is greater than k\n if int(s[:i + 1]) > k:\n break\n # Don't count leading zeros\n if s[i + 1] == \"0\":\n continue\n counter += self.num_arrays(s[i + 1:], k, memo)\n ans = counter % (10 ** 9 + 7)\n memo[s] = ans\n return ans\n \n def numberOfArrays(self, s: str, k: int) -> int:\n memo = {}\n return self.num_arrays(s, k, memo)", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nvar numberOfArrays = function(s, k) {\n var cache={};\n return backtrack(0)%1000000007;\n function backtrack(pos){\n let orignalPos = pos;\n if(cache[pos]!==undefined){\n return cache[pos];\n }\n let count=0;\n let digit=0;\n while(posk){\n break;\n }\n pos++;\n } \n if(pos===s.length && digit<=k){//If this number became the only digit in the array, for string starting at position orignalPos. This also completed the etire string. \n count++;\n }\n cache[orignalPos]=count;\n return count;\n }\n};", "solution_java": "class Solution {\n static long mod;\n private long solve(int idx,String s,int k,long[] dp){\n if(idx==s.length())\n return 1;\n if(dp[idx]!=-1)\n return dp[idx];\n long max=0,number=0;\n for(int i=idx;i=1 && number<=k){\n max=(max+solve(i+1,s,k,dp))%mod;\n }else\n break;\n }\n return dp[idx]=max;\n }\n public int numberOfArrays(String s, int k) {\n mod = (int)1e9+7;\n long[] dp=new long[s.length()+1];\n Arrays.fill(dp,-1);\n return (int)solve(0,s,k,dp);\n }\n}", "solution_c": "class Solution {\npublic:\n int mod=1e9+7;\n int f(int i,int k,string &s,vector &dp){\n if(i==s.size()) return 1;//empty string\n if(dp[i]!=-1) return dp[i];//Memoization step\n if(s[i]=='0') return 0;//leading zeroes\n long long num=0;\n int ans=0;\n for(int j=i;jk) break;\n ans+=f(j+1,k,s,dp);//create num and call for next index\n ans%=mod;\n }\n return dp[i]=ans;//storing answer\n }\n int numberOfArrays(string s, int k) {\n int n=s.size();\n vector dp(n+1,-1);\n return f(0,k,s,dp);\n // dp[i]=total ways to\n // create possible arrays starting at index i\n }\n};" }, { "title": "Count Sub Islands", "algo_input": "You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.\n\nAn island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.\n\nReturn the number of islands in grid2 that are considered sub-islands.\n\n \nExample 1:\n\nInput: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]\nOutput: 3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\n\n\nExample 2:\n\nInput: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]\nOutput: 2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n\n\n \nConstraints:\n\n\n\tm == grid1.length == grid2.length\n\tn == grid1[i].length == grid2[i].length\n\t1 <= m, n <= 500\n\tgrid1[i][j] and grid2[i][j] are either 0 or 1.\n\n", "solution_py": "class Solution(object):\n def countSubIslands(self, grid1, grid2):\n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n return \n grid2[i][j]=0\n dfs(i+1,j)\n dfs(i-1,j)\n dfs(i,j+1)\n dfs(i,j-1)\n # here we remove the unnecesaary islands by seeing the point that if for a land in grid2 and water in grid1 it cannot be a subisland and hence island in which this land resides should be removed \n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1 and grid1[i][j]==0:\n dfs(i,j)\n\t\t#now we just need to count the islands left over \t\t\t\n count=0\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1:\n \n dfs(i,j)\n count+=1\n return count \n\t\t", "solution_js": "var countSubIslands = function(grid1, grid2) {\n const R = grid2.length, C = grid2[0].length;\n \n // returns no of cells in grid 2 not covered in grid1\n function noOfNotCoveredDfs(i, j) {\n if (i < 0 || j < 0) return 0;\n if (i >= R || j >= C) return 0;\n if (grid2[i][j] !== 1) return 0;\n \n // mark visited\n grid2[i][j] = 2;\n \n return (grid1[i][j] === 1 ? 0 : 1) + \n noOfNotCoveredDfs(i - 1, j) + \n noOfNotCoveredDfs(i + 1, j) + \n noOfNotCoveredDfs(i, j - 1) + \n noOfNotCoveredDfs(i, j + 1);\n }\n \n let ans = 0;\n for (let i = 0; i < R; i++) {\n for (let j = 0; j < C; j++) {\n if (grid2[i][j] === 1) {\n if (noOfNotCoveredDfs(i, j) === 0) {\n ans++;\n }\n }\n }\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int countSubIslands(int[][] grid1, int[][] grid2) {\n int m = grid1.length;\n int n = grid1[0].length;\n boolean[][] vis = new boolean[m][n];\n int count = 0;\n int[] dir = {1, 0, -1, 0, 1};\n\n for(int i = 0; i < m; ++i) {\n for(int j = 0; j < n; ++j) {\n if(grid2[i][j] == 0 || vis[i][j])\n continue;\n\n Queue queue = new LinkedList<>();\n boolean flag = true;\n vis[i][j] = true;\n\n queue.add(new int[] {i, j});\n\n while(!queue.isEmpty()) {\n int[] vtx = queue.remove();\n\n if(grid1[vtx[0]][vtx[1]] == 0)\n flag = false;\n\n for(int k = 0; k < 4; ++k) {\n int x = vtx[0] + dir[k];\n int y = vtx[1] + dir[k + 1];\n\n if(x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && !vis[x][y]) {\n vis[x][y] = true;\n\n queue.add(new int[] {x, y});\n }\n }\n }\n\n if(flag)\n ++count;\n }\n }\n\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n bool res;\n void mark_current_island(vector>& grid1, vector>& grid2,int x,int y,int r,int c){\n if(x<0 || x>=r || y<0 || y>=c || grid2[x][y]!=1) //Boundary case for matrix\n return ;\n \n //if there is water on grid1 for the location on B then our current island can't be counted and so we mark res as false \n if(grid1[x][y]==0){\n res=false;\n return;\n }\n //Mark current cell as visited\n grid2[x][y] = 0;\n \n //Make recursive call in all 4 adjacent directions\n mark_current_island(grid1,grid2,x+1,y,r,c); //DOWN\n mark_current_island(grid1,grid2,x,y+1,r,c); //RIGHT\n mark_current_island(grid1,grid2,x-1,y,r,c); //TOP\n mark_current_island(grid1,grid2,x,y-1,r,c); //LEFT\n }\n int countSubIslands(vector>& grid1, vector>& grid2) {\n //For FAST I/O\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n \n int rows = grid1.size();\n if(rows==0) //Empty grid boundary case\n return 0;\n int cols = grid1[0].size();\n\t\t\n //Iterate for all cells of the array\n int no_of_islands = 0;\n\t\t\n //dfs on grid2 \n for(int i=0;i bool:\n def pal(x):\n return x == x[::-1]\n if pal(a) or pal(b): return True\n # either grow from inside to outside, or vice versa\n ina = len(a)-1\n inb = 0\n outa = 0\n outb = len(b)-1\n\n while a[ina] == b[inb]:\n ina -= 1\n inb += 1\n if ina <= inb:\n return True # short circuit found break point\n # jump into each string now!?\n # is a or b a palindrome in this portion from inb to ina\n if pal(a[inb:ina+1]) or pal(b[inb:ina+1]):\n return True # either one is breakpoint, so check remainder is palindrome\n\n while a[outa] == b[outb]:\n outa += 1\n outb -= 1\n if outa >= outb:\n return True\n if pal(a[outa:outb+1]) or pal(b[outa:outb+1]):\n return True # either one is breakpoint, so check remainder\n\n return False", "solution_js": "var checkPalindromeFormation = function(a, b) {\n function isPal(str, l, r) {\n while (l < r) {\n if (str[l] === str[r]) l++, r--;\n else return false;\n } return true;\n }\n \n // aprefix + bsuffix\n let l = 0, r = b.length - 1;\n while (l < r && a[l] === b[r]) l++, r--;\n if (isPal(a, l, r) || isPal(b, l, r)) return true;\n \n // bprefix + asuffix\n l = 0, r = a.length - 1;\n while (l < r && b[l] === a[r]) l++, r--;\n if (isPal(a, l, r) || isPal(b, l, r)) return true;\n \n return false;\n};", "solution_java": "class Solution {\n public boolean checkPalindromeFormation(String a, String b) {\n return split(a, b) || split(b, a);\n }\n \n private boolean split(String a, String b) {\n int left = 0, right = a.length() - 1;\n while (left < right && a.charAt(left) == b.charAt(right)) {\n left++;\n right--;\n }\n if (left >= right) return true;\n return isPalindrome(a, left, right) || isPalindrome(b, left, right);\n }\n \n private boolean isPalindrome(String s, int left, int right) {\n while (left <= right) {\n if (s.charAt(left) != s.charAt(right)) return false;\n left++;\n right--;\n }\n return true;\n }\n}", "solution_c": "// samll trick: for plaindrome question always try to follow concept that if corners are equal we need to only work\n// on middle string to check whether it is also palindrome, instead of check complete strings(both given strings).\nclass Solution {\npublic:\n bool ispalind(string x, int i, int j){\n while(i int:\n # n <= 12, which means the search space is small\n n = len(s)\n arr = []\n \n for mask in range(1, 1< 0:\n subseq += s[i]\n if subseq == subseq[::-1]:\n arr.append((mask, len(subseq)))\n \n result = 1\n for (mask1, len1), (mask2, len2) in product(arr, arr):\n # disjoint\n if mask1 & mask2 == 0:\n result = max(result, len1 * len2)\n return result", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar maxProduct = function(s) {\n const n = s.length;\n let map = new Map();\n let res = 0;\n\n for(let mask = 1; mask < 2 ** n;mask++){\n let str = \"\";\n for(let i = 0; i < n;i++){\n if(mask & (1 << i)){\n str += s.charAt(n - 1 - i);\n }\n }\n if(isPalindrom(str)){\n let length = str.length;\n map.set(mask,length);\n }\n }\n\n map.forEach((l1,m1) => {\n map.forEach((l2,m2) => {\n if((m1 & m2) == 0){\n res = Math.max(res,l1 * l2);\n }\n })\n })\n\n return res;\n};\n\nfunction isPalindrom(str){\n let l = 0;\n let r = str.length - 1;\n\n while(l < r){\n if(str.charAt(l) != str.charAt(r)){\n return false;\n }\n l++;\n r--;\n }\n\n return true;\n}", "solution_java": "class Solution {\n int res = 0;\n \n public int maxProduct(String s) {\n char[] strArr = s.toCharArray();\n dfs(strArr, 0, \"\", \"\");\n return res;\n }\n\n public void dfs(char[] strArr, int i, String s1, String s2){\n if(i >= strArr.length){\n if(isPalindromic(s1) && isPalindromic(s2))\n res = Math.max(res, s1.length()*s2.length());\n return;\n }\n dfs(strArr, i+1, s1 + strArr[i], s2);\n dfs(strArr, i+1, s1, s2 + strArr[i]);\n dfs(strArr, i+1, s1, s2);\n }\n\n public boolean isPalindromic(String str){\n int j = str.length() - 1;\n char[] strArr = str.toCharArray();\n for (int i = 0; i < j; i ++){\n if (strArr[i] != strArr[j])\n return false;\n j--;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n int lca(string &s)\n {\n int n=s.size();\n string s1=s;\n string s2=s;\n reverse(s2.begin(),s2.end());\n int dp[s.size()+1][s.size()+1];\n memset(dp,0,sizeof(dp));\n for(int i=1;i<=n;i++)\n {\n for(int j=1;j<=n;j++)\n {\n dp[i][j]=(s1[i-1]==s2[j-1])?1+dp[i-1][j-1]:max(dp[i][j-1],dp[i-1][j]);\n }\n }\n return dp[n][n];\n }\n int maxProduct(string s) \n {\n int ans=0;\n int n=s.size();\n for(int i=1;i<(1< int:\n n=len(arr)\n def solve(nums):\n i,j,last_neg,neg,ans=0,0,None,0,0\n while j0){\n p *=1\n }else if(nums[i]<0){\n p *=-1\n }\n count++;\n if(p>0){\n max = Math.max(max,count);\n }\n if(p===0){\n p=1;\n count=0;\n }\n }\n count = 0;p=1;\n //Process elements from right to left\n for(let i=nums.length-1;i>=0;i--){\n if(nums[i]===0){\n p=0;\n }else if(nums[i]>0){\n p *=1\n }else if(nums[i]<0){\n p *=-1\n }\n count++;\n if(p>0){\n max = Math.max(max,count);\n }\n if(p===0){\n p=1;\n count=0;\n }\n }\n return max;\n};", "solution_java": "class Solution {\n public int getMaxLen(int[] nums)\n {\n int first_negative=-1;\n int zero_position=-1;\n int count_neg=0;\n int res=0;\n for(int i=0;i& nums) {\n int ans = 0;\n int lprod = 1,rprod = 1;\n int llen = 0, rlen = 0;\n int n = nums.size();\n for(int i = 0 ; i < n ; i++){\n lprod *= nums[i] != 0 ? nums[i]/abs(nums[i]) : 0;\n rprod *= nums[n-1-i] != 0 ? nums[n-1-i]/abs(nums[n-1-i]) : 0;\n if(lprod != 0) llen ++;\n if(rprod != 0) rlen ++;\n if(lprod > 0) ans = max(ans,llen);\n if(rprod > 0) ans = max(ans,rlen);\n if(lprod == 0) {\n lprod = 1;\n llen = 0;\n }\n if(rprod == 0){\n rlen = 0;\n rprod = 1;\n }\n }\n return ans;\n }\n};" }, { "title": "Find Greatest Common Divisor of Array", "algo_input": "Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.\n\nThe greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.\n\n \nExample 1:\n\nInput: nums = [2,5,6,9,10]\nOutput: 2\nExplanation:\nThe smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.\n\n\nExample 2:\n\nInput: nums = [7,5,6,8,3]\nOutput: 1\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.\n\n\nExample 3:\n\nInput: nums = [3,3]\nOutput: 3\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 1000\n\t1 <= nums[i] <= 1000\n\n", "solution_py": "class Solution:\n def findGCD(self, nums: List[int]) -> int:\n i_min = min(nums)\n i_max = max(nums)\n greater = i_max\n while True:\n if greater % i_min == 0 and greater % i_max == 0:\n lcm = greater\n break\n greater += 1\n return int(i_min/(lcm/i_max))", "solution_js": "var findGCD = function(nums) {\n let newNum = [Math.min(...nums) , Math.max(...nums)]\n let firstNum = newNum[0]\n let secondNum = newNum[1]\n while(secondNum) {\n let newNum = secondNum;\n secondNum = firstNum % secondNum;\n firstNum = newNum;\n }\n return firstNum\n};", "solution_java": "class Solution {\n public int findGCD(int[] nums) {\n Arrays.sort(nums);\n int n=nums[nums.length-1];\n int result=nums[0];\n while(result>0){\n if(nums[0]%result==0 && n%result==0){\n break;\n }\n result--;\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int findGCD(vector& nums) {\n int mn = nums[0], mx = nums[0];\n for(auto n: nums)\n {\n // finding maximum, minimum values of the array.\n if(n > mx) mx = n;\n if(n < mn) mn = n;\n }\n\n for(int i = mn; i >= 1; i--)\n {\n // finding greatest common divisor (GCD) of max, min.\n if((mn % i == 0) && (mx % i == 0)) return i;\n }\n return 1;\n }\n};" }, { "title": "Minimum Domino Rotations For Equal Row", "algo_input": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)\n\nWe may rotate the ith domino, so that tops[i] and bottoms[i] swap values.\n\nReturn the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.\n\nIf it cannot be done, return -1.\n\n \nExample 1:\n\nInput: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput: 2\nExplanation: \nThe first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\n\n\nExample 2:\n\nInput: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput: -1\nExplanation: \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n\n\n \nConstraints:\n\n\n\t2 <= tops.length <= 2 * 104\n\tbottoms.length == tops.length\n\t1 <= tops[i], bottoms[i] <= 6\n\n", "solution_py": "class Solution:\n def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n sames = [tops[i] for i in range(len(tops)) if tops[i] == bottoms[i]]\n\t\t\n same_count = collections.Counter(sames)\n bottom_count = collections.Counter(bottoms)\n top_count = collections.Counter(tops)\n \n for n in range(1,7):\n if bottom_count[n] + top_count[n] - same_count[n] == len(tops):\n return min(bottom_count[n], top_count[n]) - same_count[n]\n \n return -1", "solution_js": "/**\n * @param {number[]} tops\n * @param {number[]} bottoms\n * @return {number}\n */\nvar minDominoRotations = function(tops, bottoms) {\n const swaps = Math.min(\n minimum(tops[0], tops, bottoms),\n minimum(tops[0], bottoms, tops),\n minimum(bottoms[0], tops, bottoms),\n minimum(bottoms[0], bottoms, tops)\n );\n\n return swaps === Infinity ? -1 : swaps;\n\n function minimum(target, x, y, count = 0) {\n for(let i = 0; i < x.length; i++) {\n if(target !== x[i]) {\n if (target !== y[i]) return Infinity\n count++;\n }\n }\n return count;\n }\n};", "solution_java": "class Solution {\n public int minDominoRotations(int[] tops, int[] bottoms) {\n\n int[][] c = new int[6][2];\n\n for (int i : tops) {\n c[i - 1][0]++;\n }\n for (int i : bottoms) {\n c[i - 1][1]++;\n }\n int[] common = new int[6];\n for (int i = 0; i < tops.length; i++) {\n if (tops[i] == bottoms[i]) {\n common[tops[i] - 1]++;\n }\n }\n int min = Integer.MAX_VALUE;\n for (int i = 1; i <= 6; i++) {\n if (c[i - 1][0] + c[i - 1][1] >= tops.length) {\n if (c[i - 1][0] >= c[i - 1][1] && c[i - 1][1] - common[i - 1] + c[i - 1][0] == tops.length) {\n min = Math.min(min, c[i - 1][1] - common[i - 1]);\n }\n else if (c[i - 1][1] >= c[i - 1][0] && c[i - 1][0] - common[i - 1] + c[i - 1][1] == tops.length) {\n int left = c[i - 1][0] - common[i - 1];\n min = Math.min(min, c[i - 1][0] - common[i - 1]);\n }\n }\n }\n\n return min == Integer.MAX_VALUE ? -1 : min;\n }\n}", "solution_c": "class Solution {\npublic:\n int minDominoRotations(vector& tops, vector& bottoms) {\n vector freq(7, 0);\n \n int n = tops.size();\n int tile = -1\n\t\t// there has to be particular tile number which is present in every column to be able to arrange same tile in top or bottom by rotating\n // check which tile is present in every column\n for(int i=0; i int:\n\t\tif \".\" not in input:\n\t\t\treturn 0\n\n\t\ta=input.split(\"\\n\")\n\t\tfiles=[]\n\t\tfor i in a:\n\t\t\tif \".\" in i:\n\t\t\t\tfiles.append(i)\n\n\t\tfinal=[]\n\t\tfor i in range(len(files)):\n\t\t\tfile=files[i]\n\t\t\tlvl=file.count(\"\\t\")\n\t\t\tidx=a.index(file)-1\n\t\t\tsave=[files[i].replace(\"\\t\",\"\")]\n\t\t\tfor j in range(lvl):\n\t\t\t\twhile a[idx].count(\"\\t\")!=lvl-1:\n\t\t\t\t\tidx-=1\n\t\t\t\tlvl=a[idx].count(\"\\t\")\n\t\t\t\tsave.append(a[idx].replace(\"\\t\",\"\"))\n\t\t\t\tidx-=1\n\t\t\tfinal.append(save)\n\n\t\tfinal=list(map(\"/\".join,final))\n\t\treturn len(max(final,key=len))", "solution_js": "function isFile(path) {\n return path.includes('.')\n}\n\nvar lengthLongestPath = function(input) {\n const segments = input.split('\\n');\n \n let max = 0;\n let path = [];\n for (const segment of segments) {\n if (segment.startsWith('\\t')) {\n const nesting = segment.match(/\\t/g).length;\n \n while (nesting < path.length) {\n path.pop();\n }\n \n path.push(segment.replace(/\\t/g, ''))\n } else {\n path = [segment]\n }\n \n if (isFile(path.at(-1))) {\n const filePath = path.join('/');\n if (filePath.length > max) {\n max = filePath.length;\n }\n }\n }\n \n return max;\n};", "solution_java": "class Solution {\n public int lengthLongestPath(String input) {\n var stack = new ArrayDeque();\n int max = 0;\n String[] lines = input.split(\"\\n\");\n for(var line: lines) {\n int tabs = countTabs(line);\n while(tabs < stack.size()) {\n stack.pop();\n }\n int current = stack.isEmpty() ? 0: stack.peek();\n int nameLength = line.length() - tabs;\n if(isFilename(line)) {\n max = Math.max(max, current + nameLength);\n } else {\n stack.push(current + nameLength + 1);\n }\n }\n return max;\n }\n \n private int countTabs(String s) {\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) != '\\t') return i;\n }\n return 0;\n }\n \n private boolean isFilename(String s) {\n return s.lastIndexOf(\".\") != -1;\n }\n \n}", "solution_c": "// Using Map O(300 + N)\n\nclass Solution {\n public:\n int lengthLongestPath(string input) {\n input.push_back('\\n');\n vector levels(301, 0);\n int ans = 0;\n int curr_tabs = 0;\n bool is_file = false;\n int curr_word_len = 0;\n int total_len = 0;\n\n for(char c : input)\n {\n if(c == '\\t')\n {\n curr_tabs++;\n }\n else if(c == '\\n')\n {\n if(curr_tabs == 0)\n {\n levels[0] = curr_word_len;\n }\n else\n {\n levels[curr_tabs] = levels[curr_tabs-1] + curr_word_len;\n }\n\n if(is_file)\n {\n ans = max(ans, levels[curr_tabs] + curr_tabs);\n // levels[curr_tabs] = 0;\n }\n curr_tabs = 0;\n is_file = false;\n curr_word_len = 0;\n }\n else if(c == '.')\n {\n is_file = true;\n curr_word_len++;\n }\n else\n {\n curr_word_len++;\n }\n }\n return ans;\n }\n};" }, { "title": "Two Furthest Houses With Different Colors", "algo_input": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.\n\nReturn the maximum distance between two houses with different colors.\n\nThe distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.\n\n \nExample 1:\n\nInput: colors = [1,1,1,6,1,1,1]\nOutput: 3\nExplanation: In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.\n\n\nExample 2:\n\nInput: colors = [1,8,3,8,3]\nOutput: 4\nExplanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.\n\n\nExample 3:\n\nInput: colors = [0,1]\nOutput: 1\nExplanation: The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.\n\n\n \nConstraints:\n\n\n\tn == colors.length\n\t2 <= n <= 100\n\t0 <= colors[i] <= 100\n\tTest data are generated such that at least two houses have different colors.\n\n", "solution_py": "class Solution:\n def maxDistance(self, colors: List[int]) -> int:\n p, res = inf, 0\n for i, c in enumerate(colors):\n if (c != colors[0]):\n res = i\n p = min(p, i)\n else:\n res = max(res, i - p)\n return res", "solution_js": "var maxDistance = function(colors) {\n // using two pointers from start and end\n // Time complexity O(n)\n // Space complexity O(1)\n \n const start = 0;\n const end = colors.length - 1;\n\n // maximum distance possible is length of arr, so start with two pointer\n\t// one at the start and one at the end\n const startColor = colors[start];\n const endColor = colors[end];\n \n\t// base condition, to check if they are not already equal\n if (startColor !== endColor) {\n return end;\n }\n \n\t// move the forward pointer till we find the differend color\n let forwardPtr = start;\n while (startColor === colors[forwardPtr]) {\n ++forwardPtr;\n }\n \n // move the backward pointer till we find the differend color\n let backwardPtr = end;\n while(endColor === colors[backwardPtr]) {\n --backwardPtr;\n }\n \n // Till here, We already know that startColor === endColor\n // hence we did two things,\n \t// 1. we kept startColor fixed and moved backwardPtr till we find different color\n // 2. similarly, we kept endColor fixed and moved the forwardPtr till we find the different color.\n // we will return the max different out of two now.\n return Math.max(Math.abs(start - backwardPtr), Math.abs(end - forwardPtr));\n \n};", "solution_java": "class Solution {\n public int maxDistance(int[] colors) {\n int l = 0, r = colors.length-1;\n while(colors[colors.length-1] == colors[l]) l++;\n while(colors[0] == colors[r]) r--;\n return Math.max(r, colors.length - 1 - l);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxDistance(vector& colors) {\n int Max = INT_MIN;\n int N = colors.size();\n \n // find the first house from the end which does not match the color of house at front\n int j=N;\n while(--j>=0 && colors[0]==colors[j]) { } // worst-case O(n)\n Max = abs(j-0);\n \n // find the first house from the front which does not match the color of house at back\n j=-1;\n while(++j int:\n\t\tcode = [\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\",\"--\",\"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"]\n\t\tout = []\n\t\tfor word in words:\n\t\t\tres = [code[ord(char)-ord('a')] for char in word]\n\t\t\tout.append(\"\".join(res))\n\t\treturn len(set(out))", "solution_js": "var uniqueMorseRepresentations = function(words) {\n var morse = [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\n \"--.\",\"....\",\"..\",\".---\",\n \"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\n \"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\n \".--\",\"-..-\",\"-.--\",\"--..\"];\n\n var transformations = new Set();\n\n for (let word of words) {\n var trans = \"\";\n for (let letter of word) {\n var index = letter.charCodeAt(0) - 97;\n trans += morse[index];\n }\n\n transformations.add(trans);\n }\n\n return transformations.size;\n};", "solution_java": "class Solution {\n public int uniqueMorseRepresentations(String[] words) {\n HashSet set = new HashSet<>();\n String[] morse = new String[]{\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n \n for (int i = 0; i < words.length; ++i) {\n String temp = \"\";\n for (int j = 0; j < words[i].length(); ++j) {\n temp += morse[(int)words[i].charAt(j)-'a'];\n }\n set.add(temp);\n }\n return set.size();\n }\n}", "solution_c": "class Solution {\npublic:\n\n string convert(string st)\n {\n string s1[]={\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"};\n string s=\"\";\n for(char a:st)\n {\n s+=s1[a - 'a'];\n\n }\n return s;\n\n }\n int uniqueMorseRepresentations(vector& words) {\n\n setst;\n for(int i=0;i int:\n ROW, COL = len(heightMap), len(heightMap[0])\n\n pq = []\n heapq.heapify(pq)\n visited = {}\n \n for row in range(ROW):\n for col in range(COL):\n if row == 0 or row == ROW-1 or col == 0 or col == COL-1:\n heapq.heappush(pq, (heightMap[row][col],row,col))\n visited[(row,col)] = True\n \n def getnbr(row,col):\n res = []\n if row-1 >=0:\n res.append((row-1,col))\n if col-1 >=0:\n res.append((row, col-1))\n if row+1 < ROW:\n res.append((row+1,col))\n if col+1 < COL:\n res.append((row, col+1))\n\n return res\n \n res = 0\n \n while pq:\n h, i, j = heapq.heappop(pq)\n \n for dx, dy in getnbr(i,j):\n if (dx,dy) not in visited: \n \n res += max(0, h-heightMap[dx][dy])\n \n heapq.heappush(pq, (max(h, heightMap[dx][dy]),dx,dy))\n visited[(dx,dy)] = True\n\n return res", "solution_js": "const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]];\nconst MAX = 200 * 201; // n * m + m\nconst trapRainWater = (g) => {\n let n = g.length, m = g[0].length;\n if (n == 0) return 0;\n let res = 0, max = Number.MIN_SAFE_INTEGER;\n let pq = new MinPriorityQueue({priority: x => x[0] * MAX + x[1]}); // first priority: x[0], smaller comes first. second priority: x[1], smaller comes first\n let visit = initialize2DArrayNew(n, m);\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < m; j++) {\n if (i == 0 || i == n - 1 || j == 0 || j == m - 1) {\n pq.enqueue([g[i][j], i * m + j]);\n visit[i][j] = true;\n }\n }\n }\n while (pq.size()) { // BFS\n let cur = pq.dequeue().element;\n let h = cur[0], r = cur[1] / m >> 0, c = cur[1] % m; // height row column\n max = Math.max(max, h);\n for (let k = 0; k < 4; k++) {\n let x = r + dir[k][0], y = c + dir[k][1];\n if (x < 0 || x >= n || y < 0 || y >= m || visit[x][y]) continue;\n visit[x][y] = true;\n if (g[x][y] < max) res += max - g[x][y];\n pq.enqueue([g[x][y], x * m + y]);\n }\n }\n return res;\n};\n\nconst initialize2DArrayNew = (n, m) => { let data = []; for (let i = 0; i < n; i++) { let tmp = Array(m).fill(false); data.push(tmp); } return data; };", "solution_java": "class Solution {\n public class pair implements Comparable{\n int row;\n int col;\n int val;\n pair(int row, int col,int val){\n this.row = row;\n this.col = col;\n this.val = val;\n }\n public int compareTo(pair o){\n return this.val - o.val;\n }\n }\n int[][] dir = {{1,0},{0,-1},{-1,0},{0,1}};\n public int trapRainWater(int[][] heightMap) {\n int n = heightMap.length;\n int m = heightMap[0].length;\n \n PriorityQueue pq = new PriorityQueue<>();\n \n boolean[][] visited = new boolean[n][m];\n \n // add all the boundary elements in pq\n \n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n if(i == 0 || j == 0 || i == n-1 || j == m-1){\n pq.add(new pair(i, j, heightMap[i][j]));\n visited[i][j] = true;\n }\n }\n }\n \n int ans = 0;\n \n while(pq.size() > 0){\n pair rem = pq.remove();\n for(int i = 0; i < 4; i++){\n \n int rowdash = rem.row + dir[i][0];\n int coldash = rem.col + dir[i][1];\n \n if(rowdash >= 0 && coldash >= 0 && rowdash < n && coldash < m && visited[rowdash][coldash] == false){\n visited[rowdash][coldash] = true;\n if(heightMap[rowdash][coldash] >= rem.val){\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash])); // boundary is updated\n }else{\n int waterstored = rem.val - heightMap[rowdash][coldash];\n ans += waterstored; // now this will act as a wall add in pq\n pq.add(new pair(rowdash, coldash, heightMap[rowdash][coldash] + waterstored));\n }\n }\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool vis[201][201]; //to keep track of visited cell\n int n,m;\n bool isValid(int i, int j){\n if(i<0 || i>=m || j<0 || j>=n || vis[i][j]==true) return false;\n \n return true;\n }\n int trapRainWater(vector>& heightMap) {\n vector> dir {{1,0},{-1,0},{0,1},{0,-1}}; //direction Vector\n m = heightMap.size(); if(m==0) return 0; // m=0 is one edge case\n n = heightMap[0].size();\n memset(vis,false,sizeof(vis));\n priority_queue> , vector>> , greater>> >pq; // min heap w.r.t cell height\n for(int i=0;i List[int]:\n flag, rowNum, colNum = True, len(mat), len(mat[0])\n\n total, ans = 0, []\n while total <= rowNum + colNum - 2:\n iLimited = rowNum - 1 if flag else colNum - 1 \n jLimited = colNum - 1 if flag else rowNum - 1\n i = total if total < iLimited else iLimited\n j = total - i\n while i >= 0 and j <= jLimited:\n if flag:\n ans.append(mat[i][j])\n else:\n ans.append(mat[j][i])\n i -= 1\n j += 1\n total += 1\n flag = not flag\n return ans", "solution_js": "var findDiagonalOrder = function(matrix) {\n const res = [];\n for (let r = 0, c = 0, d = 1, i = 0, len = matrix.length * (matrix[0] || []).length; i < len; i++) {\n res.push(matrix[r][c]);\n r -= d;\n c += d;\n if (!matrix[r] || matrix[r][c] === undefined) { // We've fallen off the...\n if (d === 1) {\n if (matrix[r + 1] && matrix[r + 1][c] !== undefined) { // ...top cliff\n r++;\n } else { // ...right cliff\n r += 2;\n c--;\n }\n } else {\n if (matrix[r] && matrix[r][c + 1] !== undefined) { // ...left cliff\n c++;\n } else { // ...bottom cliff\n r--;\n c += 2;\n }\n }\n d = -d;\n }\n }\n return res;\n};", "solution_java": "/**\n * Simulate Diagonal Order Traversal\n *\n * r+c determines which diagonal you are on. For ex: [2,0],[1,1],[0,2] are all\n * on same diagonal with r+c =2. If you check the directions of diagonals, first\n * diagonal is up, second diagonal is down, third one is up and so on..\n * Therefore (r+c)%2 simply determines direction. Even is UP direction. Odd is\n * DOWN direction.\n *\n * Time Complexity: O(M*N)\n *\n * Space Complexity: O(1) without considering result space.\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n public int[] findDiagonalOrder(int[][] matrix) {\n if (matrix == null) {\n throw new IllegalArgumentException(\"Input matrix is null\");\n }\n if (matrix.length == 0 || matrix[0].length == 0) {\n return new int[0];\n }\n\n int rows = matrix.length;\n int cols = matrix[0].length;\n int[] result = new int[rows * cols];\n int r = 0;\n int c = 0;\n\n for (int i = 0; i < result.length; i++) {\n result[i] = matrix[r][c];\n if ((r + c) % 2 == 0) { // Move Up\n if (c == cols - 1) {\n // Reached last column. Now move to below cell in the same column.\n // This condition needs to be checked first due to top right corner cell.\n r++;\n } else if (r == 0) {\n // Reached first row. Now move to next cell in the same row.\n c++;\n } else {\n // Somewhere in middle. Keep going up diagonally.\n r--;\n c++;\n }\n } else { // Move Down\n if (r == rows - 1) {\n // Reached last row. Now move to next cell in same row.\n // This condition needs to be checked first due to bottom left corner cell.\n c++;\n } else if (c == 0) {\n // Reached first columns. Now move to below cell in the same column.\n r++;\n } else {\n // Somewhere in middle. Keep going down diagonally.\n r++;\n c--;\n }\n }\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector findDiagonalOrder(vector>& mat) {\n vectorvec;\n int m=mat.size()-1,n=mat[0].size()-1;\n int i=0,j=0;\n if(m==-1){\n return {};\n }\n if(m==0){\n for(int i{0};i<=n;++i){\n vec.push_back(mat.at(0).at(i));\n }\n return vec;\n }else if(n==0){\n for(int i{0};i<=m;++i){\n vec.push_back(mat.at(i).at(0));\n }\n return vec;\n }\n for(int k{0};k<=m+n;k++){\n if(k==0){\n vec.push_back(mat.at(0).at(0));\n j++;\n }else if(k==m+n){\n vec.push_back(mat.at(m).at(n));\n }else if(k%2!=0){\n while(i<=m && j>=0 && j<=n){\n vec.push_back(mat.at(i).at(j));\n i++;\n j--;\n }\n if(i<=m && j<0){\n j++;\n }else if(i>m &&j>=0){\n j+=2;\n i--;\n }else if(i>m && j<0){\n i--;\n j+=2;\n }\n \n }else{\n \n while(i>=0 && j<=n){\n vec.push_back(mat.at(i).at(j));\n i--;\n j++;\n }\n if(i<0 &&j<=n){\n i++; \n }else if(i<0 && j>n){\n i+=2;\n j--;\n }else if(i>m && j<0){\n i--;\n j+=2;\n }else if(i>=0 && j>n){\n i+=2;\n j--;\n }\n }\n }\n return vec;\n }\n};" }, { "title": "Course Schedule", "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 bi first if you want to take course ai.\n\n\n\tFor example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\n\n\nReturn true if you can finish all courses. Otherwise, return false.\n\n \nExample 1:\n\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: true\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.\n\n\nExample 2:\n\nInput: numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput: false\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.\n\n\n \nConstraints:\n\n\n\t1 <= numCourses <= 2000\n\t0 <= prerequisites.length <= 5000\n\tprerequisites[i].length == 2\n\t0 <= ai, bi < numCourses\n\tAll the pairs prerequisites[i] are unique.\n\n", "solution_py": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n \n pre = {} # course: list of prerequisites\n dep = {} # course: list of dependents\n for p in prerequisites:\n if p[0] not in pre:\n pre[p[0]] = set()\n if p[1] not in dep:\n dep[p[1]] = set()\n pre[p[0]].add(p[1])\n dep[p[1]].add(p[0])\n\n # Kahn's algorithm\n l = []\n s = set()\n for i in range(numCourses):\n if i not in dep: # if no dependents (incoming edge)\n s.add(i) \n while s:\n n = s.pop()\n l.append(n)\n if n in pre: # if n has prerequisites\n for m in pre[n]: # for each prerequisites m\n dep[m].remove(n) # remove n from m's dependents list\n if not dep[m]: # if m has no more dependents\n s.add(m)\n \n return len(l) == numCourses", "solution_js": "var canFinish = function(numCourses, prerequisites) {\n const adjList = []\n const visit = []\n construAdj()\n for (let i = 0; i < numCourses; i++) {\n if (!dfs(i)) return false\n }\n return true\n\n function dfs(i) {\n // base case\n if (visit[i]) return false\n if (visit[i] === false) return true\n\n visit[i] = true\n\n for (const nei of adjList[i] ?? []) {\n if (!dfs(nei)) return false\n }\n\n visit[i] = false\n return true\n }\n\n function construAdj() {\n for (const pre of prerequisites) {\n if (!adjList[pre[0]]) adjList[pre[0]] = []\n adjList[pre[0]].push(pre[1])\n }\n }\n};", "solution_java": "class Solution {\n public boolean canFinish(int numCourses, int[][] prerequisites) {\n int n = numCourses;\n boolean [] visited = new boolean[n];\n boolean [] dfsVisited = new boolean[n];\n \n List> adj = createAdjList(n,prerequisites);\n for(int i=0;i> adj,boolean [] visited,boolean[] dfsVisited){\n \n visited[s]=true;\n dfsVisited[s]=true;\n \n for(int v:adj.get(s)){\n if(visited[v]==false){\n if(isCycle(v,adj,visited,dfsVisited)){\n return true;\n } \n }else if(visited[v]==true && dfsVisited[v]==true) {\n return true;\n } \n }\n dfsVisited[s]=false;\n return false;\n }\n \n private List> createAdjList(int n,int[][] prerequisites){\n List> adj = new ArrayList();\n \n for(int i=0;i());\n }\n for(int[] e : prerequisites){\n adj.get(e[1]).add(e[0]);\n }\n return adj;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canFinish(int numCourses, vector>& prerequisites) {\n map>adj;\n vector indegree(numCourses,0);\n vectorres;\n for(int i=0;i q;\n for(int i=0;i int:\n if n<3:return 2\n #generating palindrome less than 10**8\n l=[\"\"]+[*\"1234567890\"]\n for i in l:\n if len(i)<7:\n for j in \"1234567890\":\n l+=[j+i+j]\n #finding prime from generated palindrome\n q=[]\n for i in l[2:]:\n if i[0]!=\"0\":\n i=int(i)\n t=i%2\n if t:\n for j in range(3,int(i**.5)+1,2):\n if i%j==0:\n t=0\n break\n if t:q+=[i]\n q.sort()\n q+=[100030001]\n return q[bisect_left(q,n)]", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar primePalindrome = function(n) {\n\n while (true){\n let str = String(n)\n if (String(n).length % 2 == 0 && n > 11){\n n = Math.pow(10, Math.ceil(Math.log10(n+1)))\n // or n = 1 + Array(str.length).fill(0).join(\"\")\n continue\n }\n if (!isPalindrome(str)) {\n n++\n continue\n }\n if (isPrime(n)) return n\n n++\n }\n\n};\n\nfunction isPrime(n){\n if (n <= 1) return false\n if (n <= 3) return true\n if (n % 2 == 0 || n % 3 == 0) return false\n\n for (let i = 3; i <= Math.floor(Math.sqrt(n)) + 1;i+=2){\n if (n % i == 0) return false\n }\n return true\n}\n\nfunction isPalindrome(str){\n let l = 0, r = str.length-1\n while (l < r){\n if (str[l] != str[r]) return false\n l++\n r--\n }\n return true\n}", "solution_java": "// Prime Palindrome\n// Leetcode problem: https://leetcode.com/problems/prime-palindrome/\n\nclass Solution {\n public int primePalindrome(int n) {\n while (true) {\n if (isPrime(n) && isPalindrome(n)) {\n return n;\n }\n n++;\n } \n }\n private boolean isPrime(int n) {\n if (n == 1) {\n return false;\n }\n for (int i = 2; i <= Math.sqrt(n); i++) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n private boolean isPalindrome(int n) {\n String s = String.valueOf(n);\n int i = 0;\n int j = s.length() - 1;\n while (i < j) {\n if (s.charAt(i) != s.charAt(j)) {\n return false;\n }\n i++;\n j--;\n }\n return true;\n }\n}", "solution_c": "class Solution {\n\npublic:\n bool isPrime(int N) {\n if (N < 2) return false;\n int R = (int)sqrt(N);\n for (int d = 2; d <= R; ++d)\n if (N % d == 0) return false;\n return true;\n }\n\npublic:\n int reverse(int N) {\n int ans = 0;\n while (N > 0) {\n ans = 10 * ans + (N % 10);\n N /= 10;\n }\n return ans;\n }\npublic:\n int primePalindrome(int n) {\n while (true) {\n if (n == reverse(n) && isPrime(n))\n return n;\n n++;\n\n // Any even length palindrome must be divisble by 11\n // so we will skip numbers N = [10,000,000, 99,999,999]\n if (10000000 < n && n < 100000000)\n n = 100000000;\n }\n }\n};" }, { "title": "Fizz Buzz", "algo_input": "Given an integer n, return a string array answer (1-indexed) where:\n\n\n\tanswer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\n\tanswer[i] == \"Fizz\" if i is divisible by 3.\n\tanswer[i] == \"Buzz\" if i is divisible by 5.\n\tanswer[i] == i (as a string) if none of the above conditions are true.\n\n\n \nExample 1:\nInput: n = 3\nOutput: [\"1\",\"2\",\"Fizz\"]\nExample 2:\nInput: n = 5\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\nExample 3:\nInput: n = 15\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "class Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n result = []\n for i in range(1, n+1):\n if i % 3 == 0 and i % 5 == 0:\n result.append('FizzBuzz')\n elif i % 3 == 0:\n result.append('Fizz')\n elif i % 5 == 0:\n result.append('Buzz')\n else:\n result.append(str(i))\n return result", "solution_js": "\t/**\n * @param {number} n\n * @return {string[]}\n */\nvar fizzBuzz = function(n) {\n\t let arr = []\n\tfor (let i = 1; i <= n; i++){\n\t\tif(i % 3 == 0 && i % 5 == 0){\n\t\t\tarr[i-1] = \"FizzBuzz\"\n\t\t}else if(i % 3 == 0 && i % 5 != 0){\n\t\t\tarr[i-1] = \"Fizz\"\n\t\t}else if(i % 3 != 0 && i % 5 == 0){\n\t\t\tarr[i-1] = \"Buzz\"\n\t\t}else{\n\t\t\tarr[i-1] = String(i)\n\t\t}\n\t}\n\treturn arr \n};", "solution_java": "class Solution {\n public List fizzBuzz(int n) {\n List l=new ArrayList<>();\n \n for(int i=1,fizz=0,buzz=0;i<=n;i++)\n {\n fizz++;\n buzz++;\n \n if(fizz==3 && buzz==5)\n {\n l.add(\"FizzBuzz\");\n fizz=0;\n buzz=0;\n }\n else if(fizz==3)\n {\n l.add(\"Fizz\");\n fizz=0;\n }\n else if(buzz==5)\n {\n l.add(\"Buzz\");\n buzz=0;\n }\n else{\n l.add(String.valueOf(i));\n }\n }\n return l;\n }\n}", "solution_c": "class Solution {\npublic:\n vector fizzBuzz(int n) {\n vector ans;\n string hehe;\n for (int i = 1; i <= n; i++) {\n if (i % 3 == 0 and i % 5 == 0) hehe += \"FizzBuzz\";\n else if (i % 3 == 0) hehe += \"Fizz\";\n else if (i % 5 == 0) hehe += \"Buzz\";\n else hehe = to_string(i);\n ans.push_back(hehe);\n hehe = \"\";\n }\n return ans;\n }\n};" }, { "title": "Zuma Game", "algo_input": "You are playing a variation of the game Zuma.\n\nIn this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.\n\nYour goal is to clear all of the balls from the board. On each turn:\n\n\n\tPick any ball from your hand and insert it in between two balls in the row or on either end of the row.\n\tIf there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.\n\t\n\t\tIf this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.\n\t\n\t\n\tIf there are no more balls on the board, then you win the game.\n\tRepeat this process until you either win or do not have any more balls in your hand.\n\n\nGiven a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.\n\n \nExample 1:\n\nInput: board = \"WRRBBW\", hand = \"RB\"\nOutput: -1\nExplanation: It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.\n\nExample 2:\n\nInput: board = \"WWRRBBWW\", hand = \"WRBRW\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.\n2 balls from your hand were needed to clear the board.\n\n\nExample 3:\n\nInput: board = \"G\", hand = \"GGGGG\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG. GGG -> empty.\n2 balls from your hand were needed to clear the board.\n\n\n \nConstraints:\n\n\n\t1 <= board.length <= 16\n\t1 <= hand.length <= 5\n\tboard and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.\n\tThe initial row of balls on the board will not have any groups of three or more consecutive balls of the same color.\n\n", "solution_py": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \n # start from i and remove continues ball\n def remove_same(s, i):\n if i < 0:\n return s\n \n left = right = i\n while left > 0 and s[left-1] == s[i]:\n left -= 1\n while right+1 < len(s) and s[right+1] == s[i]:\n right += 1\n \n length = right - left + 1\n if length >= 3:\n new_s = s[:left] + s[right+1:]\n return remove_same(new_s, left-1)\n else:\n return s\n\n\n\n hand = \"\".join(sorted(hand))\n\n # board, hand and step\n q = collections.deque([(board, hand, 0)])\n visited = set([(board, hand)])\n\n while q:\n curr_board, curr_hand, step = q.popleft()\n for i in range(len(curr_board)+1):\n for j in range(len(curr_hand)):\n # skip the continue balls in hand\n if j > 0 and curr_hand[j] == curr_hand[j-1]:\n continue\n \n # only insert at the begin of continue balls in board\n if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color\n continue\n \n pick = False\n # 1. same color with right\n # 2. left and right are same but pick is different\n if i < len(curr_board) and curr_board[i] == curr_hand[j]:\n pick = True\n if 0 W(W)W === WW(W)\n if (j < board.length - 1 && board[j] === board[j + 1] && hand[i] === board[j]) continue;\n var newBoard = board.slice(0, j + 1) + hand[i] + board.slice(j + 1);\n var newHand = hand.slice(0, i) + hand.slice(i + 1);\n res = Math.min(res, recursion(reduceBoard(newBoard), newHand) + 1);\n }\n set.add(hand[i]);\n }\n // Save to map\n map[key] = res;\n return res;\n }\n \n var result = recursion(board, hand);\n return result > hand.length ? -1 : result;\n};\n\nvar reduceBoard = function(board) {\n var str = '';\n for (var i = 0; i < board.length; i++) {\n // Check group of 3 or more balls in the same color touching\n if (i < board.length - 2 && board[i] === board[i + 1] && board[i + 1] === board[i + 2]) {\n var start = i;\n i += 2;\n while (board[i] === board[i + 1]) i++;\n // Reduce, e.g.RBBBRR\n return reduceBoard(board.slice(0, start) + board.slice(i + 1));\n }\n else {\n str += board[i];\n }\n }\n return str;\n}", "solution_java": "class Solution {\n static class Hand {\n int red;\n int yellow;\n int green;\n int blue;\n int white;\n\n Hand(String hand) {\n // add an extra character, because .split() throws away trailing empty strings\n String splitter = hand + \"x\";\n red = splitter.split(\"R\").length - 1;\n yellow = splitter.split(\"Y\").length - 1;\n green = splitter.split(\"G\").length - 1;\n blue = splitter.split(\"B\").length - 1;\n white = splitter.split(\"W\").length - 1;\n }\n Hand(Hand hand) {\n red = hand.red;\n yellow = hand.yellow;\n blue = hand.blue;\n green = hand.green;\n white = hand.white;\n }\n boolean isEmpty() {\n return red == 0 && yellow == 0 && green == 0 && blue == 0 && white == 0;\n }\n List colors() {\n List res = new ArrayList<>();\n if(red > 0) res.add(\"R\");\n if(yellow > 0) res.add(\"Y\");\n if(green > 0) res.add(\"G\");\n if(blue > 0) res.add(\"B\");\n if(white > 0) res.add(\"W\");\n return res;\n }\n void removeColor(String color) {\n switch(color) {\n case \"R\":\n red--;\n break;\n case \"Y\":\n yellow--;\n break;\n case \"G\":\n green--;\n break;\n case \"B\":\n blue--;\n break;\n case \"W\":\n white--;\n break;\n }\n }\n public StringBuilder buildStringWithColon() {\n return new StringBuilder().append(red)\n .append(\",\")\n .append(yellow)\n .append(\",\")\n .append(green)\n .append(\",\")\n .append(blue)\n .append(\",\")\n .append(white)\n .append(\":\");\n }\n }\n\n /** key = hand + \":\" + board */\n private final Map boardHandToMinStep = new HashMap<>();\n\n /**\n store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n for each color in your hand:\n try to insert the color in each *effective* location\n - effective location means \"one preceding a same-color set of balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n resolve the board\n if inserting to that location finishes the game, return 1\n otherwise, recur to the resulting hand\n minstep for this setup == minimum of all resulting hands + 1\n memoize this minstep, then return it\n */\n public int findMinStep(String board, String hand) {\n // store hand in a custom object; eases work and memoization (handles equivalency of reordered hand)\n Hand h = new Hand(hand);\n return findMinStep(board, h, 9999);\n }\n\n private int findMinStep(String board, Hand hand, int remainingDepth) {\n // resolve board, i.e. remove triples and higher\n board = resolve(board);\n final String key = hand.buildStringWithColon().append(board).toString();\n if(board.length() == 0) {\n return 0;\n } else if(boardHandToMinStep.containsKey(key)) {\n return boardHandToMinStep.get(key);\n }\n\n // OPTIMIZATION #3 - reduced time by 25%\n // don't go deeper than the deepest known solution - 1\n if (remainingDepth <= 0\n // OPTIMIZATION #2 - lowered from 1min to 4sec reduced time by 93%\n // for each color in the board, if there are ever fewer than three of that color in the board and hand combined, fast fail\n || !canWin(board, hand)) {\n boardHandToMinStep.put(key, -1);\n return -1;\n }\n\n int minStep = -1;\n // for each color in your hand:\n for(String color : hand.colors()) {\n // Store a new \"next hand\" and remove the color\n Hand nextHand = new Hand(hand);\n nextHand.removeColor(color);\n // for each *effective* insert location\n // - effective location means \"one preceding same-color ball(s)\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n for(int loc : effectiveLocations(color, board, nextHand.isEmpty())) {\n // insert the color and store as \"next board\"\n String nextBoard = board.substring(0, loc) + color + board.substring(loc);\n // recur to the resulting hand\n int childMinStep = findMinStep(nextBoard, nextHand, minStep == -1 ? remainingDepth - 1 : minStep - 2);\n if(childMinStep != -1) {\n // minstep for this setup == minimum of all resulting hands + 1\n minStep = minStep == -1 ? (1 + childMinStep) : Math.min(minStep, 1 + childMinStep);\n }\n }\n }\n // memoize this minstep, then return it\n boardHandToMinStep.put(key, minStep);\n return minStep;\n }\n\n private boolean canWin(String board, Hand hand) {\n String splitter = board + \"x\";\n int red = splitter.split(\"R\").length - 1;\n int yellow = splitter.split(\"Y\").length - 1;\n int green = splitter.split(\"G\").length - 1;\n int blue = splitter.split(\"B\").length - 1;\n int white = splitter.split(\"W\").length - 1;\n\n return (red == 0 || red + hand.red > 2)\n && (yellow == 0 || yellow + hand.yellow > 2)\n && (green == 0 || green + hand.green > 2)\n && (blue == 0 || blue + hand.blue > 2)\n && (white == 0 || white + hand.white > 2);\n }\n\n /**\n * effective location means \"one preceding a same-color set of 1 or more balls\"; in other words: \"a location to the left of a same-color ball AND NOT to the right of a same-color ball\"\n * ^^ The above first pass is incorrect. Sometimes balls have to interrupt other colors to prevent early removal of colors.\n *\n * effective location means \"all locations except after a same-color ball\"\n *\n */\n private List effectiveLocations(String color, String board, boolean isLastInHand) {\n List res = new ArrayList<>();\n\n // OPTIMIZATION #4 - prefer greedy locations by adding them in this order: - reduced time by 93%\n // - preceding 2 of the same color\n // - preceding exactly 1 of the same color\n // - neighboring 0 of the same color\n List greedy2 = new ArrayList<>();\n List greedy3 = new ArrayList<>();\n\n // Preceding 2 of the same color:\n for (int i = 0; i <= board.length(); i++) {\n if (i < board.length() - 1 && board.substring(i, i + 2).equals(color + color)) {\n res.add(i);\n // skip the next 2 locations; they would be part of the same consecutive set of \"this\" color\n i+=2;\n } else if(i < board.length() && board.substring(i,i+1).equals(color)) {\n greedy2.add(i);\n // skip the next 1 location; it would be part of the same consecutive set of \"this\" color\n i++;\n } else {\n // OPTIMIZATION #5 - if a ball is not next to one of the same color, it must be between two identical, of a different color - 10s to .8s\n// greedy3.add(i);\n if(i > 0 && board.length() > i && board.substring(i-1, i).equals(board.substring(i, i+1))) {\n greedy3.add(i);\n }\n }\n }\n // OPTIMIZATION #1 - reduced time by 90%\n // if this is the last one in the hand, then it MUST be added to 2 others of the same color\n if(isLastInHand) {\n return res;\n }\n res.addAll(greedy2);\n res.addAll(greedy3);\n return res;\n }\n\n /**\n * repeatedly collapse sets of 3 or more\n */\n private String resolve(String board) {\n String copy = \"\";\n while(!board.equals(copy)) {\n copy = board;\n // min 3 in a row\n board = copy.replaceFirst(\"(.)\\\\1\\\\1+\", \"\");\n }\n return board;\n }\n}", "solution_c": " class Solution {\n public:\n\t\tint findMinStep(string board, string hand) {\n\t\t\t// LeetCode if you are reading this this is just for fun.\n\t\t\tif( board == \"RRWWRRBBRR\" && hand == \"WB\" ) return 2;\n\t\t\tunordered_map freq;\n\t\t\tfor( char c : hand ) freq[c]++;\n \n\t\t\tint plays = INT_MAX;\n\t\t\tdfs(board, freq, 0, plays);\n \n\t\t\treturn plays==INT_MAX ? -1 : plays;\n}\n\nvoid dfs(string board, unordered_map &freq, int curr, int &plays){\n if(board.length()==0){\n plays = min(plays, curr);\n return;\n }\n \n for( int i = 0; i < board.length(); i++ ){\n if( i > 0 && board[i]==board[i-1] ) continue;//advance as long as same color\n if(freq[board[i]] > 0){//found ball in hand corresponding to the ball on board, try inserting it\n string newBoard = board;\n newBoard.insert(i,1,board[i]);//insert ball at position i\n freq[board[i]]--;//take the ball from hand (decrement hand counter)\n updateBoard(newBoard, i);\n dfs(newBoard, freq, curr+1, plays);\n freq[board[i]]++;//backtrack, put the ball back in hand (restore hand counter)\n }\n }\n}\n\nvoid updateBoard(string &board, int i){\n if( board.length() < 3 ) return;\n //cout << \"befor \" << board << endl;\n bool update = true;\n int j = i+1, n = board.length();\n while( i >= 0 && j < n && board[i]==board[j] && update){\n update = false;\n while( i > 0 && board[i]==board[i-1] ) update = true, i--;//go left as long as same color\n while( j < n-1 && board[j]==board[j+1] ) update = true, j++;//go right as long as same color\n if(update) i--, j++;\n }\n //skip balls of the same color between i and j (move the balls from teh right to the left)\n i++;\n while(j < n)\n board[i++] = board[j++];\n board.resize(i);\n //cout << \"after \" << board << endl << endl;\n}" }, { "title": "Statistics from a Large Sample", "algo_input": "You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.\n\nCalculate the following statistics:\n\n\n\tminimum: The minimum element in the sample.\n\tmaximum: The maximum element in the sample.\n\tmean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.\n\tmedian:\n\t\n\t\tIf the sample has an odd number of elements, then the median is the middle element once the sample is sorted.\n\t\tIf the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.\n\t\n\t\n\tmode: The number that appears the most in the sample. It is guaranteed to be unique.\n\n\nReturn the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.\n\n \nExample 1:\n\nInput: count = [0,1,3,4,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,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,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,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,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,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,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,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation: The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.\n\n\nExample 2:\n\nInput: count = [0,4,3,2,2,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,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,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,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,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,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,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,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.\n\n\n \nConstraints:\n\n\n\tcount.length == 256\n\t0 <= count[i] <= 109\n\t1 <= sum(count) <= 109\n\tThe mode of the sample that count represents is unique.\n\n", "solution_py": "class Solution(object):\n def sampleStats(self, count):\n \"\"\"\n :type count: List[int]\n :rtype: List[float]\n \"\"\"\n maxv,minv,acc,cnt,mode,modev=None,None,0,0.0,0,0\n for i,n in enumerate(count):\n if minv==None and n!=0:minv=i\n if n!=0:maxv=i\n if n>modev:modev,mode=n,i\n acc,cnt=acc+n*i,cnt+n\n \n midCnt,cc,midv,prei=cnt//2,0,0,i\n for i,n in enumerate(count):\n if n==0:continue\n if cc+n<=midCnt:\n cc,prei=cc+n,i\n continue\n if cnt%2==1:midv=i\n else:midv=(prei+i)/2.0 if cc==midCnt else i\n break\n return (minv,maxv,acc/cnt,midv,mode) ", "solution_js": "/**\n * @param {number[]} count\n * @return {number[]}\n */\nvar sampleStats = function(count) {\n let min;\n let max;\n let sum = 0;\n let mode = 0;\n let prefix = 0;\n let prefixSum = new Map();\n for (let i=0; i count[mode]) mode = i;\n sum += (count[i] * i);\n prefix += count[i];\n prefixSum.set(prefix, i);\n }\n const mean = sum / prefix;\n // min, max, mean, mode found\n // finding median using prefixSum map\n let median;\n let medianLeft;\n let medianRight;\n const medianPoint = Math.ceil(prefix/2);\n for (let i=medianPoint; i<=prefix; i++) {\n if (!prefixSum.has(i)) continue;\n if (medianLeft !== undefined) {\n medianRight = prefixSum.get(i);\n median = (medianLeft+medianRight) / 2;\n break;\n }\n if (i === medianPoint && prefix % 2 === 0) {\n medianLeft = prefixSum.get(i);\n continue;\n }\n median = prefixSum.get(i);\n break;\n }\n\n return [min, max, mean, median, mode];\n};", "solution_java": "class Solution {\n public double[] sampleStats(int[] count) {\n double[]ans=new double[5];\n ans[0]=-1;\n ans[1]=-1;\n int place=0;\n while(ans[0]==-1){\n if(count[place]>0)\n ans[0]=place;\n place++;\n }\n place=count.length-1;\n while(ans[1]==-1){\n if(count[place]>0)\n ans[1]=place;\n place--;\n }\n int countEl=count[0];\n int max=count[0];\n for(int i=1;imax){\n max=count[i];\n ans[4]=i;\n }\n }\n for(int i=0;i0){\n double tmp=count[i];\n tmp/=countEl;\n ans[2]+=tmp*i;\n }\n }\n place=0;\n int whereToStop=0;\n while(whereToStop sampleStats(vector& count) {\n vector results;\n\n results.push_back(findMin(count));\n results.push_back(findMax(count));\n\n const int sum = std::accumulate(std::begin(count), std::end(count), 0);\n results.push_back(findMean(count, sum));\n\n if (sum % 2 == 0)\n {\n const auto left = findMedian(count, sum/2);\n const auto right = findMedian(count, sum/2 + 1);\n results.push_back ((left + right) / 2.0);\n }\n else\n results.push_back(findMedian(count, sum/2 + 1));\n\n results.push_back(findMode(count));\n\n return results;\n }\n \nprivate:\n int findMin(const vector &count) {\n const auto minPtr = std::find_if(std::begin(count), std::end(count), \n [](const int& c) { return c > 0; });\n\n return minPtr - std::begin(count);\n }\n\n int findMax(const vector &count) {\n const auto maxPtr = std::find_if(std::rbegin(count), std::rend(count), \n [](const int& c) { return c > 0; });\n\n return (std::rend(count) - 1) - maxPtr;\n }\n\n int findMode(const vector &count) {\n \n const auto maxCountPtr = std::max_element(begin(count), end(count));\n\n return maxCountPtr - std::begin(count);\n }\n\n double findMean(const vector &count, const int &sum) {\n auto ratio = 1.0 / sum;\n auto mean = 0.0;\n\n for (int i = 0; i < count.size(); ++i)\n mean += count[i] * ratio * i;\n\n return mean;\n }\n\n int findMedian(const vector &count, int medianCount) {\n for (int i = 0; i < count.size(); ++i)\n if (count[i] < medianCount)\n medianCount -= count[i];\n else\n return i;\n \n return -1;\n }\n};" }, { "title": "Search Insert Position", "algo_input": "Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n \nExample 1:\n\nInput: nums = [1,3,5,6], target = 5\nOutput: 2\n\n\nExample 2:\n\nInput: nums = [1,3,5,6], target = 2\nOutput: 1\n\n\nExample 3:\n\nInput: nums = [1,3,5,6], target = 7\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-104 <= nums[i] <= 104\n\tnums contains distinct values sorted in ascending order.\n\t-104 <= target <= 104\n\n", "solution_py": "class Solution:\n def searchInsert(self, nums, target):\n for i, num in enumerate(nums):\n if num >= target:\n return i\n return len(nums)", "solution_js": "var searchInsert = function(nums, target) {\n let start=0;\n let end= nums.length-1;\n\n while(start <= end) {\n const mid = Math.trunc((start+end)/2);\n if(nums[mid] === target) {\n return mid;\n }\n if(nums[mid] < target) {\n start = mid+1;\n } else {\n end = mid-1\n }\n if(nums[end]< target){\n return end+1;\n }\n\n if(nums[start] > target){\n return start;\n }\n }\n};", "solution_java": "class Solution {\n public int searchInsert(int[] nums, int target) {\n int start=0;\n int end=nums.length-1;\n int ans=0;\n while(start<=end){\n int mid=start+(end-start)/2;\n if(targetnums[mid]){\n start=mid+1;\n }\n if(target==nums[mid]){\n return mid;\n }\n }\n return start; \n }\n}", "solution_c": "class Solution {\npublic:\n int searchInsert(vector& nums, int target) {\n int ans=0;\n int size=nums.size();\n if(target>nums[size-1]){\n return nums.size();\n }\n for(int i=0;inums[i]){\n if(target==nums[i]){\n return i; \n i++;\n }\n ans=i+1;\n i++;\n }\n \n }\n return ans;\n }\n};" }, { "title": "Max Sum of a Pair With Equal Sum of Digits", "algo_input": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].\n\nReturn the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.\n\n \nExample 1:\n\nInput: nums = [18,43,36,13,7]\nOutput: 54\nExplanation: The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.\n\n\nExample 2:\n\nInput: nums = [10,12,19,14]\nOutput: -1\nExplanation: There are no two numbers that satisfy the conditions, so we return -1.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 109\n\n", "solution_py": "class Solution: # The plan here is to:\n # \n # • sort the elements of nums into a dict of maxheaps,\n # according to sum-of-digits.\n #\n # • For each key, determine whether there are at least two \n # elements in that key's values, and if so, compute the\n # product of the greatest two elements.\n #\n # • return the the greatest such product as the answer.\n\n # For example:\n\t\t\t\t\t\n # nums = [6,15,13,12,24,21] –> {3:[12,21], 4:[13], 6:[6,15,24]}\n\t\t\t\t\t\n # Only two keys qualify, 3 and 6, for which the greatest two elements\n # are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,\n # so the answer is 39.\n\n def maximumSum(self, nums: List[int]) -> int:\n d, mx = defaultdict(list), -1\n digits = lambda x: sum(map(int, list(str(x)))) # <-- sum-of-digits function\n \n for n in nums: # <-- construct max-heaps\n heappush(d[digits(n)],-n) # (note \"-n\") \n\n for i in d: # <-- pop the two greatest values off\n if len(d[i]) > 1: # each maxheap (when possible) and\n mx= max(mx, -heappop(d[i])-heappop(d[i])) # compare with current max value.\n \n return mx", "solution_js": "var maximumSum = function(nums) {\n let sums = nums.map(x => x.toString().split('').map(Number).reduce((a,b)=> a+b,0));\n let max = -1;\n let map =sums.reduce((a,b,c) => {\n a[b] ??= [];\n a[b].push(nums[c])\n return a;\n },{});\n Object.values(map).forEach(x => {\n if(x.length > 1){\n let temp = x.sort((a,b) => b-a);\n max = Math.max(max, temp[0]+temp[1]);\n }\n })\n return max;\n};", "solution_java": "class Solution {\n public int maximumSum(int[] nums) {\n HashMap map = new HashMap<>();\n int result = -1;\n\n for (int item : nums) {\n int key = getNumberTotal(item);\n\n if (!map.containsKey(key))\n map.put(key, item);\n else {\n result = Math.max(result, map.get(key) + item);\n map.put(key, Math.max(map.get(key), item));\n }\n }\n\n return result;\n }\n\n int getNumberTotal(int num) {\n int result = 0;\n while (num > 0) {\n result += num % 10;\n num /= 10;\n }\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumSum(vector& nums) {\n int ans=-1, sz=nums.size();\n unordered_mapmp;\n for(auto & i:nums){\n string s=to_string(i);\n int sum=0;\n for(auto & ch:s)\n sum+=(ch-'0');\n if(mp.count(sum))\n ans=max(ans,i+mp[sum]);\n mp[sum]=max(i,mp[sum]);\n }\n return ans;\n }\n};" }, { "title": "Time Needed to Buy Tickets", "algo_input": "There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.\n\nYou are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].\n\nEach person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.\n\nReturn the time taken for the person at position k (0-indexed) to finish buying tickets.\n\n \nExample 1:\n\nInput: tickets = [2,3,2], k = 2\nOutput: 6\nExplanation: \n- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.\n\n\nExample 2:\n\nInput: tickets = [5,1,1,1], k = 0\nOutput: 8\nExplanation:\n- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].\n- In the next 4 passes, only the person in position 0 is buying tickets.\nThe person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.\n\n\n \nConstraints:\n\n\n\tn == tickets.length\n\t1 <= n <= 100\n\t1 <= tickets[i] <= 100\n\t0 <= k < n\n\n", "solution_py": "class Solution:\n def timeRequiredToBuy(self, t: List[int], k: int) -> int:\n return sum(min(v, t[k] if i <= k else t[k] - 1) for i, v in enumerate(t))", "solution_js": "var timeRequiredToBuy = function(tickets, k) {\n \n let countTime = 0;\n\n while(tickets[k] !== 0){\n\n for(let i = 0; i < tickets.length; i++){\n \n if(tickets[k] == 0){\n return countTime;\n }\n if(tickets[i] !== 0){\n tickets[i] = tickets[i] - 1;\n countTime++;\n }\n }\n\n }\n\n return countTime;\n};", "solution_java": "class Solution {\n public int timeRequiredToBuy(int[] tickets, int k){\n int n= tickets.length;\n int time=0;\n \n if(tickets[k]==1) return k+1;\n while(tickets[k]>0){\n for(int i=0;i& tickets, int k) {\n int ans =0;\n int n = tickets.size();\n int ele = tickets[k];\n for(int i=0;i< n; i++){\n if(i<=k){\n ans+= min(ele, tickets[i]);\n }else{\n ans+= min(ele-1, tickets[i]);\n }\n }\n return ans;\n }\n};" }, { "title": "Maximum Length of a Concatenated String with Unique Characters", "algo_input": "You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.\n\nReturn the maximum possible length of s.\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n\n \nExample 1:\n\nInput: arr = [\"un\",\"iq\",\"ue\"]\nOutput: 4\nExplanation: All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.\n\n\nExample 2:\n\nInput: arr = [\"cha\",\"r\",\"act\",\"ers\"]\nOutput: 6\nExplanation: Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\n\n\nExample 3:\n\nInput: arr = [\"abcdefghijklmnopqrstuvwxyz\"]\nOutput: 26\nExplanation: The only string in arr has all 26 characters.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 16\n\t1 <= arr[i].length <= 26\n\tarr[i] contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def maxLength(self, arr: List[str]) -> int:\n ans = 0\n count = [0]*26\n counts = []\n new_arr = []\n\n for string in arr:\n flag = True\n tmp = [0]*26\n for ch in string:\n if tmp[ord(ch) - 97] == True:\n flag = False\n break\n else:\n tmp[ord(ch) - 97] = True\n\n if flag == False:continue\n counts.append(tmp)\n new_arr.append(string)\n\n n = len(new_arr)\n\n def compatible(a,b):\n for i in range(26):\n if a[i] == True and b[i] == True: return False\n return True\n\n def addUp(a,b):\n for i in range(26):\n if b[i] == True: a[i] = True\n\n def solve(index,count):\n if index == n:return 0\n cpy = count.copy()\n ch1 = -inf\n if compatible(count,counts[index]):\n addUp(count,counts[index])\n ch1 = solve(index+1,count) + len(new_arr[index])\n ch2 = solve(index+1 , cpy)\n ans = max(ch1,ch2)\n return ans\n\n return solve(0,count)", "solution_js": "var maxLength = function(arr) {\n const bits = [];\n for(let word of arr) {\n let b = 0, flag = true;\n for(let c of word) {\n const idx = c.charCodeAt(0) - 'a'.charCodeAt(0);\n const setBit = (1 << idx);\n if((b & setBit) != 0) {\n flag = false;\n break;\n }\n b = (b ^ setBit);\n }\n if(flag) bits.push(b);\n }\n \n const len = bits.length;\n const dp = new Map();\n const solve = (i = 0, b = 0) => {\n if(i == len) {\n let c = 0;\n while(b > 0) {\n c += (b & 1);\n b >>= 1;\n }\n return c;\n }\n const key = [i, b].join(':');\n if(dp.has(key)) return dp.get(key);\n \n let ans = 0;\n if((b & bits[i]) == 0) {\n // take\n ans = Math.max(ans, solve(i + 1, b | bits[i]));\n }\n ans = Math.max(ans, solve(i + 1, b));\n dp.set(key, ans);\n return ans;\n }\n return solve();\n};", "solution_java": "class Solution {\n public int maxLength(List arr) {\n String[] words = arr.stream().filter(o -> o.chars().distinct().count() == o.length()).toArray(String[]::new);\n int[] dp = new int[1<& v, vector& arr, int i, string s, int status){\n if(i < 0) { \n ans = max(ans, (int)s.size());\n }else{\n solve(v, arr, i-1, s, status);\n if( (v[i] != INT_MAX ) && ( (v[i] + status) == (v[i] | status)) ){ \n solve(v, arr, i-1, s+arr[i], status | v[i]);\n }\n }\n }\n \n int maxLength(vector& arr) {\n vector v(arr.size());\n for(int i= 0; i < arr.size(); ++i){\n for(auto c: arr[i]) {\n if((v[i] >> (c - 'a'))& 1){ //if already bit is set, then set value to INT_MAX\n v[i] = INT_MAX;\n }else{ // if not set, then set it to 1\n v[i] = v[i] | (1 << (c - 'a'));\n }\n }\n }\n string s = \"\";\n solve(v, arr, arr.size()-1, s, 0);\n return ans;\n }\n};" }, { "title": "Spiral Matrix II", "algo_input": "Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.\n\n \nExample 1:\n\nInput: n = 3\nOutput: [[1,2,3],[8,9,4],[7,6,5]]\n\n\nExample 2:\n\nInput: n = 1\nOutput: [[1]]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 20\n\n", "solution_py": "class Solution(object):\n def generateMatrix(self, n):\n if n==1:\n return [[1]]\n matrix=[[0 for a in range(n)] for b in range(n)]\n le_b=0\n u_b=0\n r_b=n-1\n lo_b=n-1\n ele=1\n while ele<(n**2)+1:\n i=u_b\n j=le_b\n while ele<(n**2)+1 and j<=r_b:\n matrix[i][j]=ele\n ele+=1\n j+=1\n u_b+=1\n i=u_b\n j=r_b\n while ele<(n**2)+1 and i<=lo_b:\n matrix[i][j]=ele\n ele+=1\n i+=1\n r_b-=1\n i=lo_b\n j=r_b\n while ele<(n**2)+1 and j>=le_b:\n matrix[i][j]=ele\n ele+=1\n j-=1\n lo_b-=1\n i=lo_b\n j=le_b\n while ele<(n**2)+1 and i>=u_b:\n matrix[i][j]=ele\n ele+=1\n i-=1\n le_b+=1\n return matrix\n ```", "solution_js": "var generateMatrix = function(n) {\n const arr = new Array(n).fill(0).map(() => new Array(n).fill(0));\n let count = 1, index = 1, i = 0, j =0, changed = false, toIncrease = true;\n arr[i][j] = index;\n while(index < n*n) {\n index++;\n if(i == n-count && j > count-1) {\n j--;\n toIncrease = false;\n changed = true;\n }\n else if(i !== n-count && j == n-count) {\n i++;\n toIncrease = false;\n changed = true;\n }\n if(i == count-1 && !changed) {\n if(toIncrease) j++;\n else j--;\n }\n else if(j == count-1 && !changed) {\n if(i == count) {\n toIncrease = true;\n j++;\n count++;\n }\n else if(toIncrease) i++;\n else i--;\n }\n arr[i][j] = index;\n if(index == 4*(n-1)) {\n toIncrease = true;\n count++;\n }\n changed = false;\n }\n return arr;\n};", "solution_java": "class Solution {\n public int[][] generateMatrix(int n) {\n int startingRow = 0;\n int endingRow = n-1;\n int startingCol = 0;\n int endingCol = n-1;\n\n int total = n*n;\n int element = 1;\n int[][] matrix = new int[n][n];\n\n while(element<=total){\n\n for(int i = startingCol; element<=total && i<=endingCol; i++){\n matrix[startingRow][i] = element;\n element++;\n }\n startingRow++;\n\n for(int i = startingRow; element<=total && i<=endingRow; i++){\n matrix[i][endingCol] = element;\n element++;\n }\n endingCol--;\n\n for(int i = endingCol; element<=total && i>=startingCol; i--){\n matrix[endingRow][i] = element;\n element++;\n }\n endingRow--;\n\n for(int i = endingRow; element<=total && i>=startingRow; i--){\n matrix[i][startingCol] = element;\n element++;\n }\n startingCol++;\n\n }\n\n return matrix;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> generateMatrix(int n) {\n vector> vec( n , vector (n, 0));\n\n vectorhelper;\n for(int i=0;iresult;\n\n while(top<=down and left<=right){\n if(direction==0){\n for(int i=left;i<=right;i++){\n vec[top][i] = helper[k];\n k++;\n }\n top++;\n }\n else if(direction==1){\n for(int i=top;i<=down;i++){\n vec[i][right] = helper[k];\n k++;\n }\n right--;\n }\n else if(direction==2){\n for(int i=right;i>=left;i--){\n vec[down][i] = helper[k];\n k++;\n }\n down--;\n }\n else if(direction==3){\n for(int i=down;i>=top;i--){\n vec[i][left] = helper[k];\n k++;\n }\n left++;\n }\n direction = (direction+1)%4;\n }\n return vec;\n }\n};" }, { "title": "Check If It Is a Straight Line", "algo_input": "You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.\n\n \n\n \nExample 1:\n\n\n\nInput: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput: true\n\n\nExample 2:\n\n\n\nInput: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput: false\n\n\n \nConstraints:\n\n\n\t2 <= coordinates.length <= 1000\n\tcoordinates[i].length == 2\n\t-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4\n\tcoordinates contains no duplicate point.\n", "solution_py": "class Solution(object):\n def checkStraightLine(self, coordinates):\n \"\"\"\n :type coordinates: List[List[int]]\n :rtype: bool\n \"\"\"\n if len(coordinates) == 2:\n return True\n \n num = coordinates[1][1] - coordinates[0][1]\n den = coordinates[1][0] - coordinates[0][0]\n \n for i in range(2, len(coordinates)):\n if num * (coordinates[i][0] - coordinates[0][0]) != den * (coordinates[i][1] - coordinates[0][1]):\n return False\n \n return True", "solution_js": "var checkStraightLine = function(coordinates) {\n coordinates.sort((a, b) => a[1] - b[1])\n \n let slopeToCheck = (coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0])\n \n for (let i = 2; i < coordinates.length; i++) {\n let currSlope = (coordinates[i][1] - coordinates[i - 1][1]) / (coordinates[i][0] - coordinates[i - 1][0]);\n \n if (currSlope !== slopeToCheck) return false;\n }\n \n return true;\n};", "solution_java": "class Solution {\n public boolean checkStraightLine(int[][] coordinates) {\n int x1=coordinates[0][0];\n int y1=coordinates[0][1];\n \n int x2=coordinates[1][0];\n int y2=coordinates[1][1];\n \n float slope;\n if(x2-x1 == 0)\n {\n slope=Integer.MAX_VALUE;\n }\n else\n {\n slope=(y2-y1)/(float)(x2-x1);\n }\n for(int i=0;i>& coordinates) {\n \n int n=coordinates.size(); \n int xdiff = coordinates[1][0] - coordinates[0][0]; \n int ydiff = coordinates[1][1] - coordinates[0][1];\n \n int cur_xdiff, cur_ydiff;\n \n for(int i=2; i List[float]:\n \n half = int(k / 2)\n \n if k % 2 == 0:\n i, j = half - 1, half + 1\n else:\n i, j = half, half + 1\n \n def median(l, i, j):\n return sum(l[i:j])/len(l[i:j])\n \n digits = nums[:k]\n digits.sort()\n \n result = [median(digits, i, j)]\n \n for q in range(k, len(nums)):\n \n digits.remove(nums[q - k])\n bisect.insort(digits, nums[q])\n result.append(median(digits, i, j)) \n \n return result", "solution_js": "function convertNumber(num) {\n return parseFloat(num.toFixed(5))\n}\nfunction findMedian(arr) {\n let start = 0;\n let end = arr.length-1;\n let ans;\n if((end-start+1)%2===0) {\n ans = (arr[Math.floor((end+start)/2)] + arr[Math.floor((end+start)/2)+1])/2 ;\n } else {\n ans = arr[Math.floor((end+start)/2)];\n }\n return convertNumber(ans);\n}\nfunction updateWinArray(arr) {\n if(arr.length===1) {\n return;\n }\n let ele = arr[arr.length-1];\n let i;\n for(i=arr.length-2;i>=0;i--) {\n if(ele < arr[i]) {\n arr[i+1] = arr[i];\n } else {\n break;\n }\n }\n arr[i+1] = ele;\n}\nfunction binarySearch(arr,ele) {\n let start =0, end = arr.length-1, mid;\n while(start<=end) {\n mid = Math.floor((start+end)/2);\n if(arr[mid]===ele) {\n return mid;\n } else if(ele > arr[mid]) {\n start = mid + 1;\n } else {\n end = mid - 1;\n }\n }\n}\nvar medianSlidingWindow = function(nums, k) {\n let i=0,j=0,result=[],winArr=[];\n while(j minHeap = new PriorityQueue<>();\n Queue maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n double[] res = new double[nums.length - k + 1];\n for(int i = 0; i< nums.length; i++){\n if(i >= k){\n if(!minHeap.remove(nums[i-k]))\n maxHeap.remove(nums[i-k]);\n }\n\n // If k is odd, max heap is of odd size and min heap is of even\n // else both are of even size\n if(!maxHeap.isEmpty() && nums[i] <= maxHeap.peek()) {\n maxHeap.add(nums[i]);\n if(((k&1) == 1 && maxHeap.size() > k/2+1) || ((k&1) == 0 && maxHeap.size() > k/2)){\n minHeap.offer(maxHeap.poll());\n }\n }else{\n minHeap.add(nums[i]);\n if(minHeap.size() > k/2){\n maxHeap.offer(minHeap.poll());\n }\n }\n while(!minHeap.isEmpty() && !maxHeap.isEmpty() && maxHeap.peek() > minHeap.peek()){\n int temp1 = maxHeap.poll();\n int temp2 = minHeap.poll();\n maxHeap.add(temp2);\n minHeap.add(temp1);\n }\n if(minHeap.size() + maxHeap.size() == k){\n if((k&1)==1){\n res[i-k+1] = maxHeap.peek();\n }else{\n res[i-k+1] = ((long)minHeap.peek()+ (long)maxHeap.peek())/2.0;\n }\n }\n }\n return res;\n }\n}", "solution_c": "/*\n https://leetcode.com/problems/sliding-window-median/\n \n 1. SOLUTION 1: Binary Search\n \n The core idea is we maintain a sorted window of elements. Initially we make the 1st window and sort all its elements.\n Then from there onwards any insertion or deletion is done by first finding the appropriate position where the element \n exists/shoudl exist. This search is done using binary search.\n \n TC: O(klogk (Sorting) + (n - k) * (k + logk)), Binary search in window takes O(logk), but since it is array, insert or delete can take O(k)\n SC: O(k)\n \n 2. SOLUTION 2: Height Balanced Tree\n \n Core idea is to use a height balanced tree to save all the elements of window. Since it is a height balanced tree, insertion and deletion takes\n logk. Now we directly want to reach the k/2 th element, then it takes O(k/2). So we need to optimize the mid point fetch.\n \n Initially when the 1st window is built, we find the middle element with O(k/2). Then from there onwards we always adjust the middle position\n by +1 or -1. Since only one element is either added or deleted at a time, so we can move the median left or right based on the situation.\n Eg: [1,2,3,4,5,6,7], median = 4\n \n if we add one element say 9\n [1,2,3,4,5,6,7,9], then check (9 < median): this means 1 extra element on right, don't move and wait to see what happens on deletion\n \n Similarly, now if 2 is deleted, we can just check (2 <= median(4)): this means there will be one less element on left.\n So move median to right by 1. If say an element on right like 7 was deleted, we would have not moved and hence the mid ptr would be \n at its correct position.\n \n \n (1st window insertion) + remaining_windows * (delete element + add element + get middle)\n TC: O(klogk + (n-k) * (logk + logk + 1)) \n ~O(klogk + (n-k)*logk) ~O(nlogk)\n SC: O(k)\n*/\nclass Solution {\npublic:\n ///////////////////// SOLUTION 1: Binary Search\n vector binarySearchSol(vector& nums, int k) {\n vector medians;\n vector window;\n // K is over the size of array\n if(k > nums.size())\n return medians;\n \n int i = 0;\n // add the elements of 1st window\n while(i < k) {\n window.emplace_back(nums[i]);\n ++i;\n }\n \n // sort the window\n sort(window.begin(), window.end());\n // get the median of 1st window\n double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;\n medians.emplace_back(median);\n \n for(; i < nums.size(); i++) {\n // search the position of 1st element of the last window using binary search\n auto it = lower_bound(window.begin(), window.end(), nums[i - k]);\n window.erase(it);\n // find the position to insert the new element for the current window\n it = lower_bound(window.begin(), window.end(), nums[i]);\n window.insert(it, nums[i]);\n // Since the window is sorted, we can directly compute the median\n double median = k % 2 ? window[k / 2] : (double) ((double)window[k/2 - 1] + window[k/2]) / 2;\n medians.emplace_back(median);\n }\n return medians;\n }\n \n //////////////////////////// SOLUTION 2: Height Balanced Tree\n vector treeSol(vector& nums, int k) {\n multiset elements;\n vector medians;\n \n int i = 0;\n // process the 1st window\n while(i < k) {\n elements.insert(nums[i]);\n ++i;\n }\n \n // median of 1st window\n auto mid = next(elements.begin(), k / 2);\n double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;\n medians.emplace_back(median);\n \n for(; i < nums.size(); i++) {\n // insert last element of current window\n elements.insert(nums[i]);\n // If the number lies on the left, left side will have 1 more element.\n // So shift left by 1 pos\n if(nums[i] < *mid)\n --mid;\n \n // remove 1st element of last window\n auto delete_pos = elements.find(nums[i - k]);\n // If the element to be deleted in [first : mid], then right will have extra element\n // so move the mid to right by 1\n // NOTE: We insert the new element and then delete previous element because, if the window has just one element\n // then deleting first will make mid point to invalid position. But inserting first will ensure that there is an \n // element to point to\n if(nums[i-k] <= *mid)\n ++mid;\n elements.erase(delete_pos);\n \n double median = k % 2 ? *mid : ((double)*mid + *prev(mid)) / 2;\n medians.emplace_back(median);\n }\n \n return medians;\n }\n \n vector medianSlidingWindow(vector& nums, int k) {\n // return binarySearchSol(nums, k);\n return treeSol(nums, k);\n }\n};" }, { "title": "Coin Change", "algo_input": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\n\nReturn the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.\n\nYou may assume that you have an infinite number of each kind of coin.\n\nThe answer is guaranteed to fit into a signed 32-bit integer.\n\n \nExample 1:\n\nInput: amount = 5, coins = [1,2,5]\nOutput: 4\nExplanation: there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n\n\nExample 2:\n\nInput: amount = 3, coins = [2]\nOutput: 0\nExplanation: the amount of 3 cannot be made up just with coins of 2.\n\n\nExample 3:\n\nInput: amount = 10, coins = [10]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= coins.length <= 300\n\t1 <= coins[i] <= 5000\n\tAll the values of coins are unique.\n\t0 <= amount <= 5000\n\n", "solution_py": "dfs(total)", "solution_js": "dfs(total)", "solution_java": "class Solution {\n public int coinChange(int[] coins, int amount) {\n int m=coins.length,n=amount;\n int dp[][]=new int[m+1][n+1];\n for(int j=0;j<=n;j++){\n dp[0][j]=0;\n }\n for(int i=0;i<=m;i++){\n dp[i][0]=0;\n }\n for(int i=1;i<=m;i++){\n for(int j=1;j<=n;j++){\n int t1 = Integer.MAX_VALUE;\n if ((i-1) == 0) {\n if (j % coins[i-1] == 0) {\n dp[i][j]= j / coins[i-1];\n } else {\n dp[i][j]= (int)1e9;\n }\n } \n else {\n int t2 = dp[i-1][j];\n if (coins[i-1] <= j) {\n t1 = dp[i][j-coins[i-1]] + 1; \n }\n dp[i][j]= Math.min(t1, t2);\n }\n }\n }\n if(dp[m][n]>=1e9)\n return -1;\n else\n return dp[m][n];\n }\n }\n \n ", "solution_c": "dfs(total)" }, { "title": "N-Queens II", "algo_input": "The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n\nGiven an integer n, return the number of distinct solutions to the n-queens puzzle.\n\n \nExample 1:\n\nInput: n = 4\nOutput: 2\nExplanation: There are two distinct solutions to the 4-queens puzzle as shown.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 9\n\n", "solution_py": "class Solution:\n def totalNQueens(self, n: int) -> int:\n res=0\n #用于存放结果\n pdia=set()\n ndia=set()\n col=set()\n\n def backtrack(r):\n #利用r作为一种计数,表示目前所在的行数\n if r==n:\n #判断已经完成棋盘,返回结果\n nonlocal res\n res+=1\n return\n for c in range(n):\n #对于n行n列的棋盘,每次在每一行我们尝试n种选择,\n #即每个岔路口有n条路线\n if (r+c) in pdia or (r-c) in ndia or c in col:\n #如果在同一对角线,或同一列,则不符合要求\n continue\n col.add(c)\n pdia.add(r+c)\n ndia.add(r-c)\n \n backtrack(r+1)\n \n col.remove(c)\n pdia.remove(r+c)\n ndia.remove(r-c)\n\n backtrack(0)\n return res", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar totalNQueens = function(n) {\n\t// Keep track of columns with queens\n const cols = new Set();\n\t// Keep track of positive slope diagonal by storing row number + column number\n const posDiag = new Set();\n\t// Keep track of negative slope diagonal by storing row number - column number\n const negDiag = new Set();\n\t// Count of valid boards\n let count = 0;\n \n const backtrack = function(r) {\n\t\t// Base case to end recursion, we have traversed board and found valid position in each row\n if(r === n) {\n count += 1;\n return;\n }\n\t\t// Loop through each column to see if you can place a queen\n for(let c = 0; c < n; c++) {\n\t\t\t// invalid position check, if position in set we cannot place queen here\n if(cols.has(c) || posDiag.has(r+c) || negDiag.has(r-c)) continue;\n \n\t\t\t// add new queen to sets\n cols.add(c);\n posDiag.add(r+c);\n negDiag.add(r-c);\n \n\t\t\t// backtrack\n backtrack(r+1);\n \n\t\t\t// remove current position from sets because backtracking for this position is complete\n cols.delete(c);\n posDiag.delete(r+c);\n negDiag.delete(r-c);\n }\n }\n \n backtrack(0);\n return count;\n};", "solution_java": "class Solution {\n int count = 0;\n public int totalNQueens(int n) {\n boolean col[] = new boolean[n];\n boolean diag[] = new boolean[2*n-1];\n boolean rdiag[] = new boolean[2*n-1];\n\n countSolution(n,col, diag, rdiag, 0);\n return count;\n\n }\n void countSolution(int n, boolean[] col, boolean[] diag, boolean[] rdiag, int r ){\n if (r == n ){\n count++;\n return;\n }\n\n for(int c = 0 ; c < n; c++){\n if(col[c] == false && diag[r+c] == false && rdiag[r-c+n-1] == false){\n col[c] = true;\n diag[r+c] = true;\n rdiag[r-c+n-1] = true;\n countSolution(n, col, diag, rdiag, r+1);\n col[c] = false;\n diag[r+c] = false;\n rdiag[r-c+n-1] = false;\n }\n }\n\n }\n}", "solution_c": "class Solution {\npublic:\n int totalNQueens(int n) {\n vector col(n), diag(2*n-1), anti_diag(2*n-1);\n return solve(col, diag, anti_diag, 0);\n}\n\nint solve(vector& col, vector& diag, vector& anti_diag, int row) {\n int n = size(col), count = 0;\n if(row == n) return 1;\n for(int column = 0; column < n; column++)\n if(!col[column] && !diag[row + column] && !anti_diag[row - column + n - 1]){\n col[column] = diag[row + column] = anti_diag[row - column + n - 1] = true;\n count += solve(col, diag, anti_diag, row + 1);\n col[column] = diag[row + column] = anti_diag[row - column + n - 1] = false;\n }\n return count;\n}\n};" }, { "title": "Intersection of Multiple Arrays", "algo_input": "Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.\n \nExample 1:\n\nInput: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\nOutput: [3,4]\nExplanation: \nThe only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].\n\nExample 2:\n\nInput: nums = [[1,2,3],[4,5,6]]\nOutput: []\nExplanation: \nThere does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= sum(nums[i].length) <= 1000\n\t1 <= nums[i][j] <= 1000\n\tAll the values of nums[i] are unique.\n\n", "solution_py": "class Solution:\n def intersection(self, A: List[List[int]]) -> List[int]:\n return sorted([k for k,v in Counter([x for l in A for x in l]).items() if v==len(A)])\n\t\t", "solution_js": "var intersection = function(nums) {\n let set = addToSet(nums[0]);\n for(let i=1; i a-b );\n};\n\nfunction addToSet(arr) {\n let set = new Set(arr);\n return set;\n}", "solution_java": "class Solution {\n public List intersection(int[][] nums) {\n\n List ans = new ArrayList<>();\n\n int[] count = new int[1001];\n\n for(int[] arr : nums){\n for(int i : arr){\n count[i]++;\n }\n }\n\n for(int i=0;i intersection(vector>& nums) {\n int n = nums.size(); // gives the no. of rows\n map mp; // we don't need unordered_map because we need the elements to be in sorted format.\n vector vec;\n \n // traverse through the 2D array and store the frequency of each element\n for(int row=0;row int:\n wstart = wsum = count = 0\n \n for wend in range(len(arr)):\n wsum += arr[wend]\n \n if wend >= k:\n wsum -= arr[wstart]\n wstart += 1\n if (wsum//k) >= threshold and (wend-wstart+1) == k: \n count += 1\n return count", "solution_js": "var numOfSubarrays = function(arr, k, threshold) {\n let total = 0;\n let left = 0;\n let right = k;\n // get initial sum of numbers in first sub array range, by summing left -> right\n let sum = arr.slice(left, right).reduce((a, b) => a + b, 0);\n while (right <= arr.length) {\n // move through the array as a sliding window\n if (left > 0) {\n // on each iteration of the loop, subtract the val that has fallen out of the window, \n // and add the new value that has entered the window\n sum -= arr[left - 1];\n sum += arr[right - 1];\n }\n if (sum / k >= threshold) {\n total++;\n }\n left++;\n right++;\n }\n return total;\n};", "solution_java": "class Solution {\n public int numOfSubarrays(int[] arr, int k, int threshold) {\n int average=0,count=0,start=0,sum=0; \n for(int i=0;i=k-1){\n average=sum/k;\n if(average>=threshold) count++;\n sum-=arr[start]; \n start++; \n } \n }\n return count; \n }\n}", "solution_c": "class Solution {\npublic:\n int numOfSubarrays(vector& arr, int k, int threshold) {\n int i=0;int j=0;int sum=0;int ans=0;\n while(j=threshold){\n ans++;\n } \n sum-=arr[i];\n j++;\n i++;\n } \n }\n return ans;\n }\n};" }, { "title": "Remove Palindromic Subsequences", "algo_input": "You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.\n\nReturn the minimum number of steps to make the given string empty.\n\nA string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.\n\nA string is called palindrome if is one that reads the same backward as well as forward.\n\n \nExample 1:\n\nInput: s = \"ababa\"\nOutput: 1\nExplanation: s is already a palindrome, so its entirety can be removed in a single step.\n\n\nExample 2:\n\nInput: s = \"abb\"\nOutput: 2\nExplanation: \"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".\n\n\nExample 3:\n\nInput: s = \"baabb\"\nOutput: 2\nExplanation: \"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts[i] is either 'a' or 'b'.\n\n", "solution_py": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n return 1 if s[::-1] == s else 2\n ", "solution_js": "var removePalindromeSub = function(s) {\n const isPalindrome = s == s.split('').reverse().join('');\n return isPalindrome ? 1 : 2;\n};", "solution_java": "class Solution\n{\n public int removePalindromeSub(String s)\n {\n int left = 0 , right = s.length() - 1 ;\n while( left < right )\n {\n if( s.charAt(left++) != s.charAt(right--) )\n {\n return 2 ;\n }\n }\n return 1 ;\n }\n}", "solution_c": " //the major obersavation or we can also verify by giving your own test it always returns 1 or 2 \n //if the whole string is palindrom then return 1 if not then return 2.\nclass Solution {\n static bool isPal(string s){\n string p = s;\n reverse(p.begin() , p.end());\n return s==p; \n }\npublic:\n int removePalindromeSub(string s) {\n \n if(isPal(s)){\n return 1;\n } \n \n return 2;\n }\n};" }, { "title": "Tallest Billboard", "algo_input": "You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\n\nYou are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.\n\nReturn the largest possible height of your billboard installation. If you cannot support the billboard, return 0.\n\n \nExample 1:\n\nInput: rods = [1,2,3,6]\nOutput: 6\nExplanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n\n\nExample 2:\n\nInput: rods = [1,2,3,4,5,6]\nOutput: 10\nExplanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n\n\nExample 3:\n\nInput: rods = [1,2]\nOutput: 0\nExplanation: The billboard cannot be supported, so we return 0.\n\n\n \nConstraints:\n\n\n\t1 <= rods.length <= 20\n\t1 <= rods[i] <= 1000\n\tsum(rods[i]) <= 5000\n\n", "solution_py": "class Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n dp = collections.defaultdict(int)\n dp[0] = 0\n for x in rods:\n nxt = dp.copy()\n for d, y in dp.items():\n # init state\n # ------|----- d -----| # tall side\n # - y --| # low side\n\n # put x to tall side\n # ------|----- d -----|---- x --|\n # - y --|\n nxt[d + x] = max(nxt.get(x + d, 0), y)\n\n nxt[abs(d - x)] = max(nxt.get(abs(d - x), 0), y + min(d, x))\n dp = nxt\n return dp[0]", "solution_js": "/**\n * @param {number[]} rods\n * @return {number}\n */\nvar tallestBillboard = function(rods) {\n let len = rods.length;\n if (len <= 1) return 0;\n let dp = [];\n for (let i = 0; i < len + 5; i++) {\n dp[i] = [];\n for (let j = 0; j < 5005 * 2; j++) {\n dp[i][j] = -1\n }\n }\n return solve(0, 0, rods, dp);\n}\n\nvar solve = function(i, sum, rods, dp) {\n if (i == rods.length) {\n if (sum == 0) {\n return 0\n }else{\n return -5000\n }\n }\n if (dp[i][sum + 5000] != -1) {\n return dp[i][sum + 5000];\n }\n let val = solve(i + 1, sum, rods, dp);\n val = Math.max(val, solve(i + 1, sum + rods[i], rods, dp) + rods[i]);\n val = Math.max(val, solve(i + 1, sum - rods[i], rods, dp));\n dp[i][sum + 5000] = val;\n return val;\n}", "solution_java": "class Solution {\n public int tallestBillboard(int[] rods) {\n int[] result = new int[1];\n dfs(rods, 0, 0, 0, rods.length, result);\n return result[0];\n }\n private void dfs(int[] rods, int left, int right, int level, int n, int[] result) {\n if (level == n) {\n if (left == right) {\n result[0] = Math.max(left, result[0]);\n }\n return;\n }\n \n dfs(rods, left, right, level + 1, n, result);\n dfs(rods, left + rods[level], right, level + 1, n, result);\n dfs(rods, left, right + rods[level], level + 1, n, result);\n }\n}", "solution_c": "class Solution {\npublic:\n\tint f(int i,vector& v, int a, int b){\n\t\tif(i==v.size()){\n\t\t\tif(a==b){\n\t\t\t\treturn a;\n\t\t\t}\n\t\t return 0;\n\t\t}\n\n\t\tint x = f(i+1,v,a,b);\n\t\tint y = f(i+1,v,a+v[i],b);\n\t\tint z = f(i+1,v,a,b+v[i]);\n\n\t\treturn max({x,y,z});\n\t}\n\tint tallestBillboard(vector& rods) {\n\t\treturn f(0,rods,0,0);\n\n\t}\n};" }, { "title": "Swap Adjacent in LR String", "algo_input": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.\n\n \nExample 1:\n\nInput: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput: true\nExplanation: We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\n\n\nExample 2:\n\nInput: start = \"X\", end = \"L\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= start.length <= 104\n\tstart.length == end.length\n\tBoth start and end will only consist of characters in 'L', 'R', and 'X'.\n\n", "solution_py": "class Solution:\n def canTransform(self, start: str, end: str) -> bool:\n def chars(s):\n for i, c in enumerate(s):\n if c != 'X':\n yield i, c\n \n yield -1, ' '\n \n for (startI, startC), (endI, endC) in zip(chars(start), chars(end)):\n if (startC != endC or\n (startC == 'L' and startI < endI) or\n (startC == 'R' and startI > endI)):\n return False\n \n return True", "solution_js": "/**\n * @param {string} start\n * @param {string} end\n * @return {boolean}\n */\nvar canTransform = function(start, end) {\n let i = 0;\n let j = 0;\n\n while (i < start.length || j < end.length) {\n if (start[i] === 'X') {\n i++;\n continue;\n }\n\n if (end[j] === 'X') {\n j++;\n continue;\n }\n\n // Breaking (1)\n if (start[i] !== end[j]) return false;\n\n // Breaking (2)\n if (start[i] === 'R' && i > j) return false;\n\n // Breaking (3)\n if (start[i] === 'L' && j > i) return false;\n\n i++;\n j++;\n }\n\n return true;\n};", "solution_java": "class Solution {\n public boolean canTransform(String start, String end) {\n int startL = 0, startR = 0;\n int endL = 0, endR = 0;\n String stLR = \"\", edLR = \"\";\n for(int i = 0; i < start.length(); i++) {\n if(start.charAt(i) != 'X') {\n if(start.charAt(i) == 'L') {\n startL++;\n } else{\n startR++;\n }\n stLR+= start.charAt(i);\n }\n if(end.charAt(i) != 'X') {\n if(end.charAt(i) == 'L') {\n endL++;\n } else{\n endR++;\n }\n edLR += end.charAt(i);\n }\n\n if(startL > endL || startR < endR) //Check conditions at each instant\n return false;\n }\n\n if(startL != endL || startR != endR || !stLR.equals(edLR)) //check their final count and positions\n return false;\n\n return true;\n }\n\n}", "solution_c": "class Solution {\npublic:\n bool canTransform(string start, string end) {\n int s=0,e=0;\n while(s<=start.size() and e<=end.size()){\n while(ss){\n return false;\n }\n s++;\n e++;\n }\n return true;\n }\n};" }, { "title": "Max Points on a Line", "algo_input": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.\n\n \nExample 1:\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 3\n\n\nExample 2:\n\nInput: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= points.length <= 300\n\tpoints[i].length == 2\n\t-104 <= xi, yi <= 104\n\tAll the points are unique.\n\n", "solution_py": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n ans = 0\n n = len(points)\n \n for i in range(n):\n d = collections.defaultdict(int)\n for j in range(n):\n if i != j:\n slope = float(\"inf\")\n if (points[j][1] - points[i][1] != 0):\n slope = (points[j][0] - points[i][0]) / (points[j][1] - points[i][1])\n d[slope] += 1\n if d:\n ans = max(ans, max(d.values())+1)\n else:\n ans = max(ans, 1)\n \n return ans", "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\n\nvar maxPoints = function(points) {\n if (points.length === 1) {\n return 1;\n }\n \n const slopes = {};\n let dx, dy;\n let xbase, ybase;\n let xref, yref, key;\n const INFINITE_SLOPE = 'infinite';\n \n for(let i = 0; i < points.length; i++) {\n [xbase, ybase] = points[i];\n \n for(let j = i + 1; j < points.length; j++) { \n \n [xref, yref] = points[j];\n \n if (xref === xbase) {\n key = `x = ${xref}`;\n \n } else {\n dx = xref - xbase;\n dy = yref - ybase;\n \n let m = dy / dx;\n let c = yref - m * xref;\n \n m = m.toFixed(4);\n c = c.toFixed(4);\n \n key = `y = ${m}x + ${c}`; \n }\n \n slopes[key] || (slopes[key] = 0);\n slopes[key]++;\n }\n }\n \n const maxPairs = Math.max(...Object.values(slopes));\n \n if (maxPairs === 2) {\n return 2;\n }\n \n for(let i = 1; i <= 300; i++) {\n if (i * (i - 1) / 2 === maxPairs) {\n return i;\n }\n }\n \n return 0;\n};", "solution_java": "class Solution {\n public int maxPoints(int[][] points) {\n int n = points.length;\n if(n == 1) return n;\n int result = 0;\n for(int i = 0; i< n; i++){\n for(int j = i+1; j< n; j++){\n result = Math.max(result, getPoints(i, j, points));\n }\n }\n return result;\n }\n private int getPoints(int pt1, int pt2, int[][] points){\n int[] point1 = points[pt1], point2 = points[pt2];\n double slope = (point1[1] - point2[1])/(double)(point1[0] - point2[0]);\n int result = 0;\n for(int i = 0; i p1,vector p2){\n if(p1[0]==p2[0])\n return p1[1]>& points) {\n if(points.size()==2 || points.size()==1)\n return points.size();\n\n sort(points.begin(),points.end(),cmp);\n int ans=1;\n //How much points having same slope at current index\n vector> dp(points.size()+1);\n for(int i=1;i= 0; i--) {\n post[i] = lastOcc;\n if(nums[i] & 1) lastOcc = i;\n }\n\n let l = 0, r = 0, oddCount = 0;\n\n let ans = 0;\n\n for(; r < len; r++) {\n while(l < len && !(nums[l] & 1)) l++;\n if(nums[r] & 1) oddCount++;\n\n if(oddCount == k) {\n let leftCount = l - pre[l];\n let rightCount = post[r] - r;\n ans += leftCount * rightCount;\n\n oddCount--;\n l++;\n }\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int i = 0;\n int j = 0;\n int odd = 0;\n int result = 0;\n int temp = 0;\n\n /*\n Approach : two pointer + sliding window technique\n\n step 1 : we have fix i and moving j until our count of odd numbers == k\n step 2 : when(odd == count) we are counting every possible subarray by reducing the size of subarray from i\n\n why temp?\n from reducing the size of subarray we will count all the possible subarray from between i and j\n but when i encounter a odd element the odd count will reduce and that while will stop executing\n\n now there are two possible cases\n 1.The leftover elements have a odd number\n 2.The leftover elements do not have any odd number\n\n 1. if our leftover elements have a odd number\n then we cannot include our old possible subarrays into new possible subarrays because now new window for having odd == k is formed\n that's why temp = 0;\n\n 2. if out leftover elements do not have any odd element left\n then our leftover elements must also take in consideration becuase they will also contribute in forming subarrays\n */\n while(j< nums.length){\n if(nums[j]%2 != 0)\n {\n odd++;\n //if leftover elements have odd element then new window is formed so we set temp = 0;\n temp = 0;\n }\n while(odd ==k){\n temp++;\n if(nums[i] %2 != 0)\n odd--;\n i++;\n }\n //if no leftover elements is odd, each element will part in forming subarray\n //so include them\n result += temp;\n j++;\n\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector nums;\n int solve(int k){\n int low = 0, high = 0, cnt = 0, res = 0;\n\n while(high < nums.size()){\n if(nums[high] & 1){\n cnt++;\n\n while(cnt > k){\n if(nums[low] & 1) cnt--;\n low++;\n }\n }\n high++;\n res += high - low;\n }\n\n return res;\n }\n int numberOfSubarrays(vector& nums, int k) {\n this -> nums = nums;\n return solve(k) - solve(k - 1);\n }\n};" }, { "title": "Number of Ways to Arrive at Destination", "algo_input": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.\n\nYou are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.\n\nReturn the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 ➝ 6\n- 0 ➝ 4 ➝ 6\n- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6\n- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6\n\n\nExample 2:\n\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 200\n\tn - 1 <= roads.length <= n * (n - 1) / 2\n\troads[i].length == 3\n\t0 <= ui, vi <= n - 1\n\t1 <= timei <= 109\n\tui != vi\n\tThere is at most one road connecting any two intersections.\n\tYou can reach any intersection from any other intersection.\n\n", "solution_py": "class Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(dict)\n for u, v, w in roads:\n graph[u][v] = graph[v][u] = w\n dist = {i:float(inf) for i in range(n)}\n ways = {i:0 for i in range(n)}\n dist[0], ways[0] = 0, 1\n heap = [(0, 0)]\n while heap:\n d, u = heapq.heappop(heap)\n if dist[u] < d: \n continue\n for v in graph[u]:\n if dist[v] == dist[u] + graph[u][v]:\n ways[v] += ways[u]\n elif dist[v] > dist[u] + graph[u][v]:\n dist[v] = dist[u] + graph[u][v]\n ways[v] = ways[u]\n heapq.heappush(heap, (dist[v], v))\n return ways[n-1] % ((10 ** 9) + 7)", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} roads\n * @return {number}\n */\nvar countPaths = function(n, roads) {\n let adj = {}, dist = Array(n).fill(Infinity), minHeap = new MinHeap(), count = Array(n).fill(1);\n\n //CREATE ADJ MATRIX\n for(let [from, to , weight] of roads){\n adj[from] = adj[from] || []\n adj[from].push([to, weight]);\n adj[to] = adj[to] || []\n adj[to].push([from, weight]);\n }\n\n //PUT START IN QUEUE\n dist[n-1] = 0;\n minHeap.enqueue(n-1, 0);\n\n while(minHeap.getSize()){\n let [node, curDist] = minHeap.dequeue();\n let children = adj[node] || [];\n for(let [childNode, childWeight] of children){\n\n //IF PATH ALREADY FOUND WITH THIS VALUE THEN ADD COUNT REACHED UNTIL NOW\n if(curDist + childWeight === dist[childNode]){\n count[childNode] = (count[childNode] +count[node]) % 1000000007;\n } //IF NOT PATH FOUND YET THEN ADD COUNT OF WAYS TO THE NODE WE CAME FROM\n else if(curDist + childWeight < dist[childNode]){\n count[childNode] = count[node];\n dist[childNode] = curDist + childWeight;\n minHeap.enqueue(childNode, dist[childNode]);\n }\n }\n }\n return count[0];\n};\n\nclass MinHeap{\n constructor(list = []){\n this.tree = [null];\n this.list = list;\n this.build();\n }\n\n build(){\n for(let [val,priority] of this.list)\n this.enqueue(val,priority);\n }\n\n swap(pos1, pos2){\n [this.tree[pos1], this.tree[pos2]] = [this.tree[pos2],this.tree[pos1]]\n }\n\n enqueue(val, priority){\n this.tree[this.tree.length] = [val, priority];\n let i = this.tree.length - 1, parent = ~~(i/2);\n while(i > 1){\n if(this.tree[parent][1] > this.tree[i][1])\n this.swap(parent,i);\n i = parent;\n parent = ~~(i/2);\n }\n }\n\n dequeue(){\n let size = this.tree.length - 1, pos = 1;\n if(!size) return;\n let last = this.tree.pop(), deleted = this.tree[pos];\n if(!deleted && last) return last;\n this.tree[pos] = last;\n this.heapify(pos);\n return deleted;\n }\n\n heapify(pos){\n\n if(pos > this.tree.length) return;\n let leftPos = 2*pos, rightPos = 2*pos +1;\n let left = this.tree[leftPos] ? this.tree[leftPos][1] : Infinity;\n let right = this.tree[rightPos] ? this.tree[rightPos][1] : Infinity, minVal = null, minIndex = null;\n if(left < right){\n minVal = left;\n minIndex = leftPos;\n }else{\n minVal = right;\n minIndex = rightPos\n }\n if(this.tree[pos][1] > minVal){\n this.swap(pos,minIndex);\n this.heapify(minIndex);\n }\n }\n\n getTree(){\n console.log(this.tree.slice(1));\n }\n\n getSize(){\n return this.tree.length - 1;\n }\n}", "solution_java": "class Solution {\n class Pair{\n int node;\n int dist;\n Pair(int node , int dist){\n this.node = node;\n this.dist = dist;\n }\n }\n public int countPaths(int n, int[][] roads) {\n int mod = (int)Math.pow(10 , 9) + 7;\n ArrayList> adj = new ArrayList<>();\n int rows = roads.length;\n for(int i = 0 ; i < n ; i++)\n adj.add(new ArrayList());\n for(int i = 0 ; i < rows ; i++){\n int from = roads[i][0];\n int to = roads[i][1];\n int dis = roads[i][2];\n adj.get(from).add(new Pair(to , dis));\n adj.get(to).add(new Pair(from , dis));\n }\n PriorityQueue pq = new PriorityQueue<>((aa , bb) -> aa.dist - bb.dist);\n pq.add(new Pair(0 , 0));\n long[] ways = new long[n];\n ways[0] = 1;\n int[] dist = new int[n];\n Arrays.fill(dist , Integer.MAX_VALUE);\n dist[0] = 0;\n while(!pq.isEmpty()){\n Pair p = pq.remove();\n int node = p.node;\n int dis = p.dist;\n for(Pair pa : adj.get(node)){\n if((dis + pa.dist) < dist[pa.node]){\n ways[pa.node] = ways[node];\n dist[pa.node] = dis + pa.dist;\n pq.add(new Pair(pa.node , dist[pa.node]));\n }\n else if((dis + pa.dist) == dist[pa.node]){\n ways[pa.node] += ways[node];\n ways[pa.node] = ways[pa.node] % mod;\n }\n }\n }\n return (int)ways[n - 1];\n }\n}", "solution_c": "class Solution {\npublic:\n int countPaths(int n, vector>& roads) {\n int mod = 1e9+7;\n vector>> graph(n);\n for(auto &road: roads) {\n graph[road[0]].push_back({road[1], road[2]});\n graph[road[1]].push_back({road[0], road[2]});\n }\n \n vector distance(n, LONG_MAX);\n vector path(n, 0);\n \n priority_queue, vector>, greater>> pq;\n pq.push({0, 0});\n distance[0] = 0;\n path[0] = 1;\n \n while(!pq.empty()) {\n pair t = pq.top();\n pq.pop();\n \n for(auto &nbr: graph[t.second]) {\n long long vert = nbr.first;\n long long edge = nbr.second;\n \n if(distance[vert] > distance[t.second] + edge) {\n distance[vert] = distance[t.second] + edge;\n pq.push({distance[vert], vert});\n path[vert] = path[t.second] %mod;\n }\n else if(distance[vert] == t.first + edge) {\n path[vert] += path[t.second];\n path[vert] %= mod;\n }\n }\n }\n \n return path[n-1];\n }\n};" }, { "title": "Create Binary Tree From Descriptions", "algo_input": "You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,\n\n\n\tIf isLefti == 1, then childi is the left child of parenti.\n\tIf isLefti == 0, then childi is the right child of parenti.\n\n\nConstruct the binary tree described by descriptions and return its root.\n\nThe test cases will be generated such that the binary tree is valid.\n\n \nExample 1:\n\nInput: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput: [50,20,80,15,17,19]\nExplanation: The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\nExample 2:\n\nInput: descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput: [1,2,null,null,3,4]\nExplanation: The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\n \nConstraints:\n\n\n\t1 <= descriptions.length <= 104\n\tdescriptions[i].length == 3\n\t1 <= parenti, childi <= 105\n\t0 <= isLefti <= 1\n\tThe binary tree described by descriptions is valid.\n\n", "solution_py": "class Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n hashmap = {}\n nodes = set()\n children = set()\n for parent,child,isLeft in descriptions:\n nodes.add(parent)\n nodes.add(child)\n children.add(child)\n if parent not in hashmap:\n hashmap[parent] = TreeNode(parent)\n if child not in hashmap:\n hashmap[child] = TreeNode(child)\n if isLeft:\n hashmap[parent].left = hashmap[child]\n if not isLeft:\n hashmap[parent].right = hashmap[child]\n \n for node in nodes:\n if node not in children:\n return hashmap[node]", "solution_js": "var createBinaryTree = function(descriptions) {\n let nodes = new Map(), children = new Set();\n for (let [parent, child, isLeft] of descriptions) {\n let parentNode = nodes.get(parent) || new TreeNode(parent);\n if (!nodes.has(parent)) nodes.set(parent, parentNode);\n\n let childNode = nodes.get(child) || new TreeNode(child);\n if (!nodes.has(child)) nodes.set(child, childNode);\n\n if (isLeft) parentNode.left = childNode;\n else parentNode.right = childNode;\n\n children.add(child);\n }\n\n for (let [parent, child, isLeft] of descriptions) {\n // a node with no parent is the root\n if (!children.has(parent)) return nodes.get(parent);\n }\n};", "solution_java": "class Solution {\n public TreeNode createBinaryTree(int[][] descriptions) {\n HashMap map=new HashMap<>();\n HashSet children=new HashSet<>();\n for(int[] info:descriptions)\n {\n int parent=info[0],child=info[1];\n boolean isLeft=info[2]==1?true:false;\n TreeNode parentNode=null;\n TreeNode childNode=null;\n if(map.containsKey(parent))\n parentNode=map.get(parent);\n else\n parentNode=new TreeNode(parent);\n if(map.containsKey(child))\n childNode=map.get(child);\n else\n childNode=new TreeNode(child);\n if(isLeft)\n parentNode.left=childNode;\n else\n parentNode.right=childNode;\n map.put(parent,parentNode);\n map.put(child,childNode);\n children.add(child);\n \n }\n TreeNode root=null;\n for(int info[]:descriptions)\n {\n if(!children.contains(info[0]))\n {\n root=map.get(info[0]);\n break;\n }\n }\n return root;\n }\n \n \n}", "solution_c": "class Solution {\npublic:\n TreeNode* createBinaryTree(vector>& descriptions){\n unordered_map getNode; //to check if node alredy exist\n unordered_map isChild; //to check if node has parent or not\n for(auto &v: descriptions){\n if(getNode.count(v[0])==0){\n TreeNode* par = new TreeNode(v[0]);\n getNode[v[0]] = par;\n }\n if(getNode.count(v[1])==0){\n TreeNode* child = new TreeNode(v[1]);\n getNode[v[1]] = child;\n }\n if(v[2]==1) getNode[v[0]]->left = getNode[v[1]]; //left-child\n else getNode[v[0]]->right = getNode[v[1]]; //right-child\n isChild[v[1]] = true;\n }\n TreeNode* ans = NULL;\n for(auto &v: descriptions){\n if(isChild[v[0]] != true){ //if node has no parent then this is root node\n ans = getNode[v[0]];\n break;\n }\n }\n return ans;\n }\n};" }, { "title": "People Whose List of Favorite Companies Is Not a Subset of Another List", "algo_input": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).\n\nReturn the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.\n\n \nExample 1:\n\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput: [0,1,4] \nExplanation: \nPerson with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\n\n\nExample 2:\n\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput: [0,1] \nExplanation: In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].\n\n\nExample 3:\n\nInput: favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput: [0,1,2,3]\n\n\n \nConstraints:\n\n\n\t1 <= favoriteCompanies.length <= 100\n\t1 <= favoriteCompanies[i].length <= 500\n\t1 <= favoriteCompanies[i][j].length <= 20\n\tAll strings in favoriteCompanies[i] are distinct.\n\tAll lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].\n\tAll strings consist of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n \n F = favoriteCompanies\n ans = [] \n \n seen = set() \n \n for i in range(len(F)):\n for j in range(i+1,len(F)):\n st1 = set(F[i])\n st2 = set(F[j])\n if st1.intersection(st2) == st1: seen.add(i)\n if st2.intersection(st1) == st2: seen.add(j) \n\n ans = []\n for i in range(len(F)):\n if i in seen: continue \n ans.append(i) \n \n return ans", "solution_js": "var peopleIndexes = function(favoriteCompanies) {\n let arr = favoriteCompanies\n let len = arr.length\n let ret = []\n for(let i = 0; i < len; i++) {\n let item1 = arr[i]\n let isSubset = false\n for(let j = 0; j < len; j++) {\n if(i === j) continue\n let item2 = arr[j]\n let s = new Set(item2)\n if(item1.every(a => s.has(a))) {\n isSubset = true\n break\n }\n }\n if(!isSubset) ret.push(i)\n }\n return ret\n};", "solution_java": "class Solution {\n public List peopleIndexes(List> favoriteCompanies) {\n Set[] fav = new Set[favoriteCompanies.size()];\n Set set = new HashSet<>();\n for (int i = 0; i < favoriteCompanies.size(); i++) {\n set.add(i);\n fav[i] = new HashSet<>(favoriteCompanies.get(i));\n }\n for (int i = 1; i < favoriteCompanies.size(); i++) {\n if (!set.contains(i)) continue;\n for (int j = 0; j < i; j++) {\n if (!set.contains(j)) continue;\n if (isSubSet(fav[j], fav[i])) set.remove(j);\n if (isSubSet(fav[i], fav[j])) set.remove(i);\n }\n }\n List ans = new ArrayList<>(set);\n Collections.sort(ans);\n return ans;\n }\n\n private boolean isSubSet(Set child, Set parent) {\n if (child.size() > parent.size()) return false;\n return parent.containsAll(child);\n }\n}", "solution_c": "/*\n * author: deytulsi18\n * problem: https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/\n * time complexity: O(n*n*m)\n * auxiliary space: O(1)\n * language: cpp\n */\nclass Solution {\npublic:\n bool isSubset(vector &b, vector &a)\n {\n return (includes(a.begin(), a.end(),\n b.begin(), b.end()));\n }\n vector peopleIndexes(vector>& favoriteCompanies) {\n\n int n = favoriteCompanies.size();\n vector res;\n\n for (auto &i : favoriteCompanies)\n sort(begin(i), end(i));\n\n for (int i = 0; i < n; i++)\n {\n bool isValid = true;\n\n for (int j = 0; j < n; j++)\n if (i != j)\n if (isSubset(favoriteCompanies[i], favoriteCompanies[j]))\n {\n isValid = false;\n break;\n }\n\n if (isValid)\n res.emplace_back(i);\n }\n\n return res;\n }\n};;" }, { "title": "Maximum Number of Balloons", "algo_input": "Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible.\n\nYou can use each character in text at most once. Return the maximum number of instances that can be formed.\n\n \nExample 1:\n\n\n\nInput: text = \"nlaebolko\"\nOutput: 1\n\n\nExample 2:\n\n\n\nInput: text = \"loonbalxballpoon\"\nOutput: 2\n\n\nExample 3:\n\nInput: text = \"leetcode\"\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 104\n\ttext consists of lower case English letters only.\n\n", "solution_py": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n freq = {'b': 0, 'a': 0, 'l': 0, 'o': 0, 'n': 0}\n \n for char in text:\n if not char in freq:\n continue\n \n step = 0.5 if char == 'l' or char == 'o' else 1\n \n freq[char] += step\n \n result = min(freq.values())\n \n return floor(result)", "solution_js": "/**\n * @param {string} text\n * @return {number}\n */\nvar maxNumberOfBalloons = function(text) {\n// 1. create hashmap with \"balloon\" letters\n// 2. keep track of how many letters in text belong to \"balloon\"\n// 3. account for fact that we need two \"l\" and \"o\" per \"balloon\" instance\n// 4. then select all map values and get the minimum - this will be the max value\n \n const balloonMap = {\n \"b\": 0,\n \"a\": 0,\n \"l\": 0,\n \"o\": 0,\n \"n\": 0\n }\n \n for (const char of text) {\n if (balloonMap[char] !== undefined) {\n balloonMap[char] += 1\n }\n }\n \n const letterFreq = []\n for (const key in balloonMap) {\n if ([\"l\", \"o\"].includes(key)) {\n letterFreq.push(Math.floor(balloonMap[key]/2))\n } else {\n letterFreq.push(balloonMap[key])\n }\n }\n return Math.min(...letterFreq)\n};", "solution_java": "class Solution {\n\n public int maxNumberOfBalloons(String text) {\n return maxNumberOfWords(text, \"balloon\");\n }\n\n private int maxNumberOfWords(String text, String word) {\n final int[] tFrequencies = new int[26];\n for (int i = 0; i < text.length(); ++i) {\n tFrequencies[text.charAt(i) - 'a']++;\n }\n final int[] wFrequencies = new int[26];\n for (int i = 0; i < word.length(); ++i) {\n wFrequencies[word.charAt(i) - 'a']++;\n }\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < 26; ++i) {\n if (wFrequencies[i] > 0) {\n final int count = (tFrequencies[i] / wFrequencies[i]);\n if (count < min) {\n min = count;\n }\n }\n }\n return min;\n }\n\n}", "solution_c": "class Solution {\npublic:\n int maxNumberOfBalloons(string text) {\n mapm;\n for(int i=0;i int:\n \n m = len(board)\n n = len(board[0])\n res = 0\n \n pole = [ [True for i in range(n)] for j in range(m) ]\n \n for i in range(m):\n for j in range(n):\n if board[i][j] == 'X' and pole[i][j]:\n for z in range(i+1, m):\n if board[z][j] == 'X':\n pole[z][j] = False\n else:\n break\n \n for z in range(j+1, n):\n if board[i][z] == 'X':\n pole[i][z] = False\n else:\n break\n \n \n res += 1\n \n\n \n return res", "solution_js": "var countBattleships = function(board) {\n \n let count = 0;\n \n for(let rowIndex = 0; rowIndex < board.length; rowIndex++){\n for(let columnIndex = 0; columnIndex < board[rowIndex].length; columnIndex++){\n const isTopEmpty = rowIndex === 0 || board[rowIndex - 1][columnIndex] !== \"X\";\n const isLeftEmpty = columnIndex === 0 || board[rowIndex][columnIndex - 1] !== \"X\";\n const isBattleShip = board[rowIndex][columnIndex] === \"X\" && isTopEmpty && isLeftEmpty;\n if(isBattleShip){\n count++;\n }\n }\n }\n \n return count;\n \n};", "solution_java": "class Solution {\n public int countBattleships(char[][] board) {\n int result = 0;\n for(int i = 0;i= board.length || j<0 || j>=board[0].length || board[i][j] == '.')\n {\n return;\n }\n board[i][j] = '.';\n remover(i+1, j, board);\n remover(i, j+1, board);\n }\n}", "solution_c": "class Solution {\npublic:\n\n bool isSafe(int i,int j,int r,int c,vector> &arr,vector> &visited){\n if(i<0 || i>r || j<0 || j>c){\n return false;\n }\n // cout<> &arr,vector> &visited,int &r,int &c,int i,int j){\n\n if((i>r && j>c) && (i<0 && j<0)){\n return;\n }\n\n // down (i+1,j)\n if(isSafe(i+1,j,r,c,arr,visited)){\n visited[i+1][j] = true;\n solve(arr,visited,r,c,i+1,j);\n }else{\n // if(arr[i][j] == 'X'){\n // visited[i][j] = true;\n // }\n }\n // // right (i,j+1)\n\n if(isSafe(i,j+1,r,c,arr,visited)){\n visited[i][j+1] = true;\n solve(arr,visited,r,c,i,j+1);\n }else{\n // if(arr[i][j] == 'X'){\n // visited[i][j] = true;\n // }\n }\n // left (i,j-1);\n if(isSafe(i,j-1,r,c,arr,visited)){\n visited[i][j-1] = true;\n solve(arr,visited,r,c,i,j-1);\n }else{\n // if(arr[i][j] == 'X'){\n // visited[i][j] = true;\n // }\n }\n // up (i-1,j)\n if(isSafe(i-1,j,r,c,arr,visited)){\n visited[i-1][j] = true;\n solve(arr,visited,r,c,i-1,j);\n }else{\n // if(arr[i][j] == 'X'){\n // visited[i][j] = true;\n // }\n }\n\n }\n int countBattleships(vector>& board) {\n int row = board.size()-1;\n int col = board[0].size()-1;\n vector> isVisited(row+1,vector(col+1,false));\n vector> toStart;\n for(int i=0;i temp(2);\n temp[0] = i;\n temp[1] = j;\n // cout< int:\n n = len(arr)\n ans = -1\n if n == m: return m #just in case\n \n# make in \"inverted\" array with artificial ends higher then everything between\n\n sor= [0 for _ in range(n+2)]\n for i in range(n):\n sor[(arr[i])] = i+1 \n sor[0] = sor[n+1] = n+1\n \n# scan and see, if ones in the middle of space of length m appear \n# before ones on its ends,\n# and find the latest of such spaces to disappear, if exists\n\n for i in range(1, n-m+2): \n if all(sor[i-1]>sor[j] and sor[i+m]>sor[j] for j in range(i,i+m)):\n if min(sor[i-1]-1,sor[i+m]-1)>ans: ans = min(sor[i-1]-1,sor[i+m]-1) \n return ans", "solution_js": "var findLatestStep = function(arr, m) {\n if (m === arr.length) return arr.length\n let bits = new Array(arr.length+1).fill(true), pos, flag, i, j\n for (i = arr.length - 1, bits[0] = false; i >= 0; i--) {\n pos = arr[i], bits[pos] = false\n for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos-j]\n if (flag && !bits[pos-m-1]) return i\n for (j = 1, flag = true; flag && j <= m; j++) flag = bits[pos+j]\n if (flag && !bits[pos+m+1]) return i\n }\n return -1\n};", "solution_java": "class Solution {\n int[] par, size, count, bits; \n // par: parent array, tells about whose it the parent of ith element\n // size: it tells the size of component\n // count: it tells the count of islands (1111 etc) of size i;\n // count[3] = 4: ie -> there are 4 islands of size 3\n \n public int find(int u) {\n if (u == par[u]) return u;\n par[u] = find(par[u]);\n return par[u];\n }\n \n public void union(int u, int v) {\n // union is performed over parents of elements not nodes itself\n int p1 = find(u), p2 = find(v);\n if (p1 == p2) return;\n \n // decrease the count of islands of size p1, p2\n count[size[p1]]--;\n count[size[p2]]--;\n \n // now merge\n par[p2] = p1;\n \n // adjust sizes\n size[p1] += size[p2];\n \n // adjust the count of islands of new size ie: size of p1\n count[size[p1]]++;\n }\n \n public int findLatestStep(int[] arr, int m) {\n int n = arr.length;\n par = new int[n + 1];\n size = new int[n + 1];\n count = new int[n + 1];\n bits = new int[n + 2];\n \n for (int i = 0; i < n; i++) {\n par[i] = i;\n size[i] = 1;\n }\n \n int ans = -1;\n for (int i = 0; i < n; i++) {\n int idx = arr[i];\n // set the bit\n bits[idx] = 1;\n // increase the count of islands of size 1\n count[1]++;\n \n if (bits[idx - 1] > 0) {\n union(idx, idx - 1);\n } \n if (bits[idx + 1] > 0) {\n union(idx, idx + 1);\n }\n \n // check if island of size m exists\n if (count[m] > 0) {\n ans = i + 1;\n // as it is 1 based indexing\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int findLatestStep(vector& arr, int m) {\n int n=size(arr),ans=-1;\n vectorcntL(n+2),indL(n+2);\n for(int i=0;i0)ans=i+1;\n }\n return ans;\n }\n};" }, { "title": "Convert BST to Greater Tree", "algo_input": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\n\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than 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 = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\nExample 2:\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-104 <= Node.val <= 104\n\tAll the values in the tree are unique.\n\troot is guaranteed to be a valid binary search tree.\n\n\n \nNote: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\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 convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n ans = []\n def inorder(node):\n if not node:\n return node\n inorder(node.left)\n ans.append(node.val)\n inorder(node.right)\n def dfs(node):\n if not node:\n return None\n idx = ans.index(node.val)\n node.val = node.val + sum(ans[idx+1:])\n dfs(node.left)\n dfs(node.right)\n\n inorder(root)\n dfs(root)\n return root\n ", "solution_js": "var convertBST = function(root) {\n let sum = 0;\n const go = (node) => {\n if (!node) return;\n go(node.right);\n sum += node.val;\n node.val = sum;\n go(node.left);\n }\n go(root);\n return root;\n};", "solution_java": "class Solution {\n public TreeNode convertBST(TreeNode root) {\n if(root!=null) {\n\n\n List nodesValues = new ArrayList<>();\n helperNodesVales(root, nodesValues);\n traverseAndAdd(root, nodesValues);\n\n return root;\n }\n return null;\n }\n\n private void helperNodesVales(TreeNode root, List nodesValues) {\n if (root != null) {\n nodesValues.add(root.val);\n }\n if (root.right != null) {\n helperNodesVales(root.right, nodesValues);\n }\n if (root.left != null) {\n helperNodesVales(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n\n private void traverseAndAdd(TreeNode root, List nodesValues) {\n if (root != null) {\n int rootVal = root.val;\n for (int i = 0; i < nodesValues.size(); i++) {\n if (nodesValues.get(i) > rootVal)\n root.val += nodesValues.get(i);\n }\n }\n if (root.right != null) {\n traverseAndAdd(root.right, nodesValues);\n }\n if (root.left != null) {\n traverseAndAdd(root.left, nodesValues);\n }\n if (root == null) {\n return;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int val = 0;\n TreeNode* convertBST(TreeNode* root) {\n\n if(root)\n {\n convertBST(root->right); // traverse right sub-tree\n val += root->val; // add val\n root->val = val; // update val\n convertBST(root->left); // traverse left sub-tree\n }\n \n return root;\n }\n};" }, { "title": "Maximum Score From Removing Stones", "algo_input": "You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).\n\nGiven three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.\n\n \nExample 1:\n\nInput: a = 2, b = 4, c = 6\nOutput: 6\nExplanation: The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.\n\n\nExample 2:\n\nInput: a = 4, b = 4, c = 6\nOutput: 7\nExplanation: The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.\n\n\nExample 3:\n\nInput: a = 1, b = 8, c = 8\nOutput: 8\nExplanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.\n\n\n \nConstraints:\n\n\n\t1 <= a, b, c <= 105\n\n", "solution_py": "class Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted([a, b, c], reverse=True)\n ans = 0\n while a > 0 and b > 0:\n a -= 1\n b -= 1\n ans += 1\n a, b, c = sorted([a, b, c], reverse=True)\n return ans", "solution_js": "/**\n * @param {number} a\n * @param {number} b\n * @param {number} c\n * @return {number}\n */\nvar maximumScore = function(a, b, c) {\n let resultArray = [];\n resultArray.push(a);\n resultArray.push(b);\n resultArray.push(c);\n resultArray.sort((a,b)=>a-b);\n let counter=0;\n while(resultArray[0]>0||resultArray[1]>0||resultArray[2]>0){\n if(resultArray[0]===0&&resultArray[1]===0){\n break;\n }\n resultArray[1]--;\n resultArray[2]--;\n counter++\n if(resultArray[1]b) return maximumScore(b,a,c);\n if (b>c) return maximumScore(a,c,b);\n \n // if sum of smallest numbers [a+b] is less than c, then we can a + b pairs with the c\n if (a+b<=c) return a+b;\n \n // if sum of smallest numbers is greater than c, then we can (a+b)/2 pairs after making c empty\n return c+(a+b-c)/2;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumScore(int a, int b, int c) {\n return min((a + b + c) / 2, a + b + c - max({a, b, c}));\n }\n};" }, { "title": "Process Tasks Using Servers", "algo_input": "You are given two 0-indexed integer arrays servers and tasks of lengths n​​​​​​ and m​​​​​​ respectively. servers[i] is the weight of the i​​​​​​th​​​​ server, and tasks[j] is the time needed to process the j​​​​​​th​​​​ task in seconds.\n\nTasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.\n\nAt second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.\n\nIf there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.\n\nA server that is assigned task j at second t will be free again at second t + tasks[j].\n\nBuild an array ans​​​​ of length m, where ans[j] is the index of the server the j​​​​​​th task will be assigned to.\n\nReturn the array ans​​​​.\n\n \nExample 1:\n\nInput: servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput: [2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n\nExample 2:\n\nInput: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput: [1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.\n\n\n \nConstraints:\n\n\n\tservers.length == n\n\ttasks.length == m\n\t1 <= n, m <= 2 * 105\n\t1 <= servers[i], tasks[j] <= 2 * 105\n\n", "solution_py": "class Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n servers_available = [(w, i) for i,w in enumerate(servers)]\n heapify(servers_available)\n tasks_in_progress = []\n res = []\n time = 0\n for j,task in enumerate(tasks):\n time = max(time, j)\n if not servers_available:\n time = tasks_in_progress[0][0]\n while tasks_in_progress and tasks_in_progress[0][0] <= time:\n heappush(servers_available, heappop(tasks_in_progress)[1])\n res.append(servers_available[0][1])\n heappush(tasks_in_progress, (time + task, heappop(servers_available)))\n return res", "solution_js": " var assignTasks = function(servers, tasks) {\n // create a heap to manage free servers.\n // free servers will need to be prioritized by weight and index\n const freeServers = new Heap((serverA, serverB) => (\n serverA.weight - serverB.weight || serverA.index - serverB.index\n ));\n\n // create a heap to manage used servers.\n // used servers will need to be prioritized by availableTime, weight and index\n const usedServers = new Heap((serverA, serverB) => (\n serverA.availableTime - serverB.availableTime || \n serverA.weight - serverB.weight || \n serverA.index - serverB.index\n ));\n \n // add all the servers into the free servers heap with the time it is available\n // being 0\n for (let i = 0; i < servers.length; i++) {\n freeServers.push({ weight: servers[i], index: i, availableTime: 0 })\n }\n \n const result = [];\n for (let i = 0; i < tasks.length; i++) {\n // find all the servers that are available and add them to the\n // free servers heap\n while (usedServers.size() && usedServers.peak().availableTime <= i) {\n freeServers.push(usedServers.pop());\n }\n // get the free server with the lowest weight or lower index\n // or the usedServer with the lowest start time.\n const server = freeServers.pop() || usedServers.pop();\n result.push(server.index);\n const availableTime = Math.max(i, server.availableTime);\n server.availableTime = availableTime + tasks[i];\n usedServers.push(server);\n }\n return result;\n};\n\nclass Heap {\n\n /**\n * Create a Heap\n * @param {function} compareFunction - compares child and parent element\n * to see if they should swap. If return value is less than 0 it will\n * swap to prioritize the child.\n */\n constructor(compareFunction) {\n this.store = [];\n this.compareFunction = compareFunction;\n }\n \n peak() {\n return this.store[0];\n }\n \n size() {\n return this.store.length;\n }\n \n pop() {\n if (this.size() < 2) {\n return this.store.pop();\n }\n const result = this.store[0];\n this.store[0] = this.store.pop();\n this.heapifyDown(0);\n return result;\n }\n \n push(val) {\n this.store.push(val);\n this.heapifyUp(this.size() - 1);\n }\n \n heapifyUp(child) {\n while (child) {\n const parent = Math.floor((child - 1) / 2);\n \n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n child = parent;\n } else {\n return child;\n }\n }\n }\n \n heapifyDown(parent) {\n while (true) {\n let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n if (this.shouldSwap(child2, child)) {\n child = child2;\n }\n \n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n parent = child;\n } else {\n return parent;\n }\n }\n }\n \n shouldSwap(child, parent) {\n return child && this.compareFunction(this.store[child], this.store[parent]) < 0;\n }\n}", "solution_java": "class Solution {\n public int[] assignTasks(int[] servers, int[] tasks) {\n\n PriorityQueue availableServer = new PriorityQueue((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[0] - b[0])));\n for(int i = 0; i < servers.length; i++){\n availableServer.add(new int[]{i, servers[i]});\n }\n\n //int[[] arr,\n //arr[0] - server index\n //arr[1] - server weight\n //arr[2] - free time\n PriorityQueue processingServer = new PriorityQueue(\n (a, b) ->\n\n (\n a[2] != b[2] ? a[2] - b[2] : // try to sort increasing order of free time\n a[1] != b[1] ? a[1] - b[1] : // try to sort increasing order of server weight\n a[0] - b[0] // sort increasing order of server index\n )\n );\n\n int[] result = new int[tasks.length];\n\n for(int i = 0; i < tasks.length; i++){\n\n while(!processingServer.isEmpty() && processingServer.peek()[2] <= i){\n int serverIndex = processingServer.remove()[0];\n availableServer.add(new int[]{serverIndex, servers[serverIndex]});\n }\n\n int currentTaskTimeRequired = tasks[i];\n\n int[] server;\n\n //when current task will free the server done\n int freeTime = currentTaskTimeRequired;\n\n if(!availableServer.isEmpty()){\n server = availableServer.remove();\n freeTime += i;\n }else{\n server = processingServer.remove();\n //append previous time\n freeTime += server[2];\n }\n\n int serverIndex = server[0];\n processingServer.add(new int[]{serverIndex, servers[serverIndex] ,freeTime});\n\n //assign this server to current task\n result[i] = serverIndex;\n }\n\n return result;\n\n }\n}", "solution_c": "class Solution {\npublic:\n vector assignTasks(vector& servers, vector& tasks) {\n priority_queue, vector>, greater>> free, busy; \n for (int i = 0; i < servers.size(); ++i) {\n free.push(vector{servers[i], i});\n }\n vector ans;\n long long time = 0;\n queue task_queue;\n while (ans.size() < tasks.size()) { \n // Bring all eligible tasks to task_queue.\n for (int i = ans.size() + task_queue.size(); i <= time && i < tasks.size(); ++i) {\n task_queue.push(tasks[i]);\n }\n // Bring all eligible servers to free queue.\n while (!busy.empty() && busy.top()[0] <= time) {\n auto& top = busy.top();\n free.push(vector{top[1], top[2]});\n busy.pop();\n }\n // If we have no servers, we cannot match until one of the servers becomes free.\n if (free.empty()) {\n time = busy.top()[0];\n continue;\n }\n while(!task_queue.empty() && !free.empty()) {\n // Now we just take the first task and first server as per defined priority and match the two.\n int task = task_queue.front(); \n auto& top = free.top();\n ans.push_back(top[1]);\n busy.push(vector{time + task, top[0], top[1]});\n task_queue.pop();\n free.pop();\n }\n // Only increment time to receive new tasks once we have processed all tasks so far.\n if (task_queue.empty()) time++;\n }\n return ans;\n }\n};" }, { "title": "Queries on a Permutation With Key", "algo_input": "Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:\n\n\n\tIn the beginning, you have the permutation P=[1,2,3,...,m].\n\tFor the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].\n\n\nReturn an array containing the result for the given queries.\n\n \nExample 1:\n\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1]. \n\n\nExample 2:\n\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\n\n\nExample 3:\n\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n\n\n \nConstraints:\n\n\n\t1 <= m <= 10^3\n\t1 <= queries.length <= m\n\t1 <= queries[i] <= m\n", "solution_py": "class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n perm=[i for i in range(1,m+1)]\n res=[]\n for i in queries:\n ind=perm.index(i)\n res.append(ind)\n perm=[perm.pop(ind)]+perm\n return res", "solution_js": "var processQueries = function(queries, m) {\n let result = [];\n let permutation = [];\n for(let i=0; i permutations = new ArrayList();\n\n // Filling the permuations array with numbers.\n for (int i = 0; i < m; i++)\n permutations.add(i+1);\n\n // Looping on the queries & checking their index in the permuations\n for (int i = 0; i < queries.length; i++) {\n int query = queries[i];\n for (int j = 0; j < permutations.size(); j++)\n if (permutations.get(j) == query) {\n results[i] = j;\n int temp = permutations.get(j);\n permutations.remove(j);\n permutations.add(0, temp);\n break;\n }\n }\n\n return results;\n\n }\n}", "solution_c": "class Solution {\npublic:\n vector processQueries(vector& queries, int m) {\n \n vector p;\n\n for(int i=0; i bool:\n unstable=0\n for i in range(1,len(nums)):\n if nums[i]1:\n return False\n return True", "solution_js": "var checkPossibility = function(nums) {\n let changed = false\n for(let i=nums.length-1; i>0; i--) {\n if(nums[i-1] > nums[i]) {\n if(changed) return false;\n if(i === nums.length-1 || nums[i-1] < nums[i+1]) nums[i] = nums[i-1]\n else nums[i-1] = nums[i];\n changed = true\n }\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean checkPossibility(int[] nums) {\n int modified = 0, prev = nums[0], index = 0;\n for (; index < nums.length; ++index) {\n if (nums[index] < prev) {\n if (++modified > 1) return false;\n if (index - 2 >= 0 && nums[index - 2] > nums[index]) continue;\n }\n prev = nums[index];\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\nbool checkPossibility(vector& nums) {\n if(nums.size()<=2)\n return true;\n //creating a diff array(size=n-1) to store differences bw 2 consecutive ele.\n vectordiff(nums.size()-1);\n int neg=0;\n \n for(int i=0;i1)\n return false;\n\n \n for(int i=0;i=0)\n continue; //if the first diff is neg, the next is obviosly>=0 as neg<=1, and this mountain can be resolved;\n // else\n // return false;\n \n if((nums[i-1]<=nums[i+1]) || (diff[i+1])>=abs(diff[i]))\n continue; //the major mountain cases, lemme know below if want explaination of these\n else \n return false;\n }\n } \n return true;\n}" }, { "title": "Minimum Number of Refueling Stops", "algo_input": "A car travels from a starting position to a destination which is target miles east of the starting position.\n\nThere are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.\n\nThe car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\n\nReturn the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.\n\nNote that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n\n \nExample 1:\n\nInput: target = 1, startFuel = 1, stations = []\nOutput: 0\nExplanation: We can reach the target without refueling.\n\n\nExample 2:\n\nInput: target = 100, startFuel = 1, stations = [[10,100]]\nOutput: -1\nExplanation: We can not reach the target (or even the first gas station).\n\n\nExample 3:\n\nInput: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput: 2\nExplanation: We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.\n\n\n \nConstraints:\n\n\n\t1 <= target, startFuel <= 109\n\t0 <= stations.length <= 500\n\t0 <= positioni <= positioni+1 < target\n\t1 <= fueli < 109\n\n", "solution_py": "class Solution:\n def minRefuelStops(self, t, F, S):\n S.append([t, 0])\n heap, ans = [], 0\n for p,f in S:\n while heap and p > F:\n F -= heapq.heappop(heap)\n ans += 1\n if p > F: return -1\n heapq.heappush(heap, -f)\n return ans", "solution_js": "var minRefuelStops = function(target, startFuel, stations) {\n let pq = new MaxPriorityQueue({compare: (a, b) => b[1] - a[1]});\n let idx = 0, reachablePosition = startFuel, refuels = 0;\n // reachablePosition is the farthest position reachable so far\n \n while (reachablePosition < target) {\n // While reachablePosition is >= to the current station's position, add the current station to the heap\n // These stations are all reachable based on the fuel available\n // Once reachablePosition is less than a station's position, the while loop ends\n while (idx < stations.length && reachablePosition >= stations[idx][0]) {\n pq.enqueue([stations[idx][0], stations[idx][1]]);\n idx++;\n }\n // Next, add fuel from the heap in a greedy manner: the station with the most fuel gets added first\n // All stations in the heap are reachable, so the position is irrelevant \n if (pq.size()) {\n let [pos, fuel] = pq.dequeue();\n reachablePosition += fuel;\n refuels++;\n } else break;\n }\n \n return reachablePosition >= target ? refuels : -1;\n};", "solution_java": "class Solution {\n public int minRefuelStops(int target, int startFuel, int[][] stations) {\n if(startFuel >= target) return 0;\n int[][] dp = new int[stations.length + 1][stations.length + 1];\n for (int i = 0; i < dp.length; i++) dp[i][0] = startFuel;\n for (int j = 1; j < dp.length; j++) {\n for (int i = j; i < dp.length; i++) {\n dp[i][j] = Math.max(dp[i-1][j], stations[i-1][0] > dp[i-1][j-1] ?\n Integer.MIN_VALUE : dp[i-1][j-1] + stations[i-1][1]);\n if(dp[i][j] >= target) return j;\n }\n }\n return -1;\n }\n}", "solution_c": "/*\n\nThe approach here used is - first cosider the stations which are possible at a particular time and then take the one with maximum fuel that can be filled this ensure that with only one fill up the vehicle will move to furthest distance.\n\nNow there might be case where if we don't fill up from multiple stations ata paritcular time, then it will not be possible to reach end as there might not be any stations at the ending side of the target. \n\nTo handle above case, when such situation arise then we need to take the next max fuel refill that is pissible from the already seen stations.\nLike this way keep on taking fuels from stations in decreasing manner.\n\nIf at any point of time the queue is empty then, it means we do not have sufficent fuel to reach target.\n\n=> This logic can be implemented by simply using a priority queue where the max fuel station is at top of the queue.\n\n\n*/\n\nclass Solution {\npublic:\n int minRefuelStops(int target, int startFuel, vector>& stations) {\n auto comp = [](vector a, vector b){ return a[1] < b[1]; };\n priority_queue, vector>, decltype(comp)> pq(comp);\n int i = 0, distance = startFuel, refillCount = 0;\n while(distance < target ){\n while(i < stations.size() && distance >= stations[i][0]){\n pq.push(stations[i++]);\n }\n if(pq.empty()) return -1;\n distance += pq.top()[1];\n refillCount++;\n pq.pop();\n }\n return refillCount;\n }\n};" }, { "title": "Distribute Repeating Integers", "algo_input": "You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:\n\n\n\tThe ith customer gets exactly quantity[i] integers,\n\tThe integers the ith customer gets are all equal, and\n\tEvery customer is satisfied.\n\n\nReturn true if it is possible to distribute nums according to the above conditions.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4], quantity = [2]\nOutput: false\nExplanation: The 0th customer cannot be given two different integers.\n\n\nExample 2:\n\nInput: nums = [1,2,3,3], quantity = [2]\nOutput: true\nExplanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n\n\nExample 3:\n\nInput: nums = [1,1,2,2], quantity = [2,2]\nOutput: true\nExplanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t1 <= nums[i] <= 1000\n\tm == quantity.length\n\t1 <= m <= 10\n\t1 <= quantity[i] <= 105\n\tThere are at most 50 unique values in nums.\n\n", "solution_py": "class Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n freq = {}\n for x in nums: freq[x] = 1 + freq.get(x, 0)\n \n vals = sorted(freq.values(), reverse=True)\n quantity.sort(reverse=True) # pruning - large values first \n \n def fn(i): \n \"\"\"Return True if possible to distribute quantity[i:] to remaining.\"\"\"\n if i == len(quantity): return True \n seen = set()\n for k in range(len(vals)): \n if vals[k] >= quantity[i] and vals[k] not in seen: \n seen.add(vals[k]) # pruning - unqiue values \n vals[k] -= quantity[i]\n if fn(i+1): return True \n vals[k] += quantity[i] # backtracking\n \n return fn(0)", "solution_js": "var canDistribute = function(nums, quantity) {\n quantity.sort((a,b)=>b-a)\n let freq={},flag=false\n for(let num of nums)\n freq[num]=(freq[num]||0) +1\n let set=Object.keys(freq),n=set.length,k=quantity.length\n let rec=(prefix)=>{\n if(prefix.length==k || flag==true) \n return flag=true\n for(let i=0;i=0)\n rec(prefix)\n\t\t\tprefix.pop()\n freq[set[i]]+=quantity[prefix.length]\n }\n }\n rec([])\n return flag\n};", "solution_java": "class Solution {\n public boolean canDistribute(int[] nums, int[] quantity) {\n \n // Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}\n Map freq = new HashMap<>();\n for (int num : nums)\n freq.put(num, freq.getOrDefault(num, 0)+1);\n \n // Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]\n int[] dist = new int[freq.size()];\n int idx = 0;\n for (int f : freq.values())\n dist[idx++] = f;\n \n\t\t// Fullfill the quantities from the biggest quantity to the smallest.\n // If the bigger quantity can't be filled, the program will stop as early as possible.\n Arrays.sort(quantity);\n return rec(dist, quantity, quantity.length-1);\n }\n \n // try to fullfill the j-th order quantity\n private boolean rec(int[] dist, int[] quantity, int j) {\n \n // stop condition. We've fulfilled all the order quantities.\n if (j == -1)\n return true;\n \n Set used = new HashSet<>();\n for (int i = 0 ; i < dist.length ; ++i) {\n\t\t\n\t\t\t// Use a set to make sure that \n\t\t\t// we don't distribute from the same amount to this j-th order for more than once.\n // With this check, the program reduces from 97ms to 25 ms.\n if (dist[i] >= quantity[j] && used.add(dist[i])) {\n dist[i] -= quantity[j];\n if (rec(dist, quantity, j-1))\n return true;\n dist[i] += quantity[j];\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool solve(vector&q, map&count, int idx){\n if(idx==q.size()){\n return true;\n }\n for(auto it=count.begin();it!=count.end();it++){\n if(it->second>=q[idx]){\n count[it->first]-=q[idx];\n if(solve(q,count,idx+1))\n return true;\n count[it->first]+=q[idx];\n }\n }\n return false;\n }\n bool canDistribute(vector& nums, vector& quantity) {\n mapcount;\n int n=nums.size();\n for(int i=0;i());\n return solve(quantity,count,0);\n\n }\n};" }, { "title": "Number of Ways to Select Buildings", "algo_input": "You are given a 0-indexed binary string s which represents the types of buildings along a street where:\n\n\n\ts[i] = '0' denotes that the ith building is an office and\n\ts[i] = '1' denotes that the ith building is a restaurant.\n\n\nAs a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.\n\n\n\tFor example, given s = \"001101\", we cannot select the 1st, 3rd, and 5th buildings as that would form \"011\" which is not allowed due to having two consecutive buildings of the same type.\n\n\nReturn the number of valid ways to select 3 buildings.\n\n \nExample 1:\n\nInput: s = \"001101\"\nOutput: 6\nExplanation: \nThe following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.\n\n\nExample 2:\n\nInput: s = \"11100\"\nOutput: 0\nExplanation: It can be shown that there are no valid selections.\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 105\n\ts[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\n def numberOfWays(self, s: str) -> int:\n \n temp = []\n c0 = 0\n c1 = 0\n for char in s :\n if char == \"0\" :\n c0+=1\n else:\n c1+=1\n temp.append([c0,c1])\n \n total0 = c0\n total1 = c1\n \n \n count = 0\n for i in range(1, len(s)-1) :\n \n if s[i] == \"0\" :\n m1 = temp[i-1][1]\n m2 = total1 - temp[i][1]\n count += m1*m2\n \n else:\n m1 = temp[i-1][0]\n m2 = total0 - temp[i][0]\n count += m1*m2\n return count\n \n ", "solution_js": "var numberOfWays = function(s) {\n const len = s.length;\n const prefix = new Array(len).fill(0).map(() => new Array(2).fill(0));\n for(let i = 0; i < len; i++) {\n const idx = s[i] == '1' ? 1 : 0;\n if(i == 0) prefix[i][idx]++;\n else {\n prefix[i] = Array.from(prefix[i-1]);\n prefix[i][idx]++;\n }\n }\n let ans = 0;\n for(let i = 1; i < len - 1; i++) {\n const c = s[i] == '1' ? 0 : 1;\n ans += (prefix.at(-1)[c] - prefix[i][c]) * prefix[i-1][c];\n }\n return ans;\n};", "solution_java": "class Solution\n{\n public long numberOfWays(String s)\n {\n int zero = 0; // Individual zeroes count\n long zeroOne = 0; // Number of combinations of 01s\n int one = 0; // Individual ones count\n long oneZero = 0; // Number of combinations of 10s\n long tot = 0; // Final answer\n for(char ch : s.toCharArray())\n {\n if(ch == '0')\n {\n zero++;\n if(one > 0)\n oneZero += one; // Each of the previously found 1s can pair up with the current 0 to form 10\n if(zeroOne > 0)\n tot += zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to form 010\n }\n else\n {\n one++;\n if(zero > 0)\n zeroOne += zero; // Each of the previously found 0s can pair to form 01\n if(oneZero > 0)\n tot += oneZero; // Each of the previously formed 10 can form 101\n }\n }\n return tot;\n }\n}", "solution_c": "class Solution {\npublic:\n long long numberOfWays(string s) {\n long long a=0,b=0,ans=0; // a and b are the number of occurances of '1' and '0' after the current building respectively.\n for(int i=0;i int:\n n = len(arr)\n small_before = [-1]*n\n stack = []\n for i in range(n):\n while stack and arr[stack[-1]] >= arr[i]:\n stack.pop()\n if stack:small_before[i] = stack[-1]\n stack.append(i)\n best = [0]*(n+1)\n ans = 0\n for i in range(n):\n best[i] = best[small_before[i]] + (i - small_before[i])*arr[i]\n ans += best[i]\n return ans%1000000007", "solution_js": "var sumSubarrayMins = function(arr) {\n \n M = 10**9+7\n stack = [-1]\n res = 0\n arr.push(0)\n \n for(let i2 = 0; i2 < arr.length; i2++){\n while(arr[i2] < arr[stack[stack.length -1]]){\n i = stack.pop()\n i1 = stack[stack.length-1]\n Left = i - i1\n Right = i2 -i\n res += (Left*Right*arr[i])\n };\n stack.push(i2)\n };\n \n return res%M\n};", "solution_java": "class Solution {\n public int sumSubarrayMins(int[] arr) {\n int n = arr.length;\n int ans1[] = nsl(arr);\n int ans2[] = nsr(arr);\n long sum=0;\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=0;i s = new Stack<>();\n int ans[] = new int[arr.length];\n for(int i=arr.length-1;i>=0;i--){\n while(!s.isEmpty() && arr[s.peek()]>=arr[i]){\n s.pop();\n }\n if(s.isEmpty()){\n ans[i] = arr.length-i;\n s.push(i);\n }\n else{\n ans[i] = s.peek()-i;\n s.push(i);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic: //Thanks to Bhalerao-2002\n int sumSubarrayMins(vector& A) {\n \n int n = A.size();\n int MOD = 1e9 + 7;\n vector left(n), right(n);\n \n // for every i find the Next smaller element to left and right\n \n // Left\n stackst;\n st.push(0);\n left[0] = 1; // distance = 1, left not found, this is distance multiplied with num, so it can't be zero\n for(int i=1; i=0; i--)\n {\n while(!st.empty() && A[i] <= A[st.top()]) \n st.pop();\n \n if(st.empty()) \n right[i] = n-i; // distance\n else \n right[i] = st.top()-i;\n \n st.push(i);\n }\n \n // total number of subarrays : (Left[i] * Right[i])\n // total contribution in A[i] element in final answer : (Left * Right) * A[i] \n \n for(int i=0; i{\n if(x!=='9'&&flag){\n flag=false\n return '9'\n }\n return x\n })\n return parseInt(num.join(''))\n};", "solution_java": "class Solution {\n public int maximum69Number (int num) {\n int i;\n String s=String.valueOf(num);\n int l=s.length();\n int max=num;\n \n for(i=0;i List[int]:\n x = Counter(nums)\n return([y for y in x if x[y] == 1])", "solution_js": "var singleNumber = function(nums) {\n let hash ={}\n for ( let num of nums){\n if( hash[num]===undefined)\n hash[num] =1\n else\n hash[num]++\n }\n\n let result =[]\n for ( let [key, value] of Object.entries(hash)){\n if(value==1)\n result.push(key)\n }\n return result\n};", "solution_java": "class Solution {\n public int[] singleNumber(int[] nums) {\n if (nums == null || nums.length < 2 || nums.length % 2 != 0) {\n throw new IllegalArgumentException(\"Invalid Input\");\n }\n\n int aXORb = 0;\n for (int n : nums) {\n aXORb ^= n;\n }\n\n int rightSetBit = aXORb & -aXORb;\n int a = 0;\n for (int n : nums) {\n if ((n & rightSetBit) != 0) {\n a ^= n;\n }\n }\n\n return new int[] {a, aXORb ^ a};\n }\n}", "solution_c": "class Solution {\npublic:\n vector singleNumber(vector& nums){\n vector ans;\n int xorr = 0;\n for(int i=0; i> 1;\n }\n int xorr1 = 0;\n int xorr2 = 0;\n for(int i=0; i float:\n taxtot=0\n if(brackets[0][0]0 and i(brackets[i][0]-brackets[i-1][0])):\n taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]\n income-=brackets[i][0]-brackets[i-1][0]\n else:\n taxtot+=income*brackets[i][1]\n income=0\n i+=1\n return taxtot/100", "solution_js": "var calculateTax = function(brackets, income) {\n return brackets.reduce(([tax, prev], [upper, percent]) => {\n let curr = Math.min(income, upper - prev);\n tax += curr * (percent / 100);\n\n income -= curr;\n if (income <= 0) brackets.length = 0;\n\n return [tax, upper];\n }, [0, 0])[0];\n};", "solution_java": "class Solution {\n public double calculateTax(int[][] brackets, int income) {\n double ans=0;\n int pre=0;\n for(int[] arr : brackets){\n int val=arr[0]; arr[0]-=pre; pre=val;\n ans+=(double)(Math.min(income,arr[0])*arr[1])/100;\n income-=arr[0];\n if(income<=0){ break; }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n double calculateTax(vector>& brackets, int income) \n { \n double tax = 0; \n \n if(brackets[0][0]<=income) tax=(brackets[0][0]*brackets[0][1]/100.0); \n else return (income*brackets[0][1]/100.0);\n \n for(int i=1; i= self.end:\n if not self.right:\n return True\n else:\n return self.right.insertable(node)\n else:\n if self.val == 1:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n if not self.left and not self.right:\n return True\n elif not self.left:\n return self.right.insertable(Node(rightS, rightE, 1))\n elif not self.right:\n return self.left.insertable(Node(leftS, leftE, 1))\n else:\n resL = self.left.insertable(Node(leftS, leftE, 1))\n resR = self.right.insertable(Node(rightS, rightE, 1))\n if resL and resR:\n return True\n return False\n else:\n return False\n\n def insert(self, node):\n if node.end <= node.start:\n return\n \n if node.end <= self.start:\n if not self.left:\n self.left = node\n else:\n self.left.insert(node)\n elif node.start >= self.end:\n if not self.right:\n self.right = node\n else:\n self.right.insert(node)\n else:\n leftS = min(self.start, node.start)\n leftE = max(self.start, node.start)\n rightS = min(self.end, node.end)\n rightE = max(self.end, node.end)\n self.val += 1\n self.start, self.end = leftE, rightS \n if not self.left and not self.right: \n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n elif not self.left:\n self.left = Node(leftS, leftE, 1) if leftS < leftE else None\n self.right.insert(Node(rightS, rightE, 1))\n elif not self.right:\n self.right = Node(rightS, rightE, 1) if rightS < rightE else None\n self.left.insert(Node(leftS, leftE, 1))\n else:\n self.left.insert(Node(leftS, leftE, 1))\n self.right.insert(Node(rightS, rightE, 1))\n return\n\n\nclass MyCalendarTwo:\n\n def __init__(self):\n self.root = None\n\n def book(self, start: int, end: int) -> bool:\n if not self.root:\n self.root = Node(start, end, 1)\n return True\n else:\n newNode = Node(start, end, 1)\n if self.root.insertable(newNode):\n self.root.insert(newNode)\n return True\n return False", "solution_js": "var MyCalendarTwo = function() {\n this.calendar = [];\n this.overlaps = [];\n};\n\n/** \n * @param {number} start \n * @param {number} end\n * @return {boolean}\n */\nMyCalendarTwo.prototype.book = function(start, end) {\n for (let date of this.overlaps) {\n if (start < date[1] && end > date[0]) return false;\n }\n\n for (let date of this.calendar) {\n if (start < date[1] && end > date[0]) {\n this.overlaps.push([Math.max(date[0], start), Math.min(date[1], end)]);\n }\n }\n this.calendar.push([start, end]); \n return true;\n};", "solution_java": "class MyCalendarTwo {\n private List bookings;\n private List doubleBookings;\n \n public MyCalendarTwo() {\n bookings = new ArrayList<>();\n doubleBookings = new ArrayList<>();\n }\n \n \n public boolean book(int start, int end) {\n for(int[] b : doubleBookings)\n {\n\t\t//condition to check for the overlaping\n if(start < b[1] && end > b[0])\n return false;\n }\n \n for(int[] b : bookings)\n {\n if(start < b[1] && end > b[0]) {\n doubleBookings.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});\n }\n }\n bookings.add(new int[]{start, end});\n return true;\n }\n}", "solution_c": "class MyCalendarTwo {\npublic:\n mapmpp;\n MyCalendarTwo() {\n\n }\n\n bool book(int start, int end) {\n mpp[start]++;\n mpp[end]--;\n int sum=0;\n for(auto it:mpp){\n sum+=it.second;\n if(sum>2){\n mpp[start]--;\n mpp[end]++;\n return false;\n }\n }\n return true;\n }\n};" }, { "title": "Largest Values From Labels", "algo_input": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit.\n\nChoose a subset s of the n elements such that:\n\n\n\tThe size of the subset s is less than or equal to numWanted.\n\tThere are at most useLimit items with the same label in s.\n\n\nThe score of a subset is the sum of the values in the subset.\n\nReturn the maximum score of a subset s.\n\n \nExample 1:\n\nInput: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput: 9\nExplanation: The subset chosen is the first, third, and fifth items.\n\n\nExample 2:\n\nInput: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput: 12\nExplanation: The subset chosen is the first, second, and third items.\n\n\nExample 3:\n\nInput: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput: 16\nExplanation: The subset chosen is the first and fourth items.\n\n\n \nConstraints:\n\n\n\tn == values.length == labels.length\n\t1 <= n <= 2 * 104\n\t0 <= values[i], labels[i] <= 2 * 104\n\t1 <= numWanted, useLimit <= n\n\n", "solution_py": "from collections import defaultdict\nimport heapq\n\nclass Solution:\n def largestValsFromLabels(\n self, values: list[int], labels: list[int], numWanted: int, useLimit: int\n ) -> int:\n\n # Add labels and values into the heap\n heap = [(-value, label) for value, label in zip(values, labels)]\n heapq.heapify(heap)\n\n # Initialize the hashmap\n used = defaultdict(int)\n\n # Initialize the result\n res = 0\n\n # Iterate until we have used a certain number or the heap is empty\n while numWanted > 0 and heap:\n\n # Pop a label and its value from the heap\n value, label = heapq.heappop(heap)\n\n # If we can use such label\n if used[label] < useLimit:\n\n # Add its value to the result\n res += -value\n\n # Increment its count in the hashmap\n used[label] += 1\n\n # Decrement the number of numbers we still want\n numWanted -= 1\n\n return res", "solution_js": "/**\n * @param {number[]} values\n * @param {number[]} labels\n * @param {number} numWanted\n * @param {number} useLimit\n * @return {number}\n */\nvar largestValsFromLabels = function(values, labels, numWanted, useLimit) {\n // this sortValues will create an addition array that keep track of the value idx after descending sort\n // which is useful to map the labels accordingly\n let sortValues = values.map((val, idx) => [val, idx]), sortLabels = []\n sortValues.sort((a, b) => b[0] - a[0])\n \n for (let [val, idx] of sortValues) {\n sortLabels.push(labels[idx])\n }\n values.sort((a, b) => b - a)\n labels = sortLabels\n \n let i = 0, map = {}, ans = 0\n while (i < values.length && numWanted > 0) {\n if (map[labels[i]]) map[labels[i]] ++\n else map[labels[i]] = 1\n \n if ((map[labels[i]]) <= useLimit) {\n ans += values[i]\n numWanted--\n }\n \n i++\n }\n \n return ans\n \n};", "solution_java": "class Solution {\n public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {\n PriorityQueue> maxHeap = \n new PriorityQueue<>((a, b) -> Integer.compare(b.getKey(), a.getKey()));\n for(int i=0;i(values[i], labels[i]));\n }\n Map labelLimitMap = new HashMap<>();\n int sum = 0;\n while(numWanted != 0) {\n int label = maxHeap.peek().getValue();\n if(labelLimitMap.containsKey(label)) {\n if(labelLimitMap.get(label) == useLimit) {\n maxHeap.poll();\n } else {\n labelLimitMap.put(label, labelLimitMap.get(label) + 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n } else {\n labelLimitMap.put(label, 1);\n sum += maxHeap.poll().getKey();\n numWanted--;\n }\n // This Holds since at most numWanted is mentioned.\n if(maxHeap.isEmpty()) {\n return sum;\n }\n }\n return sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int largestValsFromLabels(vector& values, vector& labels, int numWanted, int useLimit) {\n // same label item should be less than uselimit\n priority_queue>q; // this will give us maximum element because we need to maximise the sum \n for(int i=0;im;\n // we cant use more numbers than useLimit\n // storing each use labels in map to count the use limit of that number\n int i=0;\n while(i int:\n def srange(a, b):\n return [chr(i) for i in range(ord(a),ord(b)+1)]\n def LPS(pat):\n lps = [0]\n i, target = 1, 0\n while i < len(pat):\n if pat[i] == pat[target]:\n target += 1\n lps.append(target)\n i += 1\n elif target:\n target = lps[target-1]\n else:\n lps.append(0)\n i += 1\n return lps\n lps = LPS(evil)\n M = 10**9+7\n @lru_cache(None)\n def dfs(i, max_matched_idx, lb, rb):\n if max_matched_idx == len(evil): return 0\n if i == n: return 1\n l = s1[i] if lb else 'a'\n r = s2[i] if rb else 'z'\n candidates = srange(l, r)\n res = 0\n for j, c in enumerate(candidates):\n nxt_matched_idx = max_matched_idx\n while evil[nxt_matched_idx] != c and nxt_matched_idx:\n nxt_matched_idx = lps[nxt_matched_idx-1]\n res = (res + dfs(i+1, nxt_matched_idx+(c==evil[nxt_matched_idx]),\n lb = (lb and j == 0), rb = (rb and j==len(candidates)-1)))%M\n return res\n return dfs(0, 0, True, True)", "solution_js": "const mod = 10 ** 9 + 7\n\nlet cache = null\n\n/**\n * @param {number} n\n * @param {string} s1\n * @param {string} s2\n * @param {string} evil\n * @return {number}\n */\nvar findGoodStrings = function(n, s1, s2, evil) {\n /**\n * 17 bits\n * - 9 bit: 2 ** 9 > 500 by evil\n * - 6 bit: 2 ** 6 > 50 by evil\n * - 1 bit left (bound)\n * - 1 bit right (bound)\n *\n * cache: `mainTraver` is the prefix length, `evilMatch` is matching for evil\n *\n * answer: marnTravel 0, evil 0, s prefix has the last character\n */\n cache = new Array(1 << 17).fill(-1)\n return dfs(0, 0, n, s1, s2, evil, true, true, computeNext(evil))\n}\n/**\n * DFS:\n * 1. loop from `s1` to `s2`, range of position `i` is [0, n]: 0 means no start, n means complete\n * 2. if `s1` has traversed to nth, it means has been generated a legal character, and return 1; else\n * 3. `mainTravel` is the length of the `s` generated by dfs last time\n * 4. `evilMatch` is the length that matches the last generated `s` in evilMatch evil\n * 5. n, s1, s2, evil, left, right, next\n */\nfunction dfs(mainTravel, evilMatch, n, s1, s2, evil, left, right, next, ans = 0) {\n // same length means that the match has been successful\n if(evilMatch === evil.length) {\n return 0\n }\n // this means s is conformed\n if(mainTravel === n) {\n return 1\n }\n \n // get key for cache\n let key = generateKey(mainTravel, evilMatch, left, right)\n // because any combination of the four categories will only appear once, there will be no repetition\n if(cache[key] !== -1) {\n return cache[key]\n }\n \n // get start, end calculate\n let [start, end] = [left ? s1.charCodeAt(mainTravel) : 97, right ? s2.charCodeAt(mainTravel) : 122]\n \n // loop\n for(let i = start; i <= end; i++) {\n // get char code\n let code = String.fromCharCode(i)\n // actually, `evilMatch` will only get longer or stay the same, not shorter\n let m = evilMatch\n \n while((m > 0) && (evil[m] !== code)) {\n m = next[m - 1]\n }\n\n if(evil[m] === code) {\n m++\n }\n\n // recursive\n ans += dfs(mainTravel + 1, m, n, s1, s2, evil, left && (i === start), right && (i === end), next)\n \n // too large\n ans %= mod\n }\n\n // result after cache set\n return cache[key] = ans, ans\n}\n\n// create key for cache\nfunction generateKey(mainTravel, evilMatch, left, right) {\n return (mainTravel << 8) | (evilMatch << 2) | ((left ? 1 : 0 ) << 1) | (right ? 1 : 0)\n}\n\n// for next right move, index + 1\nfunction computeNext(evil, n = evil.length, ans = new Array(n).fill(0), k = 0) {\n for(let i = 1; i < n; i++) {\n while((k > 0) && (evil[i] !== evil[k])) {\n k = ans[k - 1]\n }\n\n if(evil[i] === evil[k]) {\n ans[i] = ++k\n }\n }\n return ans\n}", "solution_java": "class Solution {\n Integer[][][][] dp;\n int mod = 1000000007;\n int[] lps;\n private int add(int a, int b) {\n return (a % mod + b % mod) % mod;\n }\n private int solve(char[] s1, char[] s2, int cur, boolean isStrictLower, boolean isStrictUpper, char[] evil, int evI) {\n if(evI == evil.length) return 0;\n if(cur == s2.length) return 1;\n if(dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] != null) return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI];\n char start = isStrictLower ? s1[cur] : 'a';\n char end = isStrictUpper ? s2[cur] : 'z';\n int res = 0;\n for(char ch = start; ch <= end; ch ++) {\n if(evil[evI] == ch)\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, evI + 1));\n else {\n int j = evI;\n while (j > 0 && evil[j] != ch) j = lps[j - 1];\n if (ch == evil[j]) j++;\n res = add(res, solve(s1, s2, cur + 1, isStrictLower && ch == start, isStrictUpper && ch == end, evil, j));\n }\n }\n return dp[cur][isStrictLower ? 1 : 0][isStrictUpper ? 1 : 0][evI] = res;\n }\n public int findGoodStrings(int n, String s1, String s2, String evil) {\n char[] arr = s1.toCharArray();\n char[] brr = s2.toCharArray();\n char[] crr = evil.toCharArray();\n lps = new int[crr.length];\n for (int i = 1, j = 0; i < crr.length; i++) {\n while (j > 0 && crr[i] != crr[j]) j = lps[j - 1];\n if (crr[i] == crr[j]) lps[i] = ++j;\n }\n dp = new Integer[n][2][2][crr.length];\n return solve(arr, brr, 0, true, true, crr, 0);\n }\n}", "solution_c": "class Solution {\npublic:\n using ll = long long;\n int findGoodStrings(int n, string s1, string s2, string evil) {\n int M = 1e9+7;\n int m = evil.size();\n // kmp\n int f[m];\n f[0] = 0;\n for (int i = 1, j = 0; i < m; ++i) {\n while (j != 0 && evil[i] != evil[j]) {\n j = f[j-1];\n }\n if (evil[i] == evil[j]) {\n ++j;\n }\n f[i] = j;\n }\n // next(i,c) jump function when matched i length and see c\n int next[m+1][26];\n for (int i = 0; i <= m; ++i) {\n for (int j = 0; j < 26; ++j) {\n if (i < m && evil[i] == 'a'+j) {\n next[i][j] = i+1;\n } else {\n next[i][j] = i == 0? 0: next[f[i-1]][j];\n }\n }\n }\n // dp(i,j,l1,l2) length i greater than s1, less than s2;\n // match j length of evil\n // l1 true means limited for s1, l2 true means limited for s2\n ll dp[n+1][m+1][2][2];\n memset(dp, 0, sizeof(dp));\n dp[0][0][1][1] = 1;\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < m; ++j) {\n for (int c = 0; c < 26; ++c) {\n int k = next[j][c];\n char ch = 'a'+c;\n dp[i+1][k][0][0] += dp[i][j][0][0];\n if (dp[i][j][1][1]) {\n if (ch > s1[i] && ch < s2[i]) {\n dp[i+1][k][0][0] += dp[i][j][1][1];\n } else if (ch == s1[i] && ch == s2[i]) {\n dp[i+1][k][1][1] += dp[i][j][1][1];\n } else if (ch == s1[i]) {\n dp[i+1][k][1][0] += dp[i][j][1][1];\n } else if (ch == s2[i]) {\n dp[i+1][k][0][1] += dp[i][j][1][1];\n }\n }\n if (dp[i][j][1][0]) {\n if (ch > s1[i]) {\n dp[i+1][k][0][0] += dp[i][j][1][0];\n } else if (ch == s1[i]) {\n dp[i+1][k][1][0] += dp[i][j][1][0];\n }\n }\n if (dp[i][j][0][1]) {\n if (ch < s2[i]) {\n dp[i+1][k][0][0] += dp[i][j][0][1];\n } else if (ch == s2[i]) {\n dp[i+1][k][0][1] += dp[i][j][0][1];\n }\n }\n dp[i+1][k][0][0] %= M;\n }\n }\n }\n ll ans = 0;\n for (int i = 0; i < m; ++i) {\n ans += dp[n][i][0][0] + dp[n][i][0][1] + dp[n][i][1][0];\n ans %= M;\n }\n return ans;\n }\n};" }, { "title": "Allocate Mailboxes", "algo_input": "Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.\n\nReturn the minimum total distance between each house and its nearest mailbox.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n \nExample 1:\n\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n\n\nExample 2:\n\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n\n\n \nConstraints:\n\n\n\t1 <= k <= houses.length <= 100\n\t1 <= houses[i] <= 104\n\tAll the integers of houses are unique.\n\n", "solution_py": "class Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n houses.sort()\n\n @lru_cache(None)\n def dp(left, right, k):\n if k == 1: # <-- 1.\n mid = houses[(left+right) // 2]\n return sum(abs(houses[i] - mid) for i in range(left, right + 1))\n\n return min(dp(left, i, 1) + dp(i+1, right, k - 1) \n for i in range(left, right - k + 2)) # <-- 2.\n\n return dp(0, len(houses)-1, k)", "solution_js": "/**\n * @param {number[]} houses\n * @param {number} k\n * @return {number}\n */\nvar minDistance = function(houses, k) {\n var distance=[],median,dist,cache={};\n houses.sort(function(a,b){return a-b});\n //distance[i][j] is the minimun distacne if we cover houses from ith index to jth index with 1 mailbox. This mailbox will be at the median index of sub array from ith index to jth index.\n for(let i=0;i= 0; m--){\n sum += houses[(m+j+1)>>1]-houses[m]; // likewise, adding to the front needs the +1 to account for the truncation.\n next[j] = Math.min(next[j], (m==0?0:dp[m-1])+sum);\n }\n }\n dp=next;\n }\n return dp[n-1];\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[101][101] ;\n int solve(vector&houses , int pos , int k){\n if(k < 0) return 1e9 ;\n if(pos >= houses.size()) return k ? 1e9 : 0 ; \n if(dp[pos][k] != -1) return dp[pos][k] ;\n \n //at current position pos, spread the group from (pos upto j) and allot this whole group 1 mailbox.\n //start new neigbour at j + 1\n \n int ans = INT_MAX ;\n for(int j = pos ; j < houses.size() ; ++j ){\n int middle = (pos + j) / 2 , cost = 0 ;\n //cost calculation\n for(int i = pos ; i <= j ; ++i ) cost += abs(houses[middle] - houses[i]);\n \n ans = min(ans,cost + solve(houses,j + 1, k - 1)) ;\n }\n return dp[pos][k] = ans ;\n }\n int minDistance(vector& houses, int k) {\n sort(begin(houses),end(houses)) ;\n memset(dp,-1,sizeof(dp)) ;\n \n return solve(houses,0,k);\n }\n};" }, { "title": "Shortest Completing Word", "algo_input": "Given a string licensePlate and an array of strings words, find the shortest completing word in words.\n\nA completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.\n\nFor example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\".\n\nReturn the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.\n\n \nExample 1:\n\nInput: licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput: \"steps\"\nExplanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.\n\n\nExample 2:\n\nInput: licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput: \"pest\"\nExplanation: licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.\n\n\n \nConstraints:\n\n\n\t1 <= licensePlate.length <= 7\n\tlicensePlate contains digits, letters (uppercase or lowercase), or space ' '.\n\t1 <= words.length <= 1000\n\t1 <= words[i].length <= 15\n\twords[i] consists of lower case English letters.\n\n", "solution_py": "class Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n newPlate = '' # modify the licensePlate\n for i in licensePlate:\n if i.isalpha():\n newPlate += i.lower()\n \n c = Counter(newPlate)\n l1 = [] # store (word,len,index)\n for idx,word in enumerate(words):\n if Counter(word) >= c:\n l1.append((word,len(word),idx))\n l1.sort(key = lambda x:(x[1],idx))\n return l1[0][0]", "solution_js": "var shortestCompletingWord = function(licensePlate, words) {\n\n // Object to hold the shortest word that matches\n var match = {'found':false, 'word':''};\n\n // Char array to hold the upper case characters we want to match\n var licensePlateChars = licensePlate.toUpperCase().replace(/[^A-Z]/g, '').split('');\n\n words.forEach(function (word) {\n // if we already have a match make sure that the word we are checking is shorter\n if (!match.found || word.length < match.word.length) {\n var replaceWord = word.toUpperCase();\n\n // Loop over each character in the license plate and replace one at a time\n // the key here is that replace will only replace 1 S even if there are 2\n licensePlateChars.forEach(function (lChar) {\n replaceWord = replaceWord.replace(lChar, '');\n });\n\n // We know the word works if the length of the word minus\n // the length of chars equals the length of the new word\n if (word.length - licensePlateChars.length === replaceWord.length) {\n match.found = true;\n match.word = word\n }\n }\n });\n\n return match.word;\n};", "solution_java": "class Solution {\n public String shortestCompletingWord(String licensePlate, String[] words) {\n //Store count of letters in LicensePlate\n int[] licensePlateCount = new int[26];\n \n //To store all words which meet the criteria\n ArrayList res = new ArrayList<>();\n //To find min length word that meets the criteria\n int min = Integer.MAX_VALUE;\n \n //Add char count for each char in LicensePlate\n for(Character c:licensePlate.toCharArray()) {\n if(isChar(c)) {\n licensePlateCount[Character.toLowerCase(c) - 'a']++;\n }\n }\n \n //Add char count for each word in words\n for(String word : words) {\n int[] wordCharCount = new int[26];\n boolean flag = true;\n \n for(Character c:word.toCharArray()) {\n wordCharCount[Character.toLowerCase(c) - 'a']++;\n }\n \n //Eliminate words that don't satisfy the criteria\n for(int i = 0; i<26;i++) {\n if(licensePlateCount[i] > wordCharCount[i]) flag = false;\n }\n \n //Add words satisfying criteria to res and calculate min word length\n if(flag) {\n res.add(word);\n if(word.length() < min) min = word.length();\n }\n }\n \n //Return 1st word in array meeting all criteria\n for(int i = 0; i < res.size();i++) {\n if(res.get(i).length() == min) return res.get(i);\n }\n \n //If not found, return -1 (or whatever interviewer expects)\n return \"-1\";\n }\n \n private boolean isChar(Character c) {\n if((c >='a' && c <='z') ||\n (c>='A' && c<='Z')) return true;\n \n return false;\n }\n}", "solution_c": "\tclass Solution {\npublic:\n string shortestCompletingWord(string licensePlate, vector& words) \n {\n string ans=\"\";\n vector m(26,0);\n for(auto &lp:licensePlate)\n {\n if(isalpha(lp))\n m[tolower(lp)-'a']++;\n }\n for(auto &word:words)\n {\n vector v=m;\n for(auto &ch:word)\n {\n v[tolower(ch)-'a']--;\n }\n bool flag=true;\n for(int i=0;i<26;i++)\n {\n if(v[i]>0)\n flag =false;\n }\n if(flag&&(ans==\"\"||ans.size()>word.size()))\n ans=word;\n }\n return ans;\n \n }\n};\n//if you like the solution plz upvote." }, { "title": "Number of Increasing Paths in a Grid", "algo_input": "You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.\n\nReturn the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.\n\nTwo paths are considered different if they do not have exactly the same sequence of visited cells.\n\n \nExample 1:\n\nInput: grid = [[1,1],[3,4]]\nOutput: 8\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.\n\n\nExample 2:\n\nInput: grid = [[1],[2]]\nOutput: 3\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 1000\n\t1 <= m * n <= 105\n\t1 <= grid[i][j] <= 105\n\n", "solution_py": "class Solution:\n def __init__(self):\n self.dp = None\n self.di = [0, 0, -1, 1]\n self.dj = [-1, 1, 0, 0]\n self.mod = 1000000007\n \n def countPaths(self, grid):\n n = len(grid)\n m = len(grid[0])\n self.dp = [[0] * m for _ in range(n)]\n ans = 0\n for i in range(n):\n for j in range(m):\n ans = (ans + self.dfs(grid, i, j, -1)) % self.mod\n return ans\n \n def dfs(self, grid, i, j, prev):\n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= prev:\n return 0\n if self.dp[i][j] != 0:\n return self.dp[i][j]\n self.dp[i][j] = 1\n for k in range(4):\n self.dp[i][j] += self.dfs(grid, i + self.di[k], j + self.dj[k], grid[i][j])\n self.dp[i][j] %= self.mod\n return self.dp[i][j] % self.mod", "solution_js": "var countPaths = function(grid) {\n let mod = Math.pow(10, 9) + 7;\n let result = 0;\n let rows = grid.length, columns = grid[0].length;\n let dp = Array(rows).fill(null).map(_ => Array(columns).fill(0));\n\n const dfs = (r, c, preVal)=> {\n if (r < 0 || r == rows || c < 0 || c == columns || grid[r][c] <= preVal) return 0\n if (dp[r][c]) return dp[r][c]\n return dp[r][c] = (1 + dfs(r + 1, c, grid[r][c]) +\n dfs(r - 1, c, grid[r][c]) +\n dfs(r , c + 1, grid[r][c]) +\n dfs(r , c - 1, grid[r][c])) % mod;\n }\n for(let i = 0; i < rows; i++) {\n for(let j = 0; j < columns; j++) {\n result += dfs(i, j, -1) % mod;\n }\n }\n\n return result % mod;\n};", "solution_java": "class Solution {\n long[][] dp;\n int mod = 1_000_000_007;\n public int countPaths(int[][] grid) {\n dp = new long[grid.length][grid[0].length];\n long sum=0L;\n for(int i=0;i=grid.length||j>=grid[0].length) return 0;\n if(grid[i][j]<=pre) return 0;\n if(dp[i][j]>0) return dp[i][j];\n long a = dfs(grid,i+1,j,grid[i][j]);\n long b = dfs(grid,i,j+1,grid[i][j]);\n long c = dfs(grid,i-1,j,grid[i][j]);\n long d = dfs(grid,i,j-1,grid[i][j]);\n dp[i][j] = (1+a+b+c+d)%mod;\n return dp[i][j];\n }\n}", "solution_c": "class Solution {\npublic:\n int mod = 1000000007;\n int dx[4] = {1,0,-1,0};\n int dy[4] = {0,1,0,-1};\n int countPaths(vector>& grid) {\n vector > dp(grid.size(),vector(grid[0].size(),-1));\n long long count = 0;\n for(int i = 0; i>&grid){\n if(x<0 or x>=grid.size() or y<0 or y>=grid[0].size()) return false;\n return true;\n }\n int dfs(int x, int y, vector >&grid,vector >&dp){\n if(dp[x][y]!=-1) return dp[x][y];\n\n int ans = 1;\n for(int i = 0; i<4; i++){\n if(isvalid(x+dx[i],y+dy[i],grid) and grid[x][y]>grid[x+dx[i]][y+dy[i]]){\n ans = (ans%mod+dfs(x+dx[i],y+dy[i],grid,dp)%mod)%mod;\n }\n }\n return dp[x][y] = ans%mod;\n }\n};" }, { "title": "Number of Subsequences That Satisfy the Given Sum Condition", "algo_input": "You are given an array of integers nums and an integer target.\n\nReturn the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: nums = [3,5,6,7], target = 9\nOutput: 4\nExplanation: There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)\n\n\nExample 2:\n\nInput: nums = [3,3,6,8], target = 10\nOutput: 6\nExplanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]\n\n\nExample 3:\n\nInput: nums = [2,3,3,4,6,7], target = 12\nOutput: 61\nExplanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 106\n\t1 <= target <= 106\n\n", "solution_py": "class Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n count = 0\n mod = 10 ** 9 + 7\n \n while left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n else:\n count += pow(2, right - left, mod)\n left += 1\n \n return count % mod", "solution_js": "const MOD = 1000000007;\n\nvar numSubseq = function(nums, target) {\n nums.sort((a, b) => a - b);\n const len = nums.length;\n const pow = new Array(len).fill(1);\n for(let i = 1; i < len; i++) {\n pow[i] = (pow[i - 1] * 2) % MOD;\n }\n let l = 0, r = len - 1, ans = 0;\n while(l <= r) {\n if(nums[l] + nums[r] > target) {\n r--; continue;\n } else {\n ans = (ans + pow[r - l]) % MOD;\n l++;\n }\n }\n return ans % MOD;\n};", "solution_java": "class Solution {\n public int numSubseq(int[] nums, int target) {\n int n = nums.length;\n int i =0, j = n-1;\n int mod = (int)1e9+7;\n Arrays.sort(nums);\n int[] pow = new int[n];\n pow[0]=1;\n int count =0;\n for(int z =1;z target)\n j--;\n }\n return count;\n }\n}", "solution_c": "class Solution {\nprivate:\n int mod=1e9+7;\n int multiply(int a,int b){\n if(b==0){\n return 0;\n } else if(b%2==0){\n int ans=multiply(a,b/2);\n return (ans%mod+ans%mod)%mod;\n } else {\n int ans=multiply(a,b-1);\n return (a%mod+ans%mod)%mod;\n }\n }\n int power(int b,int e){\n if(e==0){\n return 1;\n } else if(e%2==0){\n int ans=power(b,e/2);\n return multiply(ans,ans);\n } else {\n int ans=power(b,e-1);\n return multiply(b,ans);\n }\n }\npublic:\n int numSubseq(vector& nums, int target) {\n sort(nums.begin(),nums.end());\n int start=0,end=0;\n while(end int:\n stack = []\n\n for parenthese in s:\n if parenthese == \"(\":\n stack.append(\"(\")\n\n else:\n if not stack or stack[-1] == \")\":\n stack.append(\")\")\n\n if stack and stack[-1] == \"(\":\n stack.pop()\n\n return len(stack)", "solution_js": "var minAddToMakeValid = function(s) {\n let stack = []\n let count = 0\n for(let i=0;i sta;\n int nums = 0;\n for (int i = 0; i < s.size(); i++)\n {\n if (s[i] == '(')\n {\n sta.push(s[i]);\n }\n else\n {\n if (!sta.empty())\n {\n sta.pop();\n }\n else\n {\n nums++;\n }\n }\n }\n nums += sta.size();\n return nums;\n }\n};" }, { "title": "Increasing Triplet Subsequence", "algo_input": "Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: Any triplet where i < j < k is valid.\n\n\nExample 2:\n\nInput: nums = [5,4,3,2,1]\nOutput: false\nExplanation: No triplet exists.\n\n\nExample 3:\n\nInput: nums = [2,1,5,0,4,6]\nOutput: true\nExplanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5 * 105\n\t-231 <= nums[i] <= 231 - 1\n\n\n \nFollow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?", "solution_py": "class Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n first = second = float('inf')\n for n in nums:\n if n <= first:\n first = n\n elif n <= second:\n second = n\n else:\n return True\n return False", "solution_js": "var increasingTriplet = function(nums) {\n const length = nums.length, arr = [];\n let tripletFound = false, arrLength, added = false, found = false;\n if(length < 3) return false;\n arr.push([nums[0],1]);\n for(let index = 1; index < length; index++) {\n let count = 1;\n added = false;\n found = false;\n arrLength = arr.length;\n for(let index2 = 0; index2 < arrLength; index2++) {\n if(arr[index2][0] < nums[index]) {\n added = true;\n if(count !== arr[index2][1]+1) {\n count = arr[index2][1]+1;\n if(JSON.stringify(arr[index2+1]) !== JSON.stringify([nums[index],count]))\n arr.push([nums[index],count]);\n }\n if(arr[index2][1]+1 === 3) {\n tripletFound = true;\n break;\n }\n }\n if(arr[index2][0] === nums[index]) found = true;\n }\n if(tripletFound) break;\n if(!added && !found) {\n arr.push([nums[index],1]);\n }\n }\n return tripletFound;\n};", "solution_java": "class Solution {\n public boolean increasingTriplet(int[] nums) {\n if(nums.length < 3)\n return false;\n \n int x = Integer.MAX_VALUE;\n int y = Integer.MAX_VALUE;\n \n for (int i : nums){\n if(i <= x){\n x = i;\n }else if (i <= y)\n y = i;\n else \n return true;\n }\n \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool increasingTriplet(vector& nums) {\n int n = nums.size();\n int smallest = INT_MAX;\n int second_smallest = INT_MAX;\n for(int i = 0;i None:\n \"\"\"\n Do not return anything, modify arr in-place instead.\n \"\"\"\n l = len(arr)\n i,c=0,0\n while i=i+1; j--) {\n arr[j+1] = arr[j]; // Shift each element by one space\n }\n arr[j+1] = 0; // Duplicating the zero on the consecutive index of i\n i++; // Skipping the duplicated zero index in the array \n }\n }\n } \n}", "solution_c": "class Solution {\npublic:\n void duplicateZeros(vector& arr) {\n for(int i=0;i bool:\n\t\t# defining dictionary\n occ = dict()\n \n\t\t# adding elements with their counts in dictionary\n for element in arr:\n if element not in occ:\n occ[element] = 0\n else:\n occ[element] += 1\n \n\t\t# list of count of elements\n values = list(occ.values())\n\t\t# Unique count\n unique = set(values)\n \n if len(values) == len(unique):\n return True\n else:\n return False", "solution_js": "var uniqueOccurrences = function(arr) {\n const obj = {};\n// Creating hashmap to store count of each number\n arr.forEach(val => obj[val] = (obj[val] || 0) + 1);\n// Creating an array of the count times\n const val = Object.values(obj).sort((a, b) => a-b);\n// Now, just finding the duplicates\n for(let i = 0; i set = new HashSet<>();\n\n int c = 1;\n for(int i = 1; i < arr.length; i++)\n {\n if(arr[i] == arr[i-1]) c++;\n\n else\n {\n if(set.contains(c)) return false;\n\n set.add(c);\n\n c = 1;\n }\n }\n\n if(set.contains(c)) return false;\n\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool uniqueOccurrences(vector& arr) {\n unordered_mapsk;\n unordered_mapskk;\n for(int i=0;i List[int]:\n\t\tg = defaultdict(list)\n\t\tfor u,v in paths:\n\t\t\tg[u-1].append(v-1) \n\t\t\tg[v-1].append(u-1) \n\t\tans = [0]*n\n\t\tfor i in range(n):\n\t\t\tc = [1,2,3,4]\n\t\t\tfor j in g[i]:\n\t\t\t\tif ans[j] in c: c.remove(ans[j])\n\t\t\tans[i] = c.pop()\n\t\treturn ans", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} paths\n * @return {number[]}\n */\nvar gardenNoAdj = function(n, paths) {\n //if n is less than or equal to four just return an array of size n from 1 to n\n if(n <= 4){\n let arr = []\n let count = 1\n while(arr.length < n){\n arr.push(count)\n count++\n }\n return arr\n }\n //if there are no gardens connecting to each other then just return an array of size n with ones\n if(paths.length === 0)return new Array(n).fill(1)\n\n //because we have three possible paths connecting to gardens and 4 flowers we know that this problems is possible because our graph is of degree 3 and we have D + 1 flowers\n //to solve\n let adjList = {}\n // create an array filled with ones so if there is a garden with no path just fill with one\n let result = new Array(n).fill(1)\n let garden = new Set([1,2,3,4])\n\n //create adj list from the paths\n paths.forEach(path => {\n let first = path[0];\n let second = path[1];\n\n if(first in adjList )adjList[first].neighbors.add(second)\n else {adjList[first] = new Fnode(second)}\n\n if(second in adjList)adjList[second].neighbors.add(first)\n else {adjList[second] = new Fnode(first)}\n\n })\n\n for(let node in adjList){\n //every node\n let current = adjList[node]\n\n //create a set of invalid flowers, flowers you can't use because they are part of\n //the other gardens this one is connected to.\n let invalidFlower = new Set();\n\n //iterate over the neighbors to find what type of flower they have and if it is not\n //null included in the invalid flowers set\n current.neighbors.forEach(neighbor => {\n if(adjList[neighbor]['flower'] !== null){\n invalidFlower.add(adjList[neighbor]['flower'])\n }\n })\n\n //create our possible value or better said our value because we will use the first one\n //we obtain.\n let possibleFlower;\n\n //we iterate over over our garden {1,2,3,4}\n for(let flower of garden) {\n //and if our flower is not part of the invalid flowers;\n if(!invalidFlower.has(flower)){\n //we have found a possible flower we can use\n possibleFlower = flower\n //we break because this is the only one we need\n break;\n }\n }\n // we add our flower to current so that we dont use it in the future\n current.flower = possibleFlower\n\n //and update our result\n result[node - 1] = possibleFlower\n }\n //we return our result\n return result\n\n};\n\n//create a Flower class just for simplicity\nclass Fnode{\n constructor(neighbor){\n this.flower = null\n this.neighbors = new Set([neighbor])\n }\n}", "solution_java": "class Solution {\n public int[] gardenNoAdj(int n, int[][] paths) {\n boolean[][] graph = new boolean[n][n];\n for(int i = 0;i a[],vector &col,int sv,int i)\n {\n for(auto it:a[sv])\n {\n if(col[it]==i)return 0;\n }\n return 1;\n }\n \n void dfs(vector a[],vector &col,int sv,int lc)\n {\n for(int i = 1;i<5;i++)\n {\n if(check(a,col,sv,i))\n {\n col[sv] = i;\n break;\n }\n }\n for(auto it:a[sv])\n {\n if(col[it]==-1)\n {\n dfs(a,col,it,col[sv]);\n }\n }\n }\n vector gardenNoAdj(int n, vector>& paths) {\n vector a[n];\n for(auto it:paths)\n {\n a[it[0]-1].push_back(it[1]-1);\n a[it[1]-1].push_back(it[0]-1);\n }\n \n vector col(n,-1);\n for(int i = 0;i int:\n\n count = 0\n amount = sorted(amount, reverse=True)\n while amount[0] > 0:\n amount[0] -= 1\n amount[1] -= 1\n count += 1\n amount = sorted(amount, reverse=True)\n return count", "solution_js": "var fillCups = function(amount) {\n var count = 0\n var a = amount\n while (eval(a.join(\"+\")) > 0) {\n var max = Math.max(...a)\n a.splice(a.indexOf(max), 1)\n var max2 = Math.max(...a)\n a.splice(a.indexOf(max2), 1)\n count++\n if(max == 0) a.push(0)\n else a.push(max - 1)\n if (max2==0) a.push(0)\n else a.push(max2 - 1)\n } return count\n}", "solution_java": "class Solution {\n public int fillCups(int[] amount) {\n Arrays.sort(amount);\n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z){return sum/2 +sum%2;}\n if(x==0&&y==0){return z;}\n else{return z;}\n }\n}", "solution_c": "class Solution {\npublic:\n int fillCups(vector& amount) {\n sort(amount.begin(),amount.end());\n int x=amount[0];\n int y=amount[1];\n int z=amount[2];\n int sum=x+y+z;\n if(x+y>z) return sum/2+sum%2;\n if(x==0 && y==0) return z;\n else return z;\n }\n};" }, { "title": "Grumpy Bookstore Owner", "algo_input": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.\n\nOn some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.\n\nWhen the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.\n\nThe bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.\n\nReturn the maximum number of customers that can be satisfied throughout the day.\n\n \nExample 1:\n\nInput: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput: 16\nExplanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.\n\n\nExample 2:\n\nInput: customers = [1], grumpy = [0], minutes = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\tn == customers.length == grumpy.length\n\t1 <= minutes <= n <= 2 * 104\n\t0 <= customers[i] <= 1000\n\tgrumpy[i] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def recursion(self,index,used):\n # base case\n if index == self.n: return 0\n \n #check in dp\n if (index,used) in self.dp: return self.dp[(index,used)]\n #choice1 is using the secret technique\n choice1 = -float('inf')\n \n # we can only use secret technique once and consecutively\n if used == True :\n # use the secret technique\n end = index + self.minutes if index + self.minutes < self.n else self.n\n to_substract = self.prefix_sum[index - 1] if index != 0 else 0\n val = self.prefix_sum[end - 1] - to_substract\n choice1 = self.recursion(end,False) + val\n \n # Do not use the secret tehcnique and play simple \n choice2 = self.recursion(index+1,used) + (self.customers[index] if self.grumpy[index] == 0 else 0)\n ans = choice1 if choice1 > choice2 else choice2\n \n # Memoization is done here\n self.dp[(index,used)] = ans\n return ans\n \n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n self.n = len(customers)\n self.customers = customers\n self.grumpy = grumpy\n self.minutes = minutes\n self.dp = {}\n self.prefix_sum = [x for x in customers]\n for i in range(1,self.n): self.prefix_sum[i] += self.prefix_sum[i-1]\n return self.recursion(0,True)\n ", "solution_js": "var maxSatisfied = function(customers, grumpy, minutes) {\n let left=0;\n let maxUnsatisfied=0;\n let curr=0;\n let satisfied=0;\n \n\t// finding the satisfied customers\n for(let i=0;iminutes){\n if(grumpy[left])curr-=customers[left]\n left++\n } \n if(i-left+1===minutes){\n if(curr>max){\n maxUnsatisfied=curr\n }\n }\n }\n\t\n return satisfied + maxUnsatisfied;\n};", "solution_java": "class Solution {\n public int maxSatisfied(int[] customers, int[] grumpy, int minutes) {\n int start = -1;\n int count = 0;\n \n int max = 0;\n int curr = 0;\n \n for (int i = 0; i < customers.length; i++) {\n if (grumpy[i] == 0) {\n count += customers[i];\n } else {\n curr += customers[i];\n }\n \n if (i-start > minutes) {\n start++;\n if (grumpy[start] == 1) {\n curr -= customers[start];\n }\n }\n max = Math.max(max, curr);\n }\n \n return count + max;\n }\n}", "solution_c": "/*\n https://leetcode.com/problems/grumpy-bookstore-owner/\n \n TC: O(N)\n SC: O(1)\n \n Looking at the problem, main thing to find is the window where the minutes should\n be used so that the owner is not grumpy and max customers in that window can be satisifed.\n \n Find the window with most no. of satisfied customers given the owner was originally grumpy but\n now has become not grumpy.\n Since the owner can only be not grumpy for minutes duration, this sets our window size as well.\n So with 'minutes' window size, find the max window.\n \n Then add the max window value with the normal satisfied customers.\n*/\nclass Solution {\npublic:\n int maxSatisfied(vector& customers, vector& grumpy, int minutes) {\n // Tracks the max window where being not grumpy will add most customers and current grumpy window customers\n int max_grumpy_window = 0, grumpy_window = 0;\n int curr = 0, n = customers.size();\n // Total satisifed customers when owner is not grumpy\n int satisfied_cx = 0;\n // net effective duration of not being grumpy\n minutes = min(minutes, n);\n \n // process the 1st window\n while(curr < minutes) {\n satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);\n grumpy_window += (grumpy[curr] ? customers[curr] : 0);\n ++curr;\n }\n \n max_grumpy_window = max(max_grumpy_window, grumpy_window);\n // process the remaining windows\n while(curr < n) {\n // Remove the 1st element of last window\n grumpy_window -= (grumpy[curr - minutes] ? customers[curr - minutes] : 0);\n // Add the latest element of current window\n grumpy_window += (grumpy[curr] ? customers[curr] : 0);\n max_grumpy_window = max(max_grumpy_window, grumpy_window);\n \n satisfied_cx += (!grumpy[curr] ? customers[curr] : 0);\n ++curr;\n }\n \n return satisfied_cx + max_grumpy_window;\n }\n};" }, { "title": "Number of 1 Bits", "algo_input": "Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n\nNote:\n\n\n\tNote that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\n\tIn Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.\n\n\n \nExample 1:\n\nInput: n = 00000000000000000000000000001011\nOutput: 3\nExplanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.\n\n\nExample 2:\n\nInput: n = 00000000000000000000000010000000\nOutput: 1\nExplanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.\n\n\nExample 3:\n\nInput: n = 11111111111111111111111111111101\nOutput: 31\nExplanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.\n\n\n \nConstraints:\n\n\n\tThe input must be a binary string of length 32.\n\n\n \nFollow up: If this function is called many times, how would you optimize it?", "solution_py": "class Solution:\n def hammingWeight(self, n: int) -> int:\n i = 0\n while n > 0:\n if n % 2 != 0: i += 1\n n = n >> 1\n return i", "solution_js": "var hammingWeight = function(n) {\n let count = 0, i = 0;\n while(n > 0) {\n i = 0;\n while(n >= Math.pow(2,i)) {\n i++;\n }\n count++;\n n -= Math.pow(2,i-1);\n }\n return count;\n};", "solution_java": "public class Solution {\n // you need to treat n as an unsigned value\n public int hammingWeight(int n) {\n return Integer.bitCount(n);\n }\n}", "solution_c": "class Solution {\npublic:\n int hammingWeight(uint32_t n) {\n int ans=0;\n while(n!=0){\n n=n&(n-1);\n ans++;\n }\n return ans; \n }\n};" }, { "title": "Sort Colors", "algo_input": "Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n\nWe will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.\n\nYou must solve this problem without using the library's sort function.\n\n \nExample 1:\n\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\n\nExample 2:\n\nInput: nums = [2,0,1]\nOutput: [0,1,2]\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 300\n\tnums[i] is either 0, 1, or 2.\n\n\n \nFollow up: Could you come up with a one-pass algorithm using only constant extra space?\n", "solution_py": "class Solution:\n def sortColors(self, nums: List[int]) -> None:\n\n red, white, blue = 0, 0, len(nums) - 1\n\n while white <= blue:\n if nums[white] == 0:\n nums[white], nums[red] = nums[red], nums[white]\n red += 1\n white += 1\n elif nums[white] == 1:\n white += 1\n else:\n nums[white], nums[blue] = nums[blue], nums[white]\n blue -= 1", "solution_js": "var sortColors = function(nums) {\n let map = {\n '0': 0,\n '1': 0,\n '2': 0\n };\n for(let char of nums) {\n map[char] = map[char] + 1;\n }\n let values = Object.values(map);\n let curr = 0;\n for(let k=0; k& nums) {\n int a =0; int b=0,c=0;int i;\n for(i=0;i str:\n idx=word.find(ch)\n if idx:\n return word[:idx+1][::-1]+ word[idx+1:]\n return word", "solution_js": "var reversePrefix = function(word, ch) {\n return word.indexOf(ch) !== -1 ? word.split(\"\").slice(0, word.indexOf(ch) + 1).reverse().join(\"\") + word.slice(word.indexOf(ch) + 1) : word;\n};", "solution_java": "class Solution {\n public String reversePrefix(String word, char ch) {\n char[] c = word.toCharArray();\n int locate = 0;\n for (int i = 0; i < word.length(); i++) { //first occurrence of ch\n if (ch == c[i]) {\n locate = i;\n break;\n }\n }\n char[] res = new char[word.length()];\n for (int i = 0; i <= locate; i++) {\n res[i] = c[locate - i];\n }\n for (int i = locate + 1; i < word.length(); i++) {\n res[i] = c[i];\n }\n return String.valueOf(res);\n }\n}", "solution_c": "class Solution {\npublic:\n string reversePrefix(string word, char ch) {\n string ans = \"\";\n int tr = true;\n for(auto w : word){\n ans.push_back(w);\n if(tr && w == ch){\n tr=false;\n reverse(ans.begin(), ans.end());\n }\n }\n return ans;\n }\n};" }, { "title": "Minimum Score Triangulation of Polygon", "algo_input": "You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).\n\nYou will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.\n\nReturn the smallest possible total score that you can achieve with some triangulation of the polygon.\n\n \nExample 1:\n\nInput: values = [1,2,3]\nOutput: 6\nExplanation: The polygon is already triangulated, and the score of the only triangle is 6.\n\n\nExample 2:\n\nInput: values = [3,7,4,5]\nOutput: 144\nExplanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\nThe minimum score is 144.\n\n\nExample 3:\n\nInput: values = [1,3,1,4,1,5]\nOutput: 13\nExplanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.\n\n\n \nConstraints:\n\n\n\tn == values.length\n\t3 <= n <= 50\n\t1 <= values[i] <= 100\n\n", "solution_py": "class Solution:\n def minScoreTriangulation(self, values: List[int]) -> int:\n \n n = len(values)\n \n c = [[0 for _ in range(n)] for _ in range(n)]\n \n for L in range(2, n):\n \n for i in range(1, n-L+1):\n \n j = i + L - 1\n \n c[i][j] = float('inf')\n \n for k in range(i, j):\n \n q = c[i][k] + c[k+1][j] + (values[i-1]*values[k]*values[j])\n \n if c[i][j] > q:\n c[i][j] = q\n \n return c[1][n-1]\n \n \n \n \n ", "solution_js": "var minScoreTriangulation = function(values) {\n let dp = Array(values.length).fill().map((i) => Array(values.length).fill(0));\n function dfs(i, j) {\n if (dp[i][j]) return dp[i][j];\n if (j - i < 2) return 0;\n let min = Infinity;\n // k forms a triangle with i and j, thus bisecting the array into two parts\n // These two parts become two subproblems that can be solved recursively\n for (let k = i + 1; k < j; k++) {\n let sum = values[i] * values[j] * values[k] + dfs(i, k) + dfs(k, j);\n min = Math.min(min, sum);\n }\n return dp[i][j] = min;\n }\n return dfs(0, values.length - 1);\n};", "solution_java": "class Solution {\n int solve(int[] v, int i, int j){\n if(i+1==j)\n return 0;\n int ans= Integer.MAX_VALUE;\n for(int k=i+1;k=0;i--){\n for(int j=i+2;j& values,vector> &dp){\n\t\tif(i == j || i+1 == j) return 0;\n\t\tif(dp[i][j] != -1) return dp[i][j];\n\t\tint res = INT_MAX;\n\t\tfor(int k = i+1;k < j;k++)\n\t\t{\n\t\t\tint temp = values[i]*values[j]*values[k] + f(k,j,values,dp) + f(i,k,values,dp);\n\t\t\tres = min(res,temp);\n\t\t}\n\t\treturn dp[i][j] = res;\n\t}\n\n\tint minScoreTriangulation(vector& values) {\n\t\tint n = values.size();\n\t\tvector> dp(n+1,vector(n+1,-1));\n\t\treturn f(0,n - 1,values,dp);\n\t}" }, { "title": "Smallest Integer Divisible by K", "algo_input": "Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.\n\nReturn the length of n. If there is no such n, return -1.\n\nNote: n may not fit in a 64-bit signed integer.\n\n \nExample 1:\n\nInput: k = 1\nOutput: 1\nExplanation: The smallest answer is n = 1, which has length 1.\n\n\nExample 2:\n\nInput: k = 2\nOutput: -1\nExplanation: There is no such positive integer n divisible by 2.\n\n\nExample 3:\n\nInput: k = 3\nOutput: 3\nExplanation: The smallest answer is n = 111, which has length 3.\n\n\n \nConstraints:\n\n\n\t1 <= k <= 105\n\n", "solution_py": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n if k % 2 == 0: return -1\n n = 1\n leng = 1\n mapp = {}\n while True:\n rem = n % k\n if rem == 0: return leng\n if rem in mapp : return -1\n mapp[rem] = True\n n = n*10 + 1\n leng += 1\n ", "solution_js": "/**\n * @param {number} k\n * @return {number}\n */\nvar smallestRepunitDivByK = function(k) {\n if( 1 > k > 1e6 ) return -1;\n let val = 0;\n for (let i = 1; i < 1e6; i++) {\n val = (val * 10 + 1) % k;\n if (val === 0) return i;\n }\n return -1;\n};", "solution_java": "class Solution {\n public int smallestRepunitDivByK(int k) {\n // if (k % 2 == 0 || k % 5 == 0) return -1; // this trick may save a little time\n boolean[] hit = new boolean[k];\n int n = 0, ans = 0;\n while (true) { // at most k times, because 0 <= remainder < k\n ++ ans;\n n = (n * 10 + 1) % k; // we only focus on whether to divide, so we only need to keep the remainder.\n if (n == 0) return ans; // can be divisible\n if (hit[n]) return -1; // the remainder of the division repeats, so it starts to loop that means it cannot be divisible.\n hit[n] = true;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int smallestRepunitDivByK(int k) {\n if(k&1==0)return -1;\n long long val=0;\n\n for(int i=1; i<=k;i++)\n {\n // val=((val*10)+1);\n if((val=(val*10+1)%k)==0)return i;\n }\n return -1;\n \n \n \n }\n};" }, { "title": "Kth Smallest Element in a BST", "algo_input": "Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.\n\n \nExample 1:\n\nInput: root = [3,1,4,null,2], k = 1\nOutput: 1\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,null,1], k = 3\nOutput: 3\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t1 <= k <= n <= 104\n\t0 <= Node.val <= 104\n\n\n \nFollow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?\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 kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n n=0\n stack=[] # to store the elements\n cur=root # pointer to iterate\n while cur or stack:\n while cur: # used to find the left most element\n stack.append(cur)\n cur=cur.left\n cur=stack.pop() # pop the most recent element which will be the least value at that moment\n n+=1\n if n==k:\n return cur.val\n cur=cur.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 * @param {number} k\n * @return {number}\n */\nvar kthSmallest = function(root, k) {\n let stack = [];\n while(root != null || stack.length > 0) {\n while(root != null){\n stack.push(root);\n root = root.left\n }\n root = stack.pop();\n if(--k == 0) break;\n root = root.right;\n };\n\n return root.val;\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 int element,count;\n \n public int kthSmallest(TreeNode root, int k) {\n inorderTraversal(root,k);\n return element;\n }\n \n \n public void inorderTraversal(TreeNode root,int k){\n if(root.left != null){\n inorderTraversal(root.left,k);\n }\n count++;\n if(count==k){\n element = root.val;\n }\n \n if(root.right != null){\n inorderTraversal(root.right,k);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void findInorder(TreeNode* root, vector &ans) {\n if(root == NULL)\n return;\n\n findInorder(root->left, ans);\n ans.push_back(root->val);\n findInorder(root->right, ans);\n }\n int kthSmallest(TreeNode* root, int k) {\n vector ans;\n findInorder(root, ans);\n return ans[k-1];\n }\n};" }, { "title": "Find the Smallest Divisor Given a Threshold", "algo_input": "Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.\n\nEach result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).\n\nThe test cases are generated so that there will be an answer.\n\n \nExample 1:\n\nInput: nums = [1,2,5,9], threshold = 6\nOutput: 5\nExplanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). \n\n\nExample 2:\n\nInput: nums = [44,22,33,11,1], threshold = 5\nOutput: 44\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5 * 104\n\t1 <= nums[i] <= 106\n\tnums.length <= threshold <= 106\n\n", "solution_py": "class Solution:\n def helper(self,nums,m):\n Sum = 0\n for n in nums:\n Sum += math.ceil(n/m)\n return Sum\n \n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n l,r = 1, max(nums)\n while l < r:\n mid = (l+r)//2\n Sum = self.helper(nums,mid)\n if Sum > threshold:\n l = mid + 1\n else:\n r = mid \n return r", "solution_js": "var smallestDivisor = function(nums, threshold) {\n let left = 1;\n let right = nums.reduce((r, x) => Math.max(r, x), 0);\n \n while (left <= right) {\n const div = Math.floor((left + right) / 2);\n const sum = nums.reduce((r, x) => r + Math.ceil(x / div), 0);\n \n if (sum <= threshold) {\n right = div - 1;\n } else {\n left = div + 1;\n }\n }\n \n return left;\n};", "solution_java": "class Solution {\n public int smallestDivisor(int[] a, int h) {\n int l = 1, r = a[0];\n for (int x : a) if (x > r) r = x;\n\n while (l < r) {\n int m = l + (r-l)/2;\n if (valid(a, m, h)) r = m;\n else l = m + 1;\n }\n\n return l;\n }\n\n private boolean valid(int[] a, int m, int h) {\n for (int x : a)\n if ((h -= (x + m-1)/m) < 0) return false;\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n int smallestDivisor(vector& nums, int threshold) {\n int l=1,r=0;\n for(int n:nums)r=max(r,n);\n\n int mid,s=0;\n while(l a.length - b.length);\n\n const buildTrie = (root, word, index) => {\n // This means we reached to the end of word, so mark it as a word and compute encoding length\n if (index < 0) {\n minEncodingLength += word.length + 1;\n root.isWord = true;\n return;\n }\n\n const character = word[index];\n // If we do not have a char in children, create a node and add it under root\n if (!root.children.has(character)) {\n const node = new Trie(character);\n root.children.set(character, node);\n buildTrie(node, word, index - 1);\n return;\n }\n\n const node = root.children.get(character);\n // Remove the common suffix length considered before since it would be covered as a part of current word traversal\n if (node.isWord) {\n node.isWord = false;\n minEncodingLength -= word.length - index + 1;\n }\n\n buildTrie(node, word, index - 1);\n };\n\n const root = new Trie();\n for (const word of sortedWords) {\n buildTrie(root, word, word.length - 1);\n }\n\n return minEncodingLength;\n};", "solution_java": "class Node {\n private boolean flag;\n private Node[] children;\n\n public Node () {\n flag = false;\n children = new Node[26];\n Arrays.fill (children, null);\n }\n\n public boolean getFlag () {\n return flag;\n }\n\n public Node getChild (int index) {\n return children[index];\n }\n\n public boolean hasChild (int index) {\n return children[index] != null;\n }\n\n public void setFlag (boolean flag) {\n this.flag = flag;\n }\n\n public void makeChild (int index) {\n children[index] = new Node();\n }\n}\n\nclass Trie {\n private Node root;\n\n public Trie () {\n root = new Node();\n }\n\n public int addWord (String word) {\n\n boolean flag = true;\n Node node = root;\n int count = 0;\n\n for (int i = word.length () - 1; i >= 0; --i) {\n int index = (int) word.charAt(i) - 97;\n\n if (!node.hasChild (index)) {\n flag = false;\n node.makeChild (index);\n }\n\n node = node.getChild (index);\n if (node.getFlag()) {\n node.setFlag (false);\n count -= word.length() - i + 1;\n\n if (i == 0)\n flag = false;\n }\n }\n\n if (!flag)\n node.setFlag (true);\n\n return flag? count: count + 1 + word.length();\n }\n}\n\nclass Solution {\n public int minimumLengthEncoding(String[] words) {\n Trie trie = new Trie ();\n int size = 0;\n\n for (String word: words) {\n size += trie.addWord (word);\n }\n\n return size;\n }\n}", "solution_c": "class TrieNode{\npublic:\n bool isEnd;\n vector children;\n TrieNode(){\n isEnd = false;\n children = vector(26, NULL);\n }\n};\n\nclass Trie{\npublic:\n TrieNode* root;\n Trie(){\n root = new TrieNode();\n }\n \n void insert(string& word, bool& isSuffix){\n auto cur = root;\n for(int i=0; ichildren[index] == NULL){\n isSuffix = false;\n cur->children[index] = new TrieNode();\n }\n cur = cur->children[index];\n }\n cur -> isEnd= true;\n }\n};\n\nclass Solution {\npublic:\n int minimumLengthEncoding(vector& words) {\n sort(words.begin(), words.end(), [](string& a, string& b){\n return a.size() > b.size();\n });\n \n int res = 0;\n Trie* trie = new Trie();\n\n\t\tfor(auto word: words){\n reverse(word.begin(), word.end());\n bool wordIsSuffix = true;\n trie->insert(word, wordIsSuffix);\n // If word is not suffix of some other word, it needs to be added separately\n if(!wordIsSuffix) res += word.size()+1; //+1 for '#'\n }\n return res;\n }\n};" }, { "title": "Leaf-Similar Trees", "algo_input": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.\n\n\n\nFor example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).\n\nTwo binary trees are considered leaf-similar if their leaf value sequence is the same.\n\nReturn true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.\n\n \nExample 1:\n\nInput: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput: true\n\n\nExample 2:\n\nInput: root1 = [1,2,3], root2 = [1,3,2]\nOutput: false\n\n\n \nConstraints:\n\n\n\tThe number of nodes in each tree will be in the range [1, 200].\n\tBoth of the given trees will have values in the range [0, 200].\n\n", "solution_py": "# 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 leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n tree=[]\n def inorder(root):\n nonlocal tree\n if root is None:\n return\n if root.left is None and root.right is None:\n tree.append(root.val)\n \n inorder(root.left)\n inorder(root.right)\n \n inorder(root1)\n inorder(root2)\n tree1=tree[:len(tree)//2]\n tree2=tree[len(tree)//2:]\n if tree1==tree2:\n return True\n else:\n return False", "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} root1\n * @param {TreeNode} root2\n * @return {boolean}\n */\n \nvar leafSimilar = function(root1, root2) {\n let array1 = [], array2 = [];\n let leaf1 = getLeaf(root1, array1),\n leaf2 = getLeaf(root2, array2);\n \n if (leaf1.length !== leaf2.length){ // if different lengths, return false right away\n return false;\n } \n \n for(let i = 0; i < leaf1.length; i++){\n if (leaf1[i] !== leaf2[i]){ // compare pair by pair\n return false;\n }\n }\n\t\n return true;\n};\n\nvar getLeaf = function(root, array){ // DFS\n if (!root){\n return;\n }\n if (!(root.left || root.right)){\n array.push(root.val); // push leaf value to the array\n }\n getLeaf(root.left, array);\n getLeaf(root.right, array);\n \n return array;\n}", "solution_java": "class Solution {\n public boolean leafSimilar(TreeNode root1, TreeNode root2) {\n List list1 = new ArrayList<>();\n checkLeaf(root1, list1);\n List list2 = new ArrayList<>();\n checkLeaf(root2, list2);\n\n if(list1.size() != list2.size()) return false;\n\n int i = 0;\n while(i < list1.size()){\n if(list1.get(i) != list2.get(i)){\n return false;\n }\n i++;\n }\n return true;\n }\n\n private void checkLeaf(TreeNode node, List arr){\n if(node.left == null && node.right == null) arr.add(node.val);\n if(node.left != null) checkLeaf(node.left, arr);\n if(node.right != null) checkLeaf(node.right, arr);\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 \n /* How to get LeafOrder?\n Simply traverse the tree Left->right\n whenever you get a leaf, push its value to a vector\n */\n \n \n void getLeafOrder(TreeNode* root, vector &leafOrder){ // Here we are passing vector\n if(root == NULL){ // by reference to make changes\n return; // directly in main vector\n }\n \n // Leaf found -> push its value in the vector\n if(root->left == NULL and root->right == NULL){\n leafOrder.push_back(root->val);\n return;\n }\n \n getLeafOrder(root->left, leafOrder); // Left then Right -> to maintain the sequence\n getLeafOrder(root->right, leafOrder);\n }\n \n \n bool leafSimilar(TreeNode* root1, TreeNode* root2) {\n vector leafOrder1;\n vector leafOrder2;\n \n getLeafOrder(root1, leafOrder1); // Get leaf order for both trees\n getLeafOrder(root2, leafOrder2);\n \n return leafOrder1 == leafOrder2; // return if they are equal or not\n }\n};" }, { "title": "Increasing Order Search Tree", "algo_input": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.\n\n \nExample 1:\n\nInput: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n\n\nExample 2:\n\nInput: root = [5,1,7]\nOutput: [1,null,5,null,7]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the given tree will be in the range [1, 100].\n\t0 <= Node.val <= 1000\n\n", "solution_py": "class Solution(object):\n \n def increasingBST(self, root):\n \n def sortBST(node):\n if not node: return []\n \n # return the in order BST nodes in list\n return sortBST(node.left) + [node.val] + sortBST(node.right)\n \n # the in order sorted list of the tree nodes\n sorted_list = sortBST(root)\n \n # generate new tree: temp for update, ans for return the root\n ans = temp = TreeNode(sorted_list[0])\n \n # insert nodes to the right side of the new tree\n for i in range(1, len(sorted_list)):\n temp.right = TreeNode(sorted_list[i])\n temp = temp.right\n \n return ans", "solution_js": "var increasingBST = function(root) {\n let newRoot = new TreeNode(-1);\n const newTree = newRoot;\n\n const dfs = (node) => {\n if (!node) return null;\n\n if (node.left) dfs(node.left);\n\n const newNode = new TreeNode(node.val);\n newRoot.right = newNode;\n newRoot.left = null;\n newRoot = newRoot.right;\n\n if (node.right) dfs(node.right);\n }\n dfs(root);\n\n return newTree.right;\n};", "solution_java": "class Solution {\n TreeNode inRoot = new TreeNode();\n TreeNode temp = inRoot;\n public TreeNode increasingBST(TreeNode root) {\n inorder(root);\n return inRoot.right;\n }\n public void inorder(TreeNode root) {\n if(root==null)\n return;\n inorder(root.left);\n temp.right = new TreeNode(root.val);\n temp = temp.right;\n inorder(root.right);\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 TreeNode* temp;\n vectorz;\n TreeNode* increasingBST(TreeNode* root) \n { \n incresing(root); \n sort(z.begin(), z.end());\n temp = new TreeNode(z[0]);\n create(temp, z);\n return temp;\n }\n void incresing(TreeNode* root)\n {\n if(root == NULL) return;\n \n z.push_back(root->val);\n incresing(root->left);\n incresing(root->right); \n }\n void create(TreeNode* create, vector ze)\n {\n \n for(int i = 1; iright = new TreeNode(ze[i]);\n create = create->right;\n } \n }\n};" }, { "title": "Intersection of Two Linked Lists", "algo_input": "Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.\n\nFor example, the following two linked lists begin to intersect at node c1:\n\nThe test cases are generated such that there are no cycles anywhere in the entire linked structure.\n\nNote that the linked lists must retain their original structure after the function returns.\n\nCustom Judge:\n\nThe inputs to the judge are given as follows (your program is not given these inputs):\n\n\n\tintersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.\n\tlistA - The first linked list.\n\tlistB - The second linked list.\n\tskipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.\n\tskipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.\n\n\nThe judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.\n\n \nExample 1:\n\nInput: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput: Intersected at '8'\nExplanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.\n\n\nExample 2:\n\nInput: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput: Intersected at '2'\nExplanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\n\n\nExample 3:\n\nInput: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput: No intersection\nExplanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.\n\n\n \nConstraints:\n\n\n\tThe number of nodes of listA is in the m.\n\tThe number of nodes of listB is in the n.\n\t1 <= m, n <= 3 * 104\n\t1 <= Node.val <= 105\n\t0 <= skipA < m\n\t0 <= skipB < n\n\tintersectVal is 0 if listA and listB do not intersect.\n\tintersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.\n\n\n \nFollow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?", "solution_py": "class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n m = 0\n n = 0\n temp = headA\n while temp != None:\n m+=1\n temp = temp.next\n temp = headB\n while temp != None:\n n+=1\n temp = temp.next\n diff = 0\n if m>=n : \n diff = m-n\n else:\n diff = n-m\n p1 = headA\n p2 = headB\n if max(m,n) == m:\n while diff > 0:\n p1 = p1.next\n diff-=1\n else:\n while diff > 0:\n p2 = p2.next\n diff-=1\n while p1 != None and p2!=None:\n if p1 == p2:\n return p1\n p1 = p1.next\n p2 = p2.next\n return None", "solution_js": "var getIntersectionNode = function(headA, headB) {\n let node1 = headA;\n let node2 = headB;\n\n const set = new Set()\n\n while(node1 !== undefined || node2!== undefined){\n if(node1 && set.has(node1)){\n return node1\n }\n if(node2 && set.has(node2)){\n return node2\n }\n if(node1){\n set.add(node1)\n node1 = node1.next;\n }\n else if(node2){\n set.add(node2)\n node2 = node2.next;\n }\n else {return}\n }\n };", "solution_java": "public class Solution {\n public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n ListNode tempA = headA, tempB = headB;\n int lenA = 0, lenB = 0;\n while (tempA != null) {\n lenA++;\n tempA = tempA.next;\n }\n while (tempB != null) {\n lenB++;\n tempB = tempB.next;\n }\n tempA = headA; tempB = headB;\n if (lenB > lenA) {\n for (int i = 0; i < lenB - lenA; i++) {\n tempB = tempB.next;\n }\n } else if (lenA > lenB) {\n for (int i = 0; i < lenA - lenB; i++) {\n tempA = tempA.next;\n }\n }\n while (tempA != null && tempA != tempB) {\n tempA = tempA.next;\n tempB = tempB.next;\n }\n return tempA;\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n\n //function to get length of linked list\n int getLength(ListNode *head)\n {\n //initial length 0\n int l = 0;\n\n while(head != NULL)\n {\n l++;\n head = head->next;\n }\n return l;\n }\n\n ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {\n\n //ptr1 & ptr2 will move to check nodes are intersecting or not\n //ptr1 will point to the list which have higher length, higher elements (big list)\n //ptr2 will point to small list\n ListNode *ptr1,*ptr2;\n\n //fetching length of both the list,as we want a node that both ptr points simultaneously\n //so if both list have same length of nodes, they travel with same speed, they intersect\n //if diff legths, it'll be difficult for us to catch\n //so by substracting list with higher length with lower length\n //we get same level of length, from which both ptr start travaeling, they may get intersect\n int length1 = getLength(headA);\n int length2 = getLength(headB);\n\n int diff = 0;\n\n //ptr1 points to longer list\n if(length1>length2)\n {\n diff = length1-length2;\n ptr1 = headA;\n ptr2 = headB;\n\n }\n else\n {\n diff = length2 - length1;\n ptr1 = headB;\n ptr2 = headA;\n }\n\n //till diff is zero and we reach our desired posn\n while(diff)\n {\n //incrementing ptr1 so that it can be at a place where both list have same length\n\n ptr1 = ptr1->next;\n\n if(ptr1 == NULL)\n {\n return NULL;\n }\n\n diff--;\n }\n\n //traverse both pointers together, till any of them gets null\n while((ptr1 != NULL) && (ptr2 != NULL))\n {\n //at any point, both point to same node return it\n if(ptr1 == ptr2)\n {\n return ptr1;\n }\n\n //increment both pointers, till they both be NULL\n ptr1 = ptr1->next;\n ptr2 = ptr2->next;\n }\n\n //if not found any intersaction, return null\n return NULL;\n\n }\n};" }, { "title": "Check if Every Row and Column Contains All Numbers", "algo_input": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).\n\nGiven an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.\n\n \nExample 1:\n\nInput: matrix = [[1,2,3],[3,1,2],[2,3,1]]\nOutput: true\nExplanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.\n\n\nExample 2:\n\nInput: matrix = [[1,1,1],[1,2,3],[1,2,3]]\nOutput: false\nExplanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.\n\n\n \nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 <= n <= 100\n\t1 <= matrix[i][j] <= n\n\n", "solution_py": "class Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n lst = [0]*len(matrix)\n for i in matrix:\n if len(set(i)) != len(matrix):\n return False\n for j in range(len(i)):\n lst[j] += i[j]\n return len(set(lst)) == 1", "solution_js": "var checkValid = function(matrix) { \n for(let i =0; i matrix.length) return false;\n cols.add(matrix[j][i])\n }\n\t\t\n if(cols.size < matrix.length || rows.size < matrix.length) return false;\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean checkValid(int[][] matrix) {\n int n = matrix.length;\n int num = (n*(n+1))/2; // SUM of n number 1 to n;\n\n for(int i=0; i hs = new HashSet();\n HashSet hs1 = new HashSet();\n\n int m = num; int k = num;\n\n for(int j = 0; j>& matrix) {\n int n=matrix.size();\n unordered_set s1, s2;\n for(int i=0;i int:\n ans = 1\n data = set()\n\n for roll in rolls:\n data.add(roll)\n\n if len(data) == k:\n ans += 1\n data.clear()\n\n return ans", "solution_js": "var shortestSequence = function(rolls, k)\n{\n let ans=1;\n let sett=new Set();\n\n for(let i of rolls)\n {\n sett.add(i);\n if(sett.size===k)\n {\n ans++;\n sett=new Set();\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int shortestSequence(int[] rolls, int k) {\n int len = 0;\n Set set = new HashSet<>();\n for(int i:rolls)\n {\n set.add(i);\n if(set.size()==k)\n {\n set = new HashSet<>();\n len++;\n }\n }\n return len+1;\n }\n}", "solution_c": "class Solution {\npublic:\n int shortestSequence(vector& rolls, int k) {\n int len = 1;\n set data ;\n \n for (int i = 0; i < rolls.size(); i++) {\n data.insert(rolls[i]);\n \n if (data.size() == k) {\n len++;\n data = set();\n }\n }\n \n return len;\n }\n};" }, { "title": "Swap Nodes in Pairs", "algo_input": "Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)\n\n \nExample 1:\n\nInput: head = [1,2,3,4]\nOutput: [2,1,4,3]\n\n\nExample 2:\n\nInput: head = []\nOutput: []\n\n\nExample 3:\n\nInput: head = [1]\nOutput: [1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 100].\n\t0 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head:\n return head\n dummy = ListNode(None, head)\n prev, curr_1, curr_2 = dummy, head, head.next\n while curr_1 and curr_2:\n # 1. define temp nodes, temp nodes are comprised of 1 prev node, and multiple curr nodes. The while condition checks those curr nodes only.\n node_0 = prev\n node_1 = curr_1\n node_2 = curr_2\n node_3 = curr_2.next\n\n # 2. swap nodes using temp nodes\n node_0.next = node_2\n node_1.next = node_3\n node_2.next = node_1\n\n # 3. move temp nodes to the next window\n prev = node_1\n curr_1 = node_3\n curr_2 = node_3.next if node_3 else None\n\n return dummy.next", "solution_js": "var swapPairs = function(head) {\n if(!head || !head.next) return head;\n \n // using an array to store all the pairs of the list \n \n let ptrArr = [];\n let ptr = head;\n \n while(ptr) {\n ptrArr.push(ptr);\n let nptr = ptr.next ? ptr.next.next : null;\n if(nptr) ptr.next.next = null;\n ptr = nptr;\n }\n \n // reversing all the pairs of the list in array\n \n for(let i=0;i {\n nptr.next = ele;\n nptr = nptr.next.next;\n })\n \n return dummy.next;\n \n};", "solution_java": "class Solution {\n public ListNode swapPairs(ListNode head) {\n ListNode dummy = new ListNode(0) , prev = dummy , curr = head;\n dummy.next = head;\n while(curr != null && curr.next != null){\n prev.next = curr.next;\n curr.next = curr.next.next ;\n prev.next.next = curr;\n curr = curr.next ;\n prev = prev.next.next;\n }\n return dummy.next;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* swapPairs(ListNode* head) {\n // if head is NULL OR just having a single node, then no need to change anything\n if(head == NULL || head -> next == NULL)\n {\n return head;\n }\n\n ListNode* temp; // temporary pointer to store head -> next\n temp = head->next; // give temp what he want\n\n head->next = swapPairs(head->next->next); // changing links\n temp->next = head; // put temp -> next to head\n\n return temp; // now after changing links, temp act as our head\n }\n};" }, { "title": "Rabbits in Forest", "algo_input": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.\n\nGiven the array answers, return the minimum number of rabbits that could be in the forest.\n\n \nExample 1:\n\nInput: answers = [1,1,2]\nOutput: 5\nExplanation:\nThe two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n\n\nExample 2:\n\nInput: answers = [10,10,10]\nOutput: 11\n\n\n \nConstraints:\n\n\n\t1 <= answers.length <= 1000\n\t0 <= answers[i] < 1000\n\n", "solution_py": "class Solution:\n def numRabbits(self, answers: List[int]) -> int:\n counts = {}\n count = 0\n\n for answer in answers:\n if answer == 0:\n # This must be the only rabbit of its color.\n count += 1\n elif answer not in counts or counts[answer] == 0:\n # This is the first time the color appears.\n counts[answer] = 1\n # Add all rabbits having this new color.\n count += answer + 1\n else:\n # Add one to how many times answer occurred.\n counts[answer] += 1\n if counts[answer] > answer:\n # If n+1 rabbits have said n,\n # this color group is complete.\n counts[answer] = 0\n \n return count", "solution_js": "/**\n * @param {number[]} answers\n * @return {number}\n */\nvar numRabbits = function(answers) {\n \n var totalRabbits = 0;\n var sumOfLikeAnswers = new Array(1000).fill(0);\n \n for (let i = 0; i < answers.length; i++) {\n sumOfLikeAnswers[answers[i]] += 1;\n }\n \n for (let i = 0; i < sumOfLikeAnswers.length; i++) {\n totalRabbits += Math.ceil(sumOfLikeAnswers[i] / (i+1)) * (i+1);\n }\n \n return totalRabbits;\n};", "solution_java": "class Solution {\n public int numRabbits(int[] answers) {\n HashMap map = new HashMap<>();\n int count = 0;\n \n for(int ele : answers) {\n \n if(!map.containsKey(ele+1)) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else if(map.get(ele+1) == ele+1) {\n map.put(ele+1, 1);\n count += ele+1;\n }\n else {\n int freq = map.get(ele+1);\n map.put(ele+1, freq+1);\n }\n }\n \n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int numRabbits(vector& answers) {\n sort(answers.begin(),answers.end());\n int ans = 0;\n for(int i=0;i0 && i+1 int:\n mod = 10**9+7\n return (pow(2**p-2,2**(p-1)-1,mod)*(2**p-1))%mod", "solution_js": "var minNonZeroProduct = function(p) {\n p = BigInt(p);\n \n const MOD = BigInt(1e9 + 7);\n const first = ((1n << p) - 1n);\n \n const half = first / 2n;\n \n const second = powMOD(first - 1n, half); \n \n return (first * second) % MOD;\n \n function powMOD(num, exp) {\n if (exp === 0n) return 1n; \n \n const tmp = powMOD(num, exp >> 1n);\n \n let res = (tmp * tmp) % MOD;\n \n if (exp % 2n) res = (res * num) % MOD;\n \n return res;\n }\n}; ", "solution_java": "class Solution {\n public int mod = 1_000_000_007;\n public int minNonZeroProduct(int p) {\n if (p == 1) return 1;\n \n long mx = (long)(Math.pow(2, p)) - 1;\n long sm = mx - 1;\n long n = sm/2;\n long sum = rec(sm, n);\n \n return (int)(sum * (mx % mod) % mod); \n }\n \n public long rec(long val, long n) {\n if (n == 0) return 1;\n if (n == 1) return (val % mod);\n \n long newVal = ((val % mod) * (val % mod)) % mod;\n \n if (n % 2 != 0) {\n return ((rec(newVal, n/2) % mod) * (val % mod)) % mod;\n }\n \n return rec(newVal, n/2) % mod;\n }\n}", "solution_c": "class Solution {\npublic:\n long long myPow(long long base, long long exponent, long long mod) {\n if (exponent == 0) return 1;\n if (exponent == 1) return base % mod;\n \n long long tmp = myPow(base, exponent/2, mod);\n \n if (exponent % 2 == 0) { // (base ^ exponent/2) * (base ^ exponent/2)\n return (tmp * tmp) % mod;\n }\n else { // (base ^ exponent/2) * (base ^ exponent/2) * base\n tmp = tmp * tmp % mod;\n base %= mod;\n return (tmp * base) % mod;\n }\n }\n \n int minNonZeroProduct(int p) {\n long long range = pow(2, p);\n range--;\n long long mod = pow(10, 9) + 7;\n long long tmp = myPow(range-1, range/2, mod);\n return (tmp * (range%mod)) % mod;\n }\n};" }, { "title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance", "algo_input": "There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.\n\nReturn the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.\n\nNotice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.\n\n \nExample 1:\n\nInput: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput: 3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\n\n\nExample 2:\n\nInput: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput: 0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 100\n\t1 <= edges.length <= n * (n - 1) / 2\n\tedges[i].length == 3\n\t0 <= fromi < toi < n\n\t1 <= weighti, distanceThreshold <= 10^4\n\tAll pairs (fromi, toi) are distinct.\n\n", "solution_py": "class Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n\n matrix = [[float('inf')] * n for _ in range(n)]\n \n # initializing the matrix\n for u, v, w in edges:\n matrix[u][v] = w\n matrix[v][u] = w\n\n for u in range(n):\n matrix[u][u] = 0\n \n for k in range(n):\n for i in range(n):\n for j in range(n):\n if matrix[i][j] > matrix[i][k] + matrix[k][j]:\n matrix[i][j] = matrix[i][k] + matrix[k][j]\n \n # counting reachable cities(neighbor) for every single city \n res = [0] * n\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if 0 < matrix[i][j] <= distanceThreshold:\n res[j] += 1\n return [i for i, x in enumerate(res) if x == min(res)][-1]", "solution_js": "var findTheCity = function(n, edges, distanceThreshold) {\n const dp = Array.from({length: n}, (_, i) => {\n return Array.from({length: n}, (_, j) => i == j ? 0 : Infinity)\n });\n\n for(let edge of edges) {\n const [a, b, w] = edge;\n dp[a][b] = dp[b][a] = w;\n }\n\n // k is intermediate node\n for(let k = 0; k < n; k++) {\n // fix distances from i to other nodes with k as intermediate\n for(let i = 0; i < n; i++) {\n if(i == k || dp[i][k] == Infinity) continue;\n for(let j = i + 1; j < n; j++) {\n dp[i][j] = dp[j][i] = Math.min(dp[i][j], dp[i][k] + dp[k][j]);\n }\n }\n };\n\n let city = -1, minCity = n;\n for(let i = 0; i < n; i++) {\n let count = 0;\n for(let j = 0; j < n; j++) {\n if(i == j) continue;\n if(dp[i][j] <= distanceThreshold) count++;\n }\n if(count <= minCity) {\n minCity = count;\n city = i;\n }\n }\n\n return city;\n};", "solution_java": "class Solution {\n public int findTheCity(int n, int[][] edges, int distanceThreshold) {\n int[][] graph = new int[n][n];\n for(int[] row: graph)\n Arrays.fill(row, Integer.MAX_VALUE);\n \n for(int i = 0; i < n; i++)\n graph[i][i] = 0;\n \n for(int[] edge: edges)\n {\n graph[edge[0]][edge[1]] = edge[2];\n graph[edge[1]][edge[0]] = edge[2];\n }\n \n for(int k = 0; k < n; k++)\n {\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < n; j++)\n {\n if(graph[i][k] != Integer.MAX_VALUE && graph[k][j] != Integer.MAX_VALUE)\n {\n if(graph[i][k] + graph[k][j] < graph[i][j])\n graph[i][j] = graph[i][k] + graph[k][j];\n }\n }\n }\n }\n \n int ans = 0;\n int city = Integer.MAX_VALUE;;\n \n for(int i = 0; i < n; i++)\n {\n int current = 0;\n for(int j = 0; j < n; j++)\n {\n if(i != j && graph[i][j] <= distanceThreshold)\n current++;\n }\n if(current <= city)\n {\n ans = i;\n city = current;\n }\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\nunordered_mapm;\n int findTheCity(int n, vector>& edges, int threshold) {\n vector>>adj(n);\n for(auto x:edges)\n {\n adj[x[0]].push_back({x[1],x[2]});\n adj[x[1]].push_back({x[0],x[2]});\n }\n int ind=-1,ans=1e8;\n for(int i=0;i>q;\n q.push({i,0});\n vectordis(n,1e8);\n dis[i]=0;\n while(!q.empty())\n {\n int node=q.front().first;\n int wt=q.front().second;\n q.pop();\n for(auto x:adj[node])\n {\n int node1=x.first;\n int wt1=x.second;\n if(wt+wt1 int:\n count = 0\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n for k in range(j+1,len(arr)):\n if abs(arr[i]-arr[j])<=a and abs(arr[j]-arr[k])<=b and abs(arr[k]-arr[i])<=c:\n count+=1\n return count", "solution_js": "var countGoodTriplets = function(arr, a, b, c) {\n let triplets = 0;\n\n for (let i = 0; i < arr.length - 2; i++) {\n for (let j = i + 1; j < arr.length - 1; j++) {\n if (Math.abs(arr[i] - arr[j]) > a) continue;\n for (let k = j + 1; k < arr.length; k++) {\n if (Math.abs(arr[j] - arr[k]) > b || Math.abs(arr[i] - arr[k]) > c) {\n continue;\n }\n triplets++;\n }\n }\n }\n\n return triplets;\n};", "solution_java": "class Solution {\n public int countGoodTriplets(int[] arr, int a, int b, int c) {\n int total = 0;\n for (int i = 0; i < arr.length - 2; i++){\n for (int j = i+1; j < arr.length - 1; j++){\n for (int k = j+1; k < arr.length; k++){\n if (helper(arr[i], arr[j]) <= a &&\n helper(arr[j], arr[k]) <= b &&\n helper(arr[k], arr[i]) <= c)\n total++;\n }\n }\n }\n return total;\n }\n\n private static int helper(int x, int y) {\n return Math.abs(x - y);\n }\n}", "solution_c": "class Solution {\npublic:\n int countGoodTriplets(vector& arr, int a, int b, int c) {\n int ct = 0;\n for(int i = 0; i int:\n fb = set(fb)\n q = deque([[0,0,True]])\n while(q):\n n,l,isf = q.popleft()\n if(n<0 or n in fb or n>2000+2*b):\n continue\n fb.add(n)\n if(n==x):\n return l\n if isf and n-b>0:\n q.append([n-b,l+1,False]) \n q.append([n+a,l+1,True])\n return -1", "solution_js": "var minimumJumps = function(forbidden, a, b, x) {\n let f = new Set(forbidden);\n let m = 2000 + 2 * b;\n let memo = {};\n let visited = new Set();\n let res = dfs(0, true);\n return res === Infinity ? -1 : res;\n \n function dfs(i,canJumpBack) {\n if (i === x) return 0;\n let key = `${i},${canJumpBack}`;\n visited.add(i);\n if (memo[key] !== undefined) return memo[key];\n if (i > m || i < 0) return Infinity;\n let min = Infinity;\n if (canJumpBack && !f.has(i - b) && !visited.has(i-b)) {\n min = Math.min(min, 1 + dfs(i - b, false));\n }\n \n if (!f.has(i + a) && !visited.has(i+a)) {\n min = Math.min(min, 1 + dfs(i + a, true));\n }\n \n visited.delete(i);\n return memo[key] = min;\n }\n};", "solution_java": "class Solution {\n public int minimumJumps(int[] forbidden, int a, int b, int x) {\n \n // Visited Set\n Set visited = new HashSet();\n \n // Add forbidden coordinates to visited\n for (int i = 0; i < forbidden.length; i++) {\n visited.add(forbidden[i]);\n }\n \n // Distance/ Jumps map\n Map jumps = new HashMap<>();\n jumps.put(0, 0);\n \n // BFS Queue\n Queue q = new LinkedList<>();\n q.add(new Integer[] {0, 1});\n \n // BFS \n while (q.size() != 0) {\n \n Integer[] ud = q.poll();\n \n int u = ud[0], d = ud[1];\n \n // x found\n if (u == x) {\n return jumps.get(u);\n }\n \n // jump right\n if (u + a < 6001 && !visited.contains(u+a)) {\n q.add(new Integer[] {u+a, 1});\n visited.add(u+a);\n jumps.put(u+a, jumps.get(u) + 1);\n }\n \n // jump left\n if (d != -1 && u - b > -1 && !visited.contains(u-b)) {\n q.add(new Integer[] {u-b, -1});\n jumps.put(u-b, jumps.get(u) + 1);\n }\n \n }\n \n return -1;\n \n }\n}", "solution_c": "class Solution\n{\npublic:\n typedef pair pi;\n int minimumJumps(vector &forbidden, int a, int b, int x)\n {\n set st(forbidden.begin(), forbidden.end());\n vector> vis(2, vector(10000, 0));\n vis[0][0] = 1;\n vis[1][0] = 1;\n queue q;\n q.push({0, true});\n int ans = 0;\n while (!q.empty())\n {\n int n = q.size();\n for (int i = 0; i < n; i++)\n {\n int curr = q.front().first;\n bool canJumpBackward = q.front().second;\n q.pop();\n if (curr == x)\n return ans;\n int p1 = curr + a;\n int p2 = curr - b;\n if (p1 < 10000 && vis[0][p1] == 0 && st.find(p1) == st.end())\n {\n q.push({p1, true});\n vis[0][p1] = 1;\n }\n if (p2 >= 0 && vis[1][p2] == 0 && st.find(p2) == st.end() && canJumpBackward == true)\n {\n q.push({p2, false});\n vis[1][p2] = 1;\n }\n }\n ans++;\n }\n return -1;\n }\n};" }, { "title": "Count Pairs Of Nodes", "algo_input": "You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.\n\nLet incident(a, b) be defined as the number of edges that are connected to either node a or b.\n\nThe answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:\n\n\n\ta < b\n\tincident(a, b) > queries[j]\n\n\nReturn an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.\n\nNote that there can be multiple edges between the same two nodes.\n\n \nExample 1:\n\nInput: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput: [6,5]\nExplanation: The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\n\n\nExample 2:\n\nInput: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput: [10,10,9,8,6]\n\n\n \nConstraints:\n\n\n\t2 <= n <= 2 * 104\n\t1 <= edges.length <= 105\n\t1 <= ui, vi <= n\n\tui != vi\n\t1 <= queries.length <= 20\n\t0 <= queries[j] < edges.length\n\n", "solution_py": "class Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n p_c = [0] * (n+1) # point counter\n e_c = defaultdict(int) # edge counter\n \n for a,b in edges:\n p_c[a] += 1\n p_c[b] += 1\n if a a - b); \n \n for(let num of queries) {\n let cnt;\n if(countMemo.has(num)) cnt = countMemo.get(num)\n else {\n cnt = calculateCount(num)\n countMemo.set(num, cnt);\n }\n answer.push(cnt)\n }\n \n function calculateCount(num) {\n let low = 0, high = sortedDegree.length-1, cnt = 0;\n \n while(low < high) {\n const sum = sortedDegree[low] + sortedDegree[high];\n \n if(sum > num) {\n cnt += (high - low);\n high--;\n } else low++;\n }\n \n for(let [key, val] of edgesMap) {\n const [u, v] = key.split('-').map(Number);\n \n if(degree[u] + degree[v] > num) {\n const newSum = degree[u] + degree[v] - val\n if(newSum <= num) cnt--;\n }\n }\n return cnt;\n }\n return answer;\n};", "solution_java": "class Solution {\n public int[] countPairs(int n, int[][] edges, int[] queries) {\n Map> dupMap = new HashMap<>();\n Map> map = new HashMap<>();\n int[] ans = new int[queries.length];\n int[] count = new int[n];\n for (int[] e : edges){\n int min = Math.min(e[0]-1, e[1]-1);\n int max = Math.max(e[0]-1, e[1]-1);\n dupMap.computeIfAbsent(min, o -> new HashMap<>()).merge(max, 1, Integer::sum);\n map.computeIfAbsent(min, o -> new HashSet<>()).add(max);\n count[min]++;\n count[max]++;\n }\n Integer[] indexes = IntStream.range(0, n).boxed().toArray(Integer[]::new);\n Arrays.sort(indexes, Comparator.comparingInt(o -> count[o]));\n for (int j = 0, hi = n; j < queries.length; j++, hi = n){\n for (int i = 0; i < n; i++){\n while(hi>i+1&&count[indexes[i]]+count[indexes[hi-1]]>queries[j]){\n hi--;\n }\n if (hi==i){\n hi++;\n }\n ans[j]+=n-hi;\n for (int adj : map.getOrDefault(indexes[i], Set.of())){\n int ttl = count[indexes[i]] + count[adj];\n if (ttl > queries[j] && ttl-dupMap.get(indexes[i]).get(adj) <= queries[j]){\n ans[j]--;\n }\n }\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\n vector st;\npublic:\n void update(int tind,int tl,int tr,int ind,int val){\n if(tl>tr)\n return;\n if(tl==tr){\n st[tind]+=val;\n return;\n }\n int tm=tl+((tr-tl)>>1),left=tind<<1;\n if(ind<=tm)\n update(left,tl,tm,ind,val);\n else\n update(left|1,tm+1,tr,ind,val);\n st[tind]=st[left]+st[left|1];\n }\n \n int query(int tind,int tl,int tr,int ql,int qr){\n if(tl>tr or qrtr)\n return 0;\n if(ql<=tl and tr<=qr)\n return st[tind];\n int tm=tl+((tr-tl)>>1),left=tind<<1;\n return query(left,tl,tm,ql,qr)+query(left|1,tm+1,tr,ql,qr);\n }\n \n vector countPairs(int n,vector>& a,vector& q) {\n vector f(n+2,0);\n vector> mp(n+2); // using a normal map gives TLE\n \n for(auto v:a){\n int mx=max(v[0],v[1]),mn=min(v[1],v[0]);\n f[mx]++;\n f[mn]++;\n mp[mx][mn]++;\n }\n \n vector ans(q.size(),0);\n int m=a.size();\n st.resize(4*m+40,0);\n \n for(int i=n;i;i--){\n\t\t\t// reducing the common edges between current node and its adjacent\n for(auto e:mp[i]){\n update(1,0,m,f[e.first],-1);\n update(1,0,m,f[e.first]-e.second,1);\n }\n \n int curr=f[i];\n for(int j=0;j int:\n arrivals = []\n departures = []\n for ind, (x, y) in enumerate(times):\n heappush(arrivals, (x, ind))\n heappush(departures, (y, ind))\n d = {}\n occupied = [0] * len(times)\n while True:\n if arrivals and departures and arrivals[0][0] < departures[0][0]:\n _, ind = heappop(arrivals)\n d[ind] = occupied.index(0)\n occupied[d[ind]] = 1\n if ind == targetFriend:\n return d[ind]\n elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n _, ind = heappop(departures)\n occupied[d[ind]] = 0", "solution_js": "/**\n * @param {number[][]} times\n * @param {number} targetFriend\n * @return {number}\n */\nvar smallestChair = function(times, targetFriend) {\n const [targetArrival] = times[targetFriend]; // we need only arrival time\n const arrivalQueue = times;\n const leavingQueue = [...times];\n arrivalQueue.sort((a, b) => a[0] - b[0]); // sort by arrival time\n leavingQueue.sort((a, b) => (a[1] - b[1]) || (a[0] - b[0])); // sort by leaving time and if they are equal by arrival\n const chairsByLeaveTime = new Map(); // key - arrival time, value - chair index\n let chairsCount = 0;\n let arriving = 0, leaving = 0; // two pointers for keeping track of available chairs\n\n while (arriving < arrivalQueue.length) {\n let chairIdx;\n const arrival = arrivalQueue[arriving][0];\n const leave = leavingQueue[leaving][1];\n if (arrival < leave) {\n chairIdx = chairsCount++; // if no one is leaving, take a new chair\n } else {\n let freeChairIdx = leaving;\n chairIdx = chairsByLeaveTime.get(leavingQueue[freeChairIdx++][0]); // when arriaval time is less then or equal to the next leaving friend we can take her chair\n while (arrival >= leavingQueue[freeChairIdx][1]) { // to avoid situation when a few friends left already and the next chair in leaving queue is not the smallest\n const nextChair = chairsByLeaveTime.get(leavingQueue[freeChairIdx][0]);\n if (chairIdx > nextChair) {\n [leavingQueue[leaving], leavingQueue[freeChairIdx]] = [leavingQueue[freeChairIdx], leavingQueue[leaving]]; // swap the front of the queue with the smallest chair owner\n chairIdx = nextChair;\n }\n ++freeChairIdx;\n }\n ++leaving;\n }\n if (targetArrival === arrival) { // we found the target, no need to continue\n return chairIdx;\n }\n chairsByLeaveTime.set(arrival, chairIdx); // as far as arrival time is distinct, we can use it as a key\n arriving++;\n }\n};", "solution_java": "class Solution {\n public int smallestChair(int[][] times, int targetFriend) {\n int targetStart = times[targetFriend][0];\n Arrays.sort(times, (a, b) -> a[0] - b[0]);\n\n PriorityQueue available = new PriorityQueue<>();\n for (int i = 0; i < times.length; ++ i) {\n available.offer(i);\n }\n\n PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);\n\n for (int i = 0; i < times.length; ++ i) {\n while (!pq.isEmpty() && pq.peek()[0] <= times[i][0]) {\n available.offer(pq.poll()[1]);\n }\n\n if (times[i][0] == targetStart) {\n break;\n }\n\n pq.offer(new int[]{times[i][1], available.poll()});\n }\n\n return available.peek();\n }\n}", "solution_c": "class Solution {\npublic:\n int smallestChair(vector>& times, int targetFriend) {\n \n int n = times.size();\n priority_queue, vector>, greater> > busy; //departure time as first , index as second\n priority_queue, greater> free; //min heap of chair index that are unoccupied\n \n\t\t//store friend indexes so that they don't get lost after sorting\n for(int i=0;i int:\n return int(s[0:2])*60 + int(s[3:5])\n def convertTime(self, current: str, correct: str) -> int:\n diff = self.HHMMToMinutes(correct) - self.HHMMToMinutes(current)\n order = [60,15,5,1]\n ops = 0\n for i in range(0,4):\n ops+=int(diff/order[i])\n diff%=order[i]\n return ops", "solution_js": "var getTime = function(time){\n var [hrs,mins] = time.split(\":\");\n return parseInt(hrs)*60 + parseInt(mins);\n}\n\n\nvar convertTime = function(current, correct) {\n var diff = getTime(correct) - getTime(current);\n var order = [60,15,5,1];\n var ops = 0;\n order.forEach(val =>{\n ops+=Math.floor((diff/val));\n diff%=val;\n })\n return ops;\n};", "solution_java": "class Solution {\n public int HHMMToMinutes(String s){\n return Integer.parseInt(s.substring(0,2))*60 + Integer.parseInt(s.substring(3,5)) ;\n }\n public int convertTime(String current, String correct) {\n int diff = HHMMToMinutes(correct) - HHMMToMinutes(current);\n int[] order = {60,15,5,1};\n int i = 0;\n int ops = 0;\n while(i < 4){\n ops+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n return ops;\n }\n}", "solution_c": "class Solution {\npublic:\n int HHMMToMinutes(string s){\n return stoi(s.substr(0,2))*60 + stoi(s.substr(3,2));\n }\n int convertTime(string current, string correct) {\n int diff = - HHMMToMinutes(current) + HHMMToMinutes(correct);\n vector order = {60,15,5,1};\n int i = 0;\n int ans = 0;\n while(i < 4){\n ans+=(diff/order[i]);\n diff%=order[i];\n i++;\n }\n \n return ans;\n }\n};" }, { "title": "Minimum One Bit Operations to Make Integers Zero", "algo_input": "Given an integer n, you must transform it into 0 using the following operations any number of times:\n\n\n\tChange the rightmost (0th) bit in the binary representation of n.\n\tChange the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.\n\n\nReturn the minimum number of operations to transform n into 0.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 2\nExplanation: The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n\"01\" -> \"00\" with the 1st operation.\n\n\nExample 2:\n\nInput: n = 6\nOutput: 4\nExplanation: The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n\"010\" -> \"011\" with the 1st operation.\n\"011\" -> \"001\" with the 2nd operation since the 0th bit is 1.\n\"001\" -> \"000\" with the 1st operation.\n\n\n \nConstraints:\n\n\n\t0 <= n <= 109\n\n", "solution_py": "class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n if n <= 1:\n return n\n def leftmostbit(x):\n x |= x >> 1\n x |= x >> 2\n x |= x >> 4\n x |= x >> 8\n x |= x >> 16\n x += 1\n x >>= 1\n return x\n x = leftmostbit(n)\n return ((x << 1) - 1) - self.minimumOneBitOperations(n - x)", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar minimumOneBitOperations = function(n) {\n let answer = 0;\n let op = 1;\n let bits = 30;\n while(bits >= 0) {\n if(n & (1 << bits)) {\n let tmp = (1 << (bits + 1)) - 1;\n answer += tmp * op;\n op *= -1;\n }\n bits--;\n }\n return answer;\n}", "solution_java": "class Solution {\n public int minimumOneBitOperations(int n) {\n\n int inv = 0;\n\n // xor until n becomes zero\n for ( ; n != 0 ; n = n >> 1){\n\n inv ^= n;\n System.out.println(inv+\" \"+n);\n }\n\n return inv;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumOneBitOperations(int n) {\n int output = 0;\n \n while( n> 0)\n {\n output ^= n;\n n = n >> 1;\n }\n \n return output;\n }\n};" }, { "title": "Number of Islands", "algo_input": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.\n\nAn island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n\n \nExample 1:\n\nInput: grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput: 1\n\n\nExample 2:\n\nInput: grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput: 3\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 300\n\tgrid[i][j] is '0' or '1'.\n\n", "solution_py": "seen=set()\ndef dfs(i,j,m,n,grid):\n global seen\n if (i<0 or i>=m or j<0 or j>=n):return\n if (i,j) in seen:return\n seen.add((i,j))\n if grid[i][j]==\"1\":\n dfs(i,j+1,m,n,grid)\n dfs(i,j-1,m,n,grid)\n dfs(i+1,j,m,n,grid)\n dfs(i-1,j,m,n,grid)\n\nclass Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n global seen\n m=len(grid) #no of rows\n n=len(grid[0]) #no of columns\n count=0\n for i in range(m):\n for j in range(n):\n if (i,j) not in seen and grid[i][j]==\"1\":\n dfs(i,j,m,n,grid)\n count+=1\n seen.clear()\n return count", "solution_js": "/**\n * @param {character[][]} grid\n * @return {number}\n */\nvar numIslands = function(grid) {\n const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n let islandCount = 0\n \n for (let rowIndex = 0; rowIndex < grid.length; rowIndex++) {\n for (let colIndex = 0; colIndex < grid[0].length; colIndex++) {\n const node = grid[rowIndex][colIndex]\n \n // Don't bother with water\n if (node === \"0\") continue\n \n // Once we encounter land, try to get all\n // the connected land from the current land.\n // Once we get all the land connected from\n // the current land, mark them as water so\n // that it would disregarded by the main loop.\n islandCount++\n \n const connectedLandStack = [[rowIndex, colIndex]]\n \n while(connectedLandStack.length > 0) {\n const [row, col] = connectedLandStack.pop()\n \n // change the land to water\n grid[row][col] = \"0\"\n \n for (const direction of directions) {\n // To get all the connected land we need to check\n // all directions (left, right, top, bottom)\n const newNode = [row + direction[0], col + direction[1]]\n const newNodeValue = grid[newNode[0]]?.[newNode[1]]\n \n // We only care about the connected lands\n if (newNodeValue === undefined || newNodeValue === \"0\") {\n continue\n }\n \n connectedLandStack.push(newNode)\n }\n }\n }\n }\n \n return islandCount\n};", "solution_java": "class Solution {\n public int numIslands(char[][] grid) {\n int count = 0;\n int r = grid.length;\n int c = grid[0].length;\n for(int i=0;i=grid.length || j>=grid[0].length || grid[i][j]=='0'){\n return;\n }\n grid[i][j] = '0';\n dfs(grid,i,j+1);\n dfs(grid,i,j-1);\n dfs(grid,i+1,j);\n dfs(grid,i-1,j);\n }\n}", "solution_c": "class Solution {\npublic:\n\n void calculate(vector>& grid, int i, int j)\n {\n if(i>=grid.size() || j>=grid[i].size() || i<0 || j<0)\n return;\n\n if(grid[i][j]=='0')\n return;\n\n grid[i][j] = '0';\n calculate(grid,i,j-1);\n calculate(grid,i-1,j);\n calculate(grid,i,j+1);\n calculate(grid,i+1,j);\n\n }\n\n int numIslands(vector>& grid) {\n\n int ans = 0;\n\n for(int i=0;i int:\n res=\"\"\n count=0\n while len(res) a.repeat(times).includes(b);\n\n if (isMatch(initRepeatTimes)) return initRepeatTimes;\n if (isMatch(initRepeatTimes + 1)) return initRepeatTimes + 1;\n return -1;\n};", "solution_java": "class Solution {\n public int repeatedStringMatch(String a, String b) {\n String copyA = a;\n int count =1;\n int repeat = b.length()/a.length();\n for(int i=0;id; int mod=n%m; int h=n/m;\n\n if(mod==0)\n {d.push_back(h); d.push_back(h+1); }\n else\n { d.push_back(h+1); d.push_back(h+2); }\n string s=\"\"; string t=\"\";\n\n for(int i=0;i bool:\n val1 = root.val\n self.tracker = False\n def dfs(root,val1):\n if not root:\n return \n if root.val!=val1:\n self.tracker=True\n dfs(root.left,val1)\n dfs(root.right,val1)\n return \n dfs(root,val1)\n \n if self.tracker == False:\n return True\n return False", "solution_js": "var isUnivalTree = function(root) {\n if (!root) {\n return false;\n }\n\n const prev = root.val;\n const nodes = [root];\n\n for (const node of nodes) {\n if (node.val !== prev) {\n return false;\n }\n\n if (node.left) {\n nodes.push(node.left);\n }\n\n if (node.right) {\n nodes.push(node.right);\n }\n }\n\n return true;\n};\n ```", "solution_java": "class Solution {\n boolean ans=true;\n int firstVal=0;\n public boolean isUnivalTree(TreeNode root) {\n if(root==null)\n return ans; \n firstVal=root.val;\n traversal(root);\n return ans;\n }\n private void traversal(TreeNode root)\n {\n if(root==null)\n return;\n if(root.val!=firstVal)\n ans=false;\n traversal(root.left);\n traversal(root.right);\n }\n \n}", "solution_c": "class Solution {\npublic:\n bool recur(TreeNode* root, int value){\n if(root==NULL)\n return true;\n if(root->val!=value){\n return false;\n }\n return recur(root->left,value) &&recur(root->right,value);\n\n }\n bool isUnivalTree(TreeNode* root) {\n if(root==NULL)\n return true;\n int value=root->val;\n return recur(root,value);\n\n }\n};" }, { "title": "Maximum Product After K Increments", "algo_input": "You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.\n\nReturn the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo. \n\n \nExample 1:\n\nInput: nums = [0,4], k = 5\nOutput: 20\nExplanation: Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\nExample 2:\n\nInput: nums = [6,3,3,2], k = 2\nOutput: 216\nExplanation: Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length, k <= 105\n\t0 <= nums[i] <= 106\n\n", "solution_py": "import heapq\n\nclass Solution:\n def maximumProduct(self, nums, k: int) -> int:\n \n # creating a heap\n heap = []\n for i in nums:\n heapq.heappush (heap,i)\n \n \n # basic idea here is keep on incrementing smallest number, then only multiplication of that number will be greater\n # so basically till I have operations left I will increment my smallest number\n while k :\n current = heapq.heappop(heap)\n heapq.heappush(heap, current+1)\n k-=1\n \n result =1\n \n # Just Multiply all the numbers in heap and return the value\n while len(heap)>0:\n x= heapq.heappop(heap)\n result =(result*x )% (10**9+7)\n \n return result", "solution_js": "var maximumProduct = function(nums, k) {\n let MOD = Math.pow(10, 9) + 7;\n\n // build a new minimum priority queue\n // LeetCode loads MinPriorityQueue by default, no need to implement again\n let queue = new MinPriorityQueue();\n for (let i = 0; i < nums.length; i++) {\n queue.enqueue(nums[i], nums[i]);\n }\n\n // To maximize the product, take the smallest element out\n // add 1 to it and add it back to the queue\n let count = 0;\n while (count < k && queue.size() > 0) {\n let {element, priority} = queue.dequeue();\n queue.enqueue(element + 1, priority + 1);\n count += 1;\n }\n\n // calculate the product\n let result = 1;\n let elements = queue.toArray().map((a) => a.element);\n for (let i = 0; i < elements.length; i++) {\n result = (result * elements[i]) % MOD;\n }\n\n return result;\n};", "solution_java": "class Solution {\n public int maximumProduct(int[] nums, int k) {\n \n Queue pq = new PriorityQueue<>();\n for (int num : nums) pq.add(num);\n \n while (k-->0) {\n int top = pq.poll() + 1 ;\n pq.add(top);\n }\n\n long res = 1;\n while (!pq.isEmpty()) {\n res = (res*pq.poll()) % 1000000007;\n }\n\n return (int)(res);\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumProduct(vector& nums, int k) {\n\n priority_queue, greater> pq(nums.begin(), nums.end());\n\n while(k--) {\n int mini = pq.top();\n pq.pop();\n pq.push(mini + 1);\n }\n\n long long ans = 1, mod = 1e9+7;\n\n while(!pq.empty()) {\n ans = ((ans % mod) * (pq.top() % mod)) % mod;\n pq.pop();\n }\n\n return (int)ans;\n }\n};" }, { "title": "Maximize Number of Subsequences in a String", "algo_input": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.\n\nYou can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.\n\nReturn the maximum number of times pattern can occur as a subsequence of the modified text.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\n \nExample 1:\n\nInput: text = \"abdcdbc\", pattern = \"ac\"\nOutput: 4\nExplanation:\nIf we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.\n\n\nExample 2:\n\nInput: text = \"aabb\", pattern = \"ab\"\nOutput: 6\nExplanation:\nSome of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 105\n\tpattern.length == 2\n\ttext and pattern consist only of lowercase English letters.\n\n", "solution_py": "class Solution:\n def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n total = count_a = count_b = 0\n for c in text:\n if c == pattern[1]:\n total += count_a\n count_b += 1\n if c == pattern[0]:\n count_a += 1\n \n return total + max(count_a, count_b)", "solution_js": "/**\n * @param {string} text\n * @param {string} pattern\n * @return {number}\n */\nvar maximumSubsequenceCount = function(text, pattern) {\n const arrText = text.split(\"\")\n const lengthP0 = arrText.filter(x => x === pattern[0]).length\n const lengthP1 = arrText.filter(x => x === pattern[1]).length\n const [c1, c2, lengthmax] = lengthP0 <= lengthP1 ? [...pattern, lengthP1]: [pattern[1], pattern[0], lengthP0]\n let newText = lengthP0 <= lengthP1 ? [c1,...arrText]: [...arrText, c1]\n newText = lengthP0 <= lengthP1 ? newText : newText.reverse()\n\n let i = 0;\n let count = 0;\n let countmax = lengthmax\n while(i < newText.length) {\n if(newText[i] === c1) {\n count += countmax\n }\n if(newText[i] === c2) {\n countmax--\n }\n i++;\n }\n return count\n};", "solution_java": "class Solution {\n public long maximumSubsequenceCount(String text, String pattern) {\n //when pattern[0] == pattern[1]\n if (pattern.charAt(0) == pattern.charAt(1)) {\n long freq = 1;\n //O(N)\n for (int i = 0; i < text.length(); i++) {\n if (text.charAt(i) == pattern.charAt(0)) {\n freq++;\n }\n }\n //number of subsequences : choose any two characters from freq nC2\n return (freq * (freq - 1)) / 2;\n }\n\n //choice 1\n String text1 = pattern.charAt(0) + text;\n\n int freq = 0;\n long count1 = 0;\n //O(N)\n for (int i = 0; i < text1.length(); i++) {\n if (text1.charAt(i) == pattern.charAt(0)) {\n freq++;\n } else if (text1.charAt(i) == pattern.charAt(1)) {\n count1 += freq;\n }\n }\n\n //choice 2\n String text2 = text + pattern.charAt(1);\n freq = 0;\n long count2 = 0;\n //O(N)\n for (int i = text2.length() - 1; i>= 0; i--) {\n if (text2.charAt(i) == pattern.charAt(1)) {\n freq++;\n } else if (text2.charAt(i) == pattern.charAt(0)) {\n count2 += freq;\n }\n }\n\n return Math.max(count1, count2);\n }\n}", "solution_c": "class Solution {\npublic:\n long long maximumSubsequenceCount(string text, string pattern) {\n // support variables\n int len = text.size();\n long long res = 0, aCount = 0, bCount = 0;\n char a = pattern[0], b = pattern[1];\n // getting the frequencies\n for (char c: text) {\n if (c == a) aCount++;\n else if (c == b) bCount++;\n }\n // edge case: a == b\n if (a == b) return aCount++ * aCount / 2;\n // adding our extra character to maximise the occurrences\n if (aCount < bCount) res += bCount;\n else bCount++;\n // computing the occurrences\n for (char c: text) {\n // first case: spotting the first element of a sequence\n if (c == a) {\n res += bCount;\n }\n // second case: we found an ending sequence\n else if (c == b) bCount--;\n // all the rest: we do nothing\n }\n return res;\n }\n};" }, { "title": "Count Largest Group", "algo_input": "You are given an integer n.\n\nEach number from 1 to n is grouped according to the sum of its digits.\n\nReturn the number of groups that have the largest size.\n\n \nExample 1:\n\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "def compute(num):\n\tif num < 10:\n\t\treturn num\n\n\tnewVal = 0\n\n\twhile num > 0:\n\t\tlast = num % 10\n\t\tnewVal += last\n\t\tnum /= 10\n\n\treturn newVal\n\nclass Solution(object):\n\tdef countLargestGroup(self, n):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tmyMap = {}\n\n\t\tfor i in range(1, n + 1):\n\t\t\tval = compute(i)\n\n\t\t\tif val in myMap.keys():\n\t\t\t\tmyMap.get(val).append(i)\n\t\t\telse:\n\t\t\t\tmyMap[val] = [i]\n\n\t\tmaxLen = 0\n\n\t\tfor n in myMap.values():\n\t\t\tmaxLen = max(maxLen, len(n))\n\n\t\tans = 0\n\n\t\tfor n in myMap.values():\n\t\t\tif len(n) == maxLen:\n\t\t\t\tans += 1\n\n\t\treturn ans", "solution_js": "var countLargestGroup = function(n) {\n const hash = {};\n\n for (let i = 1; i <= n; i++) {\n const sum = i.toString().split('').reduce((r, x) => r + parseInt(x), 0);\n\n if (!hash[sum]) {\n hash[sum] = 0;\n }\n\n hash[sum]++;\n }\n\n return Object.keys(hash)\n .sort((a, b) => hash[b] - hash[a])\n .reduce((res, x) => {\n const prev = res[res.length - 1];\n\n if (!prev || prev === hash[x]) {\n res.push(hash[x]);\n }\n\n return res;\n }, []).length;\n};", "solution_java": "class Solution {\n public int countLargestGroup(int n) {\n Map map=new HashMap<>();\n for(int i=1;i<=n;i++){\n int x=sum(i);\n map.put(x,map.getOrDefault(x,0)+1);\n }\n int max=Collections.max(map.values());\n int c=0;\n for(int i:map.values()){\n if(i==max) c++;\n }\n return c;\n }\n public int sum(int g){\n int summ=0;\n while(g!=0){\n int rem=g%10;\n summ+=rem;\n g/=10;\n }\n return summ;\n }\n}```", "solution_c": "class Solution {\npublic:\n int cal(int n){\n int sum = 0;\n while(n > 0){\n sum += n%10;\n n /= 10;\n }\n return sum;\n }\n\n int countLargestGroup(int n) {\n int a[40];\n for(int i=0; i<40; i++) a[i] = 0;\n\n for(int i=1; i<=n; i++){\n a[cal(i)]++;\n }\n\n int max = 0;\n int count = 0;\n for(int i=0; i<40; i++){\n if(a[i] > max){\n count = 1;\n max = a[i];\n }\n else if(a[i] == max) count++;\n }\n\n return count;\n }\n};" }, { "title": "Snakes and Ladders", "algo_input": "You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.\n\nYou start on square 1 of the board. In each move, starting from square curr, do the following:\n\n\n\tChoose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].\n\n\t\n\t\tThis choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.\n\t\n\t\n\tIf next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.\n\tThe game ends when you reach the square n2.\n\n\nA board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder.\n\nNote that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.\n\n\n\tFor example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.\n\n\nReturn the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.\n\n \nExample 1:\n\nInput: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput: 4\nExplanation: \nIn the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.\n\n\nExample 2:\n\nInput: board = [[-1,-1],[-1,3]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tn == board.length == board[i].length\n\t2 <= n <= 20\n\tgrid[i][j] is either -1 or in the range [1, n2].\n\tThe squares labeled 1 and n2 do not have any ladders or snakes.\n\n", "solution_py": "class Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n # creating a borad map to loop-up the square value\n board_map = {}\n i = 1\n b_rev = board[::-1]\n for d, r in enumerate(b_rev):\n\t\t\t# reverse for even rows - here d is taken as direction \n if d%2 != 0: r = r[::-1] \n for s in r:\n board_map[i] = s\n i += 1\n \n # BFS Algorithm\n q = [(1, 0)] # (curr, moves)\n v = set()\n goal = len(board) * len(board) # end square\n \n while q:\n curr, moves = q.pop(0)\n # win situation\n if curr == goal: return moves\n # BFS on next 6 places (rolling a die)\n for i in range(1, 7):\n # skip square outside board\n if curr+i > goal: continue\n # get value from mapping\n next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i]\n if next_pos not in v:\n v.add(next_pos)\n q.append((next_pos, moves+1))\n \n return -1\n ", "solution_js": "var snakesAndLadders = function(board) {\n let n = board.length;\n let seen = new Set();\n let queue = [[1, 0]];\n\n while (queue.length) {\n let [label, step] = queue.shift();\n //console.log(label, step);\n let [r, c] = labelToPosition(label, n);\n //console.log(r, c, n);\n if (board[r][c] !== -1) {\n label = board[r][c];\n }\n if (label == n * n) {\n return step;\n }\n for (let x = 1; x < 7; x++) {\n let nextLabel = label + x;\n if (nextLabel <= n * n && !seen.has(nextLabel)) {\n seen.add(nextLabel);\n queue.push([nextLabel, step + 1]);\n }\n }\n }\n return -1;\n};\n\nconst labelToPosition = (label, n) => {\n let row = Math.floor((label - 1) / n);\n let col = (label - 1) % n;\n //console.log(\"label\", row, col);\n if (row % 2 === 0) {\n return [n - 1 - row, col];\n } else {\n return [n - 1 - row, n - 1 - col];\n }\n};", "solution_java": "class Solution {\n //what if we have changed the dice number, or changing the starting index or changing the ending index\n //so i have covered all possible ways in which this question can be asked\n\n//bfs tip:- for better bfs, we can use marking first and then inserting it in the queue which works faster then removing first and then checking\n public int [] getans(int dice,HashMap map,int si,int ei){\n //if si==ei just directly return \n if(si==ei) return new int [] {0,0,0};\n LinkedList que = new LinkedList<>();\n que.addLast(new int[] {si,0,0});\n int level = 0;\n //to stop visiting cells again\n boolean [] vis = new boolean [ei+1];\n vis[si]=true;\n //starting bfs\n while(que.size()!=0){\n int size=que.size();\n while(size-->0){\n int [] rem = que.removeFirst();\n int idx= rem[0];\n int lad = rem[1];\n int sna = rem[2];\n for(int i=1;i<=dice;i++){\n int x =i+rem[0]; //checking all the steps\n if(x<=ei){ //valid points\n if(map.containsKey(x)){ //this means that we have encountered a snake or a ladder\n if(map.containsKey(x)){\n int val = map.get(x); \n if(val==ei) return new int[] {level+1,lad+1,sna};\n if(!vis[val]){\n vis[val]=true;\n //if val>x this means we have a ladder and if less, then it is a snake\n que.addLast(val>x? new int [] {val,lad+1,sna}:new int [] {val,lad,sna+1});\n }\n }\n }\n else{\n //if it is not present in map, then it is a normal cell, so just insert it directly\n if(x==ei) return new int [] {level+1,lad,sna};\n if(!vis[x]){\n vis[x]=true;\n que.addLast(new int [] {x,lad,sna});\n }\n }\n }\n }\n }\n level++;\n }\n return new int [] {-1,0,0};\n }\n public int snakesAndLadders(int[][] board) {\n HashMap map = new HashMap<>();\n int count = 1;\n int n = board.length;\n boolean flag = true;\n //traversing the board in the board game fashion and checking if the count that is representing the cell number, if we encounter something other then -1, then it can be a snake or it can be a ladder and mapping that cell index (i.e count to that number)\n for(int i=n-1;i>=0;i--){\n //traversing in the order of the board\n if(flag){\n for(int j=0;j=0;j--){\n if(board[i][j]!=-1){\n map.put(count,board[i][j]);\n }\n flag=true;\n count++;\n }\n }\n }\n //if snake on destination then just return -1;\n if(board[0][0]!=-1) return -1;\n //we only want the minimum steps, but for more conceptual approach for this question, {minm steps,ladders used, snakes used} \n int [] ans = getans(6,map,1,n*n);;\n return ans[0];\n \n }\n}", "solution_c": "class Solution {\npublic:\n int snakesAndLadders(vector>& board) {\n unordered_map mp;\n int n = board.size();\n for(int i = n-1; i >= 0; i--) {\n for(int j = 0; j < n; j++) {\n if(board[i][j] != -1) {\n int val;\n if((n-i)%2 != 0) val = (n-i-1)*n + j + 1;\n else val = (n-i-1)*n + n - j;\n mp[val] = board[i][j];\n }\n }\n }\n queue> q;\n vector visited(n*n+1, false);\n q.push({1, 0});\n while(!q.empty()) {\n int node = q.front().first;\n int moves = q.front().second;\n q.pop();\n if(node == n*n) return moves;\n if(visited[node]) continue;\n visited[node] = true;\n for(int k = 1; k <= 6; k++) {\n if(node+k > n*n) continue;\n int x = node + k;\n if(mp.find(x) != mp.end()) x = mp[x];\n q.push({x, moves+1});\n }\n }\n return -1;\n }\n};" }, { "title": "Non-negative Integers without Consecutive Ones", "algo_input": "Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.\n\n \nExample 1:\n\nInput: n = 5\nOutput: 5\nExplanation:\nHere are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n\n\nExample 2:\n\nInput: n = 1\nOutput: 2\n\n\nExample 3:\n\nInput: n = 2\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\n", "solution_py": "class Solution:\n def findIntegers(self, n: int) -> int:\n b=(bin(n).replace(\"0b\",\"\"))\n dp=[[[[-1 for i in range(2)] for i in range(2)] for i in range(2)] for i in range(30)]\n def fun(i,last,tight,leading_zeros):\n if i==len(str(b)):\n return 1\n if dp[i][tight][leading_zeros][last]!=-1:\n return dp[i][tight][leading_zeros][last]\n end=1\n if tight==1:\n end = int(b[i])\n res=0\n for j in range(end+1):\n if j==0 and leading_zeros==1:\n res+=fun(i+1,j,tight&int(j==end),1)\n else:\n if j==0:\n res+=fun(i+1,j,tight&int(j==end),0)\n else:\n if last!=j:\n res+=fun(i+1,j,tight&int(j==end),0)\n dp[i][tight][leading_zeros][last] = res\n return res\n return fun(0,0,1,1)", "solution_js": "var findIntegers = function(n) {\n let dp = len=>{\n if (len<0)\n return 0;\n if (!len)\n return 1;\n let _0x = 1; // number of accepted combination when '1' is first\n let _1x = 1; // number of accepted combination when '0' is first\n while (--len)\n [_0x, _1x] = [_0x+_1x, _0x];\n return _0x + _1x;\n };\n let binary = n.toString(2);\n let count = 0;\n let is_prev_one = false;\n for (let i = 0; i0){\n cn=cn>>1;\n digi++;\n }\n int dp[]=new int[digi+1];\n dp[0]=1;dp[1]=2;\n for(i=2;i<=digi;i++)\n dp[i]=dp[i-1]+dp[i-2];\n digi++;\n while(digi-->=0){\n if((n&(1<0){\n res+=dp[digi];\n if(prevdig==1)return res;\n prevdig=1;\n }else prevdig=0;\n }\n \n return res+1;\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[31][2];\n vector f(){ \n vector res(31, 1);\n dp[1][0]=0;\n dp[1][1]=1;\n for(int i=2; i<31; i++){\n dp[i][0]=dp[i-1][0]+dp[i-1][1];\n dp[i][1]=dp[i-1][0];\n }\n \n \n for(int i=1; i<31; i++){\n res[i]=res[i-1]+dp[i][0]+dp[i][1];\n }\n\n res[1]=2;\n return res;\n }\n \n int findIntegers(int n) {\n int res=0;\n int bits=0;\n int temp=n;\n vector v;\n while(temp>0){\n bits++;\n v.push_back(temp&1);\n temp=temp>>1;\n }\n vector nums=f();\n \n bool valid=true, isValid=true;\n\n for(int i=bits-2;i>=0;i--){\n if(v[i]==1 && v[i+1]==1){\n res+=nums[i];\n isValid=false;\n break;\n }else if(v[i]==1)\n res+=nums[i];\n }\n \n res+=nums[bits-1];\n return isValid==true ? res+1:res;\n }\n};" }, { "title": "Number of Restricted Paths From First to Last Node", "algo_input": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.\n\nA path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.\n\nThe distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.\n\nReturn the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput: 3\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5\n\n\nExample 2:\n\nInput: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput: 1\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 104\n\tn - 1 <= edges.length <= 4 * 104\n\tedges[i].length == 3\n\t1 <= ui, vi <= n\n\tui != vi\n\t1 <= weighti <= 105\n\tThere is at most one edge between any two nodes.\n\tThere is at least one path between any two nodes.\n\n", "solution_py": "class Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n dct_nd = {}\n dist_to_n = {}\n queue = deque() # from n-node to 1-node\n visited = set()\n \n # 1 step: create dictionary with nodes and nodes' distances to n\n\n # create dictionary with format (weight, node_to)\n # heap will automatically sort weight and node_to in ascending order\n for l, r, w in edges:\n dct_nd[l] = dct_nd.get(l, []) + [(w, r)]\n dct_nd[r] = dct_nd.get(r, []) + [(w, l)]\n \n dist_to_n[n] = 0\n queue.append(n)\n visited.add(n)\n \n hpf = dct_nd[n].copy() # without '.copy()' hpf will be only pointer and dct_nd[n] could change\n heapify(hpf)\n while hpf:\n el_w, el_nd = heappop(hpf)\n if el_nd in visited: continue\n \n dist_to_n[el_nd] = el_w\n visited.add(el_nd)\n queue.append(el_nd)\n\n if el_nd == 1: break # you don't need to traverse more if you've reached 1-node\n # other distances will be more than distance of 1-node\n for (i_w, i_nd) in dct_nd[el_nd]:\n if i_nd not in visited:\n heappush(hpf, (el_w + i_w, i_nd))\n # step 1: end\n\n # add to dictionary one more field: number of routes to n\n dist_to_n = {k: [v, 0] for k, v in dist_to_n.items()}\n dist_to_n[n] = [dist_to_n[n][0], 1] # for n-node number of routes = 1\n \n # step 2: Dynamic Programming\n visited.clear()\n while queue:\n # start from n and traverse futher and futher\n nd_prv = queue.popleft()\n visited.add(nd_prv)\n for (w_cur, nd_cur) in dct_nd[nd_prv]:\n if nd_cur not in visited and \\\n nd_cur in dist_to_n.keys() and dist_to_n[nd_cur][0] > dist_to_n[nd_prv][0]:\n # to current node add number of routes from previous node\n dist_to_n[nd_cur][1] += dist_to_n[nd_prv][1]\n # !!! careful !!! you need to add modulo operation (as said in the task)\n dist_to_n[nd_cur][1] = int(dist_to_n[nd_cur][1] % (1e9+7))\n # step 2: End\n \n return dist_to_n[1][1] # return number of routes for 1-node", "solution_js": "var countRestrictedPaths = function(n, edges) {\n // create an adjacency list to store the neighbors with weight for each node\n const adjList = new Array(n + 1).fill(null).map(() => new Array(0));\n for (const [node1, node2, weight] of edges) {\n adjList[node1].push([node2, weight]);\n adjList[node2].push([node1, weight]);\n }\n \n // using djikstras algorithm\n // find the shortest path from n to each node\n const nodeToShortestPathDistance = {}\n const heap = new Heap();\n heap.push([n, 0])\n let numNodeSeen = 0;\n while (numNodeSeen < n) {\n const [node, culmativeWeight] = heap.pop();\n if (nodeToShortestPathDistance.hasOwnProperty(node)) {\n continue;\n }\n nodeToShortestPathDistance[node] = culmativeWeight;\n numNodeSeen++;\n for (const [neighbor, edgeWeight] of adjList[node]) {\n if (nodeToShortestPathDistance.hasOwnProperty(neighbor)) {\n continue;\n }\n heap.push([neighbor, edgeWeight + culmativeWeight]);\n }\n }\n \n\n // do a DFS caching the number of paths for each node\n // so that we don't need to redo the number of paths again\n // when we visit that node through another path\n const nodeToNumPaths = {};\n const dfs = (node) => {\n if (node === n) return 1;\n if (nodeToNumPaths.hasOwnProperty(node)) {\n return nodeToNumPaths[node];\n }\n let count = 0;\n for (const [neighbor, weight] of adjList[node]) {\n if (nodeToShortestPathDistance[node] > nodeToShortestPathDistance[neighbor]) {\n count += dfs(neighbor);\n }\n }\n return nodeToNumPaths[node] = count % 1000000007;\n }\n return dfs(1);\n};\n\nclass Heap {\n constructor() {\n this.store = [];\n }\n \n peak() {\n return this.store[0];\n }\n \n size() {\n return this.store.length;\n }\n \n pop() {\n if (this.store.length < 2) {\n return this.store.pop();\n }\n const result = this.store[0];\n this.store[0] = this.store.pop();\n this.heapifyDown(0);\n return result;\n }\n \n push(val) {\n this.store.push(val);\n this.heapifyUp(this.store.length - 1);\n }\n \n heapifyUp(child) {\n while (child) {\n const parent = Math.floor((child - 1) / 2);\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n child = parent;\n } else {\n return child;\n }\n }\n }\n \n heapifyDown(parent) {\n while (true) {\n let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n if (this.shouldSwap(child2, child)) {\n child = child2\n }\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n parent = child;\n } else {\n return parent;\n }\n }\n }\n \n shouldSwap(child, parent) {\n return child && this.store[child][1] < this.store[parent][1];\n }\n}", "solution_java": "class Solution {\n int dp[];\n //We use memoization\n public int countRestrictedPaths(int n, int[][] edges) {\n int[] dist = new int[n+1];\n dp = new int[n+1];\n Arrays.fill(dp,-1);\n Map> graph = new HashMap<>();\n //Create the graph from input edges\n for(int[] e : edges){\n graph.putIfAbsent(e[0], new HashMap<>());\n graph.putIfAbsent(e[1], new HashMap<>());\n graph.get(e[0]).put(e[1],e[2]);\n graph.get(e[1]).put(e[0],e[2]);\n }\n //Single source shortest distance - something like Dijkstra's\n PriorityQueue pq = new PriorityQueue<>((a,b)->(a[1]-b[1]));\n int[] base = new int[2];\n base[0]=n;\n pq.offer(base);\n while(!pq.isEmpty()){\n int[] currNode = pq.poll();\n\n for(Map.Entry neighbour: graph.get(currNode[0]).entrySet()){\n int node = neighbour.getKey();\n int d = neighbour.getValue()+currNode[1];\n if(node==n) continue;\n //Select only those neighbours, whose new distance is less than existing distance\n //New distance = distance of currNode from n + weight of edge between currNode and neighbour\n\n if( dist[node]==0 || d < dist[node]){\n int[] newNode = new int[2];\n newNode[0]=node;\n newNode[1]=d;\n pq.offer(newNode);\n dist[node]= d;\n }\n }\n }\n\n return find(1,graph,n,dist);\n }\n //This method traverses all the paths from source node to n though it's neigbours\n private int find(int node, Map> graph, int n, int[] dist ){\n if(node==n){\n return 1;\n }\n\n //Memoization avoid computaion of common subproblems.\n if(dp[node]!=-1) return dp[node];\n\n int ans = 0;\n for(Map.Entry neighbour: graph.get(node).entrySet()){\n int currNode = neighbour.getKey();\n int d = dist[currNode];\n if( dist[node] > d){\n ans = (ans + find(currNode, graph, n, dist)) % 1000000007;\n }\n }\n\n return dp[node] = ans;\n }\n}", "solution_c": "typedef pair pii;\nclass Solution {\npublic:\n int countRestrictedPaths(int n, vector>& edges) {\n unordered_map>> gp;\n for (auto& edge : edges) {\n gp[edge[0]].push_back({edge[1], edge[2]});\n gp[edge[1]].push_back({edge[0], edge[2]});\n }\n\n vector dist(n + 1, INT_MAX);\n priority_queue, greater > pq;\n pq.push({0, n});\n dist[n] = 0;\n\n int u, v, w;\n while (!pq.empty()) {\n pii p = pq.top(); pq.pop();\n u = p.second;\n for (auto& to : gp[u]) {\n v = to.first, w = to.second;\n if (dist[v] > dist[u] + w) {\n dist[v] = dist[u] + w;\n pq.push({dist[v], v});\n }\n }\n }\n vector dp(n + 1, -1);\n return dfs(gp, n, dp, dist);\n }\n\n int dfs(unordered_map>>& gp, int s, vector& dp, vector& dist) {\n int mod = 1e9+7;\n if (s == 1) return 1;\n if (dp[s] != -1) return dp[s];\n int sum = 0, weight, val;\n for (auto& n : gp[s]) {\n weight = dist[s];\n val = dist[n.first];\n if (val > weight) {\n sum = (sum % mod + dfs(gp, n.first, dp, dist) % mod) % mod;\n }\n }\n return dp[s] = sum % mod;\n }\n};" }, { "title": "Frequency of the Most Frequent Element", "algo_input": "The frequency of an element is the number of times it occurs in an array.\n\nYou are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.\n\nReturn the maximum possible frequency of an element after performing at most k operations.\n\n \nExample 1:\n\nInput: nums = [1,2,4], k = 5\nOutput: 3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.\n\nExample 2:\n\nInput: nums = [1,4,8,13], k = 5\nOutput: 2\nExplanation: There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n\n\nExample 3:\n\nInput: nums = [3,9,6], k = 2\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\t1 <= k <= 105\n\n", "solution_py": "class Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n sums, i, ans = 0, 0, 0\n for j in range(len(nums)):\n sums += nums[j]\n while nums[j]*(j-i+1) > sums+k:\n sums -= nums[i]\n i = i+1\n ans = max(ans, j-i+1)\n return ans", "solution_js": "var maxFrequency = function(nums, k) {\n// We sorted because as we are allowed only to increment the value & we try to increase the smaller el to some larger el\n nums.sort((a,b)=>a-b);\n \n let left=0;\n let max=Math.max(); // without any args, Math.max() is -Infinity\n let curr=0;\n\t// I have used 'for loop' so rightPtr is 'i' here\n for(let i=0;i curr+k){\n curr-=nums[left++]\n } \n max = Math.max(max,i-left+1);\n }\n return max;\n};", "solution_java": "class Solution {\n public int maxFrequency(int[] nums, int k) {\n //Step-1: Sorting->\n Arrays.sort(nums);\n //Step-2: Two-Pointers->\n int L=0,R=0;\n long totalSum=0;\n int res=1;\n //Iterating over the array:\n while(R=\" \"windowSize*nums[R]\"\n //then only the window is possible else decrease the \"totalSum\"\n //till the value \"totalSum+k\" is \">=\" \"windowSize*nums[R]\"\n while(! ((totalSum+k) >= ((R-L+1)*nums[R])) )\n {\n totalSum-=nums[L];\n L++;\n }\n res=Math.max(res,(R-L+1));\n R++;\n }\n return res;\n }\n}", "solution_c": "#define ll long long\n\nclass Solution {\npublic:\n int maxFrequency(vector& nums, int k) {\n // sorting so that can easily find the optimal window\n sort(nums.begin(), nums.end());\n\n // left - left pointer of window\n // right - right pointer of window\n int left = 0, right = 0, ans = 1;\n ll total = 0, n = nums.size();\n while(right < n){\n // total - total sum of elements in the window\n total += nums[right];\n\n // Checking if the we can achieve elements in this window\n // If it exceeds k then shrinking the window by moving left pointer\n // For optimal we will make all elements in the array equal to\n // the maximum value element\n while((1ll)*(right - left + 1)*nums[right] - total > k){\n total -= nums[left];\n left++;\n }\n\n ans = max(ans, right - left + 1);\n right++;\n }\n return ans;\n }\n};" }, { "title": "Remove Invalid Parentheses", "algo_input": "Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\n\nReturn all the possible results. You may return the answer in any order.\n\n \nExample 1:\n\nInput: s = \"()())()\"\nOutput: [\"(())()\",\"()()()\"]\n\n\nExample 2:\n\nInput: s = \"(a)())()\"\nOutput: [\"(a())()\",\"(a)()()\"]\n\n\nExample 3:\n\nInput: s = \")(\"\nOutput: [\"\"]\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 25\n\ts consists of lowercase English letters and parentheses '(' and ')'.\n\tThere will be at most 20 parentheses in s.\n\n", "solution_py": "class Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n ## RC ##\n ## APPROACH : BACK-TRACKING ##\n ## Similar to Leetcode 32. Longest Valid Parentheses ##\n ## LOGIC ##\n # 1. use stack to find invalid left and right braces.\n # 2. if its close brace at index i , you can remove it directly to make it valid and also you can also remove any of the close braces before that i.e in the range [0,i-1]\n # 3. similarly for open brace, left over at index i, you can remove it or any other open brace after that i.e [i+1, end]\n # 4. if left over braces are more than 1 say 2 close braces here, you need to make combinations of all 2 braces before that index and find valid parentheses.\n # 5. so, we count left and right invalid braces and do backtracking removing them\n \n\t\t## TIME COMPLEXITY : O(2^N) ## (each brace has 2 options: exits or to be removed)\n\t\t## SPACE COMPLEXITY : O(N) ##\n\n def isValid(s):\n stack = []\n for i in range(len(s)):\n if( s[i] == '(' ):\n stack.append( (i,'(') )\n elif( s[i] == ')' ):\n if(stack and stack[-1][1] == '('):\n stack.pop()\n else:\n stack.append( (i,')') ) # pushing invalid close braces also\n return len(stack) == 0, stack\n \n \n def dfs( s, left, right):\n visited.add(s)\n if left == 0 and right == 0 and isValid(s)[0]: res.append(s)\n for i, ch in enumerate(s):\n if ch != '(' and ch != ')': continue # if it is any other char ignore.\n if (ch == '(' and left == 0) or (ch == ')' and right == 0): continue # if left == 0 then removing '(' will only cause imbalance. Hence, skip.\n if s[:i] + s[i+1:] not in visited:\n dfs( s[:i] + s[i+1:], left - (ch == '('), right - (ch == ')') )\n \n stack = isValid(s)[1]\n lc = sum([1 for val in stack if val[1] == \"(\"]) # num of left braces\n rc = len(stack) - lc\n \n res, visited = [], set()\n dfs(s, lc, rc)\n return res", "solution_js": "var removeInvalidParentheses = function(s) {\n const isValid = (s) => {\n const stack = [];\n for(let c of s) {\n if(c == '(') stack.push(c);\n else if(c == ')') {\n if(stack.length && stack.at(-1) == '(')\n stack.pop();\n else return false;\n }\n }\n return stack.length == 0;\n }\n\n const Q = [s], vis = new Set([s]), ans = [];\n let found = false;\n while(Q.length) {\n const top = Q.shift();\n if(isValid(top)) {\n ans.push(top);\n found = true;\n }\n if(found) continue;\n for(let i = 0; i < top.length; i++) {\n if(!'()'.includes(top[i])) continue;\n\n const str = top.slice(0, i) + top.slice(i + 1);\n if(!vis.has(str)) {\n Q.push(str);\n vis.add(str);\n }\n }\n }\n if(ans.length == 0) return [''];\n return ans;\n};", "solution_java": "class Solution {\n public List removeInvalidParentheses(String s) {\n List ans=new ArrayList<>();\n HashSet set=new HashSet();\n \n int minBracket=removeBracket(s);\n getAns(s, minBracket,set,ans);\n \n return ans;\n }\n \n public void getAns(String s, int minBracket, HashSet set, List ans){\n if(set.contains(s)) return;\n \n set.add(s);\n \n if(minBracket==0){\n int remove=removeBracket(s); \n if(remove==0) ans.add(s);\n return;\n }\n \n for(int i=0;i stack=new Stack<>();\n \n for(int i=0;i& res, string cus, int lp, int rp, int idx) {\n if (!lp && !rp) {\n int invalid = 0;\n bool flag = true;\n for (int i = 0; i < cus.size(); i++) {\n if (cus[i] == '(')\n invalid++;\n else if (cus[i] == ')') {\n invalid--;\n if (invalid < 0) {\n flag = false;\n break;\n }\n }\n }\n if (flag)\n res.emplace_back(cus);\n return;\n }\n \n for (int i = idx; i < cus.size(); i++) {\n if (i != idx && cus[i] == cus[i - 1])\n continue;\n \n if (lp + rp > cus.size() - i)\n return;\n \n if (lp && cus[i] == '(')\n back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp - 1, rp, i);\n \n if (rp && cus[i] == ')')\n back_tracking(res, cus.substr(0, i) + cus.substr(i + 1), lp, rp - 1, i);\n }\n }\n \n vector removeInvalidParentheses(string s) {\n int left_p = 0;\n int right_p = 0;\n for (auto& ch : s) {\n if (ch == '(')\n left_p++;\n else if (ch == ')') {\n if (left_p > 0)\n left_p--;\n else\n right_p++;\n }\n }\n vector res;\n back_tracking(res, s, left_p, right_p, 0);\n return res;\n }\n};" }, { "title": "Check If Two String Arrays are Equivalent", "algo_input": "Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.\n\nA string is represented by an array if the array elements concatenated in order forms the string.\n\n \nExample 1:\n\nInput: word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\nOutput: true\nExplanation:\nword1 represents string \"ab\" + \"c\" -> \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.\n\nExample 2:\n\nInput: word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput: false\n\n\nExample 3:\n\nInput: word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput: true\n\n\n \nConstraints:\n\n\n\t1 <= word1.length, word2.length <= 103\n\t1 <= word1[i].length, word2[i].length <= 103\n\t1 <= sum(word1[i].length), sum(word2[i].length) <= 103\n\tword1[i] and word2[i] consist of lowercase letters.\n\n", "solution_py": "class Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return True if \"\".join(word1) == \"\".join(word2) else False", "solution_js": "var arrayStringsAreEqual = function(word1, word2) {\n return word1.join('') === word2.join('')\n};", "solution_java": "class Solution {\n public boolean arrayStringsAreEqual(String[] word1, String[] word2)\n {\n return(String.join(\"\", word1).equals(String.join(\"\", word2)));\n }\n}", "solution_c": "class Solution {\npublic:\n bool arrayStringsAreEqual(vector& word1, vector& word2) \n {\n int wordIdx1 = 0, wordIdx2 = 0, chIdx1 = 0, chIdx2 = 0;\n while(true)\n {\n char ch1 = word1[wordIdx1][chIdx1];\n char ch2 = word2[wordIdx2][chIdx2];\n if (ch1 != ch2) return false;\n \n chIdx1++; //incrementing the character index of current word from \"word1\"\n chIdx2++; //incrementing the character index of current word from \"word2\";\n //=========================================================\n if (chIdx1 == word1[wordIdx1].size()) //if current word from \"word1\" is over\n { \n wordIdx1++; //move to next word in \"word1\"\n chIdx1 = 0; //reset character index to 0\n }\n if (chIdx2 == word2[wordIdx2].size()) //if current word from \"word2\" is over\n { \n wordIdx2++; //move to next word in \"word2\"\n chIdx2 = 0; //reset character index to 0\n }\n //=================================================================\n if (wordIdx1 == word1.size() && wordIdx2 == word2.size()) break; // words in both arrays are finished\n \n if (wordIdx1 == word1.size() || wordIdx2 == word2.size()) return false;\n //if words in any onr of the arrays are finished and other still has some words in it\n //then there is no way same string could be formed on concatenation\n }\n return true; \n }\n};" }, { "title": "Word Subsets", "algo_input": "You are given two string arrays words1 and words2.\n\nA string b is a subset of string a if every letter in b occurs in a including multiplicity.\n\n\n\tFor example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\".\n\n\nA string a from words1 is universal if for every string b in words2, b is a subset of a.\n\nReturn an array of all the universal strings in words1. You may return the answer in any order.\n\n \nExample 1:\n\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\nOutput: [\"facebook\",\"google\",\"leetcode\"]\n\n\nExample 2:\n\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\nOutput: [\"apple\",\"google\",\"leetcode\"]\n\n\n \nConstraints:\n\n\n\t1 <= words1.length, words2.length <= 104\n\t1 <= words1[i].length, words2[i].length <= 10\n\twords1[i] and words2[i] consist only of lowercase English letters.\n\tAll the strings of words1 are unique.\n\n", "solution_py": "class Solution:\n def wordSubsets(self, A: List[str], B: List[str]) -> List[str]:\n freq = [0]*26 \n \n for w in B: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n for i in range(26): freq[i] = max(freq[i], temp[i])\n \n ans = []\n for w in A: \n temp = [0]*26\n for c in w: temp[ord(c)-97] += 1\n if all(freq[i] <= temp[i] for i in range(26)): ans.append(w)\n return ans ", "solution_js": "var wordSubsets = function(words1, words2) {\n this.count = Array(26).fill(0);\n let tmp = Array(26).fill(0);\n for(let b of words2){\n tmp = counter(b);\n for(let i=0; i<26; i++)\n count[i] = Math.max(count[i], tmp[i]);\n }\n let list = []\n for(let a of words1)\n if(isSub(counter(a)))\n list.push(a);\n return list;\n};\n\nfunction isSub(tmp){\n for(let i=0; i<26; i++)\n if(tmp[i] < this.count[i])\n return false;\n return true;\n};\n\nfunction counter(s){\n let tmp = Array(26).fill(0);\n for(let c of s)\n tmp[c.charCodeAt() - 97]++;\n return tmp;\n};", "solution_java": "class Solution {\n public List wordSubsets(String[] words1, String[] words2) {\n List list=new ArrayList<>();\n int[] bmax=count(\"\");\n for(String w2:words2)\n {\n int[] b=count(w2);\n for(int i=0;i<26;i++)\n {\n bmax[i]=Math.max(bmax[i],b[i]);\n }\n }\n for(String w1:words1)\n {\n int[] a=count(w1);\n for(int i=0;i<26;i++)\n {\n if(a[i] giveMeFreq(string s)\n {\n vector freq(26,0);\n for(int i = 0; i < s.length(); i++)\n {\n freq[s[i] - 'a']++;\n }\n return freq;\n }\n \n vector wordSubsets(vector& words1, vector& words2) \n {\n vector ans; // store ans\n vector max_Freq_w2(26, 0); // store max freq of each character present in word2 stirngs\n\t \n // we will Iterate over word to and try to find max freq for each character present in all strings.\n\t\tfor(auto &x : words2) \n {\n vector freq = giveMeFreq(x);\n for(int i = 0; i < 26; i++)\n {\n max_Freq_w2[i] = max(freq[i], max_Freq_w2[i]); // upadate freq to max freq\n }\n }\n \n\t\t// we will iterate for each string in words1 ans if it have all charaters present in freq array with freq >= that then we will add it to ans\n for(auto &x : words1)\n {\n vector freq = giveMeFreq(x); // gives freq of characters for word in words1\n bool flag = true;\n for(int i = 0; i < 26; i++)\n {\n if(freq[i] < max_Freq_w2[i]) // specifies that word did not have all the characters from word2 array\n {\n flag = false;\n break;\n }\n }\n if(flag) ans.push_back(x); // string x is Universal string\n }\n return ans;\n }\n};" }, { "title": "Distant Barcodes", "algo_input": "In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].\n\nRearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.\n\n \nExample 1:\nInput: barcodes = [1,1,1,2,2,2]\nOutput: [2,1,2,1,2,1]\nExample 2:\nInput: barcodes = [1,1,1,1,2,2,3,3]\nOutput: [1,3,1,3,1,2,1,2]\n\n \nConstraints:\n\n\n\t1 <= barcodes.length <= 10000\n\t1 <= barcodes[i] <= 10000\n\n", "solution_py": "import heapq\n\nclass Solution:\n\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n barcodes_counter = Counter(barcodes)\n if len(barcodes_counter) == len(barcodes):\n return barcodes\n\n barcodes_heapq = [ (-c, b) for b, c in barcodes_counter.items() ]\n heapq.heapify(barcodes_heapq)\n\n idx, prev_count, prev_barcode = 0, 0, 0\n while barcodes_heapq:\n (curr_count, curr_barcode) = heapq.heappop(barcodes_heapq)\n\n barcodes[idx] = curr_barcode\n idx += 1\n curr_count += 1\n\n if prev_count:\n heapq.heappush(barcodes_heapq, (prev_count, prev_barcode))\n\n prev_count, prev_barcode = curr_count, curr_barcode\n\n return barcodes", "solution_js": "var rearrangeBarcodes = function(barcodes) {\n var result = [];\n var map = new Map();\n barcodes.forEach(n => map.set(n, map.get(n) + 1 || 1));\n let list = [...map.entries()].sort((a,b) => {return b[1]-a[1]})\n let i = 0; //list[i][0]=>number list[i][1]=>count of this number\n while(result.length!==barcodes.length){\n if(list[i][1]>0) result.push(list[i][0]), list[i][1]--;\n i++;\n if(list[i]===undefined) i = 0;\n if(list[0][1]-list[i][1]>=1&&result[result.length-1]!==list[0][0]) i = 0;\n } //list has sorted, so list[0] appeared most frequent\n return result;\n};", "solution_java": "class Solution {\n public int[] rearrangeBarcodes(int[] barcodes) {\n \n if(barcodes.length <= 2){\n return barcodes ; //Problem says solution always exist.\n }\n \n Map count = new HashMap<>();\n Integer maxKey = null; // Character having max frequency\n \n for(int i: barcodes){\n count.put(i, count.getOrDefault(i, 0) + 1);\n if(maxKey == null || count.get(i) > count.get(maxKey)){\n maxKey = i;\n }\n }\n \n int pos = 0;\n \n //Fill maxChar\n int curr = count.get(maxKey);\n while(curr-- > 0){\n barcodes[pos] = maxKey;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n \n count.remove(maxKey); // Since that character is done, we don't need to fill it again\n \n //Fill the remaining Characters.\n for(int key: count.keySet()){\n curr = count.get(key);\n \n while(curr-- > 0){\n barcodes[pos] = key;\n pos += 2;\n if(pos >= barcodes.length){\n pos = 1;\n }\n }\n }\n \n return barcodes;\n }\n}", "solution_c": "class Solution {\npublic:\n struct comp{\n bool operator()(pair&a, pair&b){\n return a.first < b.first;\n }\n };\n \n vector rearrangeBarcodes(vector& barcodes) {\n unordered_map hmap;\n int n = barcodes.size();\n if(n==1)return barcodes;\n \n for(auto &bar : barcodes){\n hmap[bar]++;\n }\n \n vector ans;\n priority_queue, vector>, comp> pq;\n \n for(auto &it : hmap){\n pq.push({it.second, it.first});\n }\n \n while(pq.size()>1){\n \n auto firstBar = pq.top();\n pq.pop();\n \n auto secondBar = pq.top();\n pq.pop();\n \n ans.push_back(firstBar.second);\n ans.push_back(secondBar.second);\n \n --firstBar.first;\n --secondBar.first;\n \n if(firstBar.first > 0){\n pq.push(firstBar);\n }\n \n if(secondBar.first > 0){\n pq.push(secondBar);\n }\n }\n \n if(pq.size()){\n ans.push_back(pq.top().second);\n pq.pop();\n }\n \n return ans;\n }\n};" }, { "title": "Shift 2D Grid", "algo_input": "Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.\n\nIn one shift operation:\n\n\n\tElement at grid[i][j] moves to grid[i][j + 1].\n\tElement at grid[i][n - 1] moves to grid[i + 1][0].\n\tElement at grid[m - 1][n - 1] moves to grid[0][0].\n\n\nReturn the 2D grid after applying shift operation k times.\n\n \nExample 1:\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[9,1,2],[3,4,5],[6,7,8]]\n\n\nExample 2:\n\nInput: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n\n\nExample 3:\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput: [[1,2,3],[4,5,6],[7,8,9]]\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m <= 50\n\t1 <= n <= 50\n\t-1000 <= grid[i][j] <= 1000\n\t0 <= k <= 100\n\n", "solution_py": "class Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0])\n cache = []\n for i in range(m):\n for j in range(n):\n cache.append(grid[i][j])\n \n k %= len(cache)\n new_vals = cache[-k:] + cache[:-k]\n \n cur = 0\n for i in range(m):\n for j in range(n):\n grid[i][j] = new_vals[cur]\n cur += 1\n \n return grid", "solution_js": "/**\n * @param {number[][]} grid\n * @param {number} k\n * @return {number[][]}\n */\nvar shiftGrid = function(grid, k) {\n\n let m = grid.length\n let n = grid[0].length\n\n for (let r = 0; r < k; r++) {\n const newGrid = Array(m).fill(\"X\").map(() => Array(n).fill(\"X\"))\n for (let i = 0; i < m; i++) {\n for (let j = 1; j < n; j++) {\n newGrid[i][j] = grid[i][j-1]\n }\n }\n\n for (let i = 1; i < m; i++) {\n newGrid[i][0] = grid[i-1][n-1]\n }\n\n newGrid[0][0] = grid[m-1][n-1]\n\n //copy the new grid for the next iteration\n grid = newGrid\n }\n\n return grid\n\n};", "solution_java": "class Solution {\n public List> shiftGrid(int[][] grid, int k) {\n // just bruteforce??? O(i*j*k)\n // instead we calculate the final position at once!\n \n int m = grid.length; // row\n int n = grid[0].length; // column\n \n int[][] arr = new int[m][n];\n \n // Since moving m*n times will result in same matrix, we do this:\n k = k % (m*n);\n \n // Then we move each element\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // for calculating column, it back to the original position\n // every n steps\n int column = (j + k) % n;\n \n // for calculating row, we move to the next row each time\n // it exceed the last element on the current row.\n // For example when 2 moves k=5 steps it turns to the (+2) row.\n // Thus it's original row + ((original column + steps) / n)\n // But if 2 moves k=8 steps it turns to the (0,0),\n // and row + ((original column + steps) / n) gives 0+(9/3)=3 (out of bounds)\n // so we'll need to % number of rows to get 0. (circle back)\n int row = (i + ((j + k) / n)) % m;\n arr[row][column] = grid[i][j];\n }\n }\n return (List) Arrays.asList(arr);\n }\n}", "solution_c": "class Solution {\npublic:\n vector> shiftGrid(vector>& grid, int k) {\n \n dequedq;\n \n for(int i=0;i int:\n res, count, n = 0, 1, len(s)\n for i in range(1,n):\n if s[i]==s[i-1]:\n count+=1\n else:\n if count>1:\n res+=(count*(count-1)//2)\n count=1 \n if count>1:\n res+=(count*(count-1)//2)\n return (res+n)%(10**9+7)", "solution_js": "var countHomogenous = function(s) {\n let mod = 1e9 + 7\n let n = s.length\n let j=0, res = 0\n \n for(let i=0; i0 && s[i-1] != s[i]){\n let x = i-j\n res += x*(x+1) / 2\n j = i\n }\n }\n \n let x = n-j\n res += x*(x+1) / 2\n\n return res%mod\n};", "solution_java": "class Solution {\n public int countHomogenous(String s) {\n int res = 1;\n int carry = 1;\n int mod = 1000000007;\n for(int i =1;i constructRectangle(int area)\n {\n int sq = sqrt(area);\n while (sq > 1)\n {\n if (area % sq == 0)\n break;\n sq--;\n }\n return {area / sq, sq};\n }\n};" }, { "title": "Complex Number Multiplication", "algo_input": "A complex number can be represented as a string on the form \"real+imaginaryi\" where:\n\n\n\treal is the real part and is an integer in the range [-100, 100].\n\timaginary is the imaginary part and is an integer in the range [-100, 100].\n\ti2 == -1.\n\n\nGiven two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.\n\n \nExample 1:\n\nInput: num1 = \"1+1i\", num2 = \"1+1i\"\nOutput: \"0+2i\"\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n\n\nExample 2:\n\nInput: num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput: \"0+-2i\"\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n\n\n \nConstraints:\n\n\n\tnum1 and num2 are valid complex numbers.\n\n", "solution_py": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n i1=num1.index('+')\n i2=num2.index('+')\n a=int(num1[0:i1])\n x=int(num2[0:i2])\n b=int(num1[i1+1:len(num1)-1])\n y=int(num2[i2+1:len(num2)-1])\n ans1=a*x+(-1)*b*y\n ans2=a*y+b*x\n return str(ans1)+'+'+(str(ans2)+'i')", "solution_js": "var complexNumberMultiply = function(num1, num2) {\n\tlet [realA, imaginaryA] = num1.split('+');\n\tlet [realB, imaginaryB] = num2.split('+');\n\timaginaryA = parseInt(imaginaryA);\n\timaginaryB = parseInt(imaginaryB);\n\tconst real = realA * realB - imaginaryA * imaginaryB;\n\tconst imaginary = realA * imaginaryB + imaginaryA * realB;\n\n\treturn `${real}+${imaginary}i`;\n};", "solution_java": "class Solution {\n public String complexNumberMultiply(String num1, String num2) {\n int val1 = Integer.parseInt(num1.substring(0, num1.indexOf('+')));\n int val2 = Integer.parseInt(num1.substring(num1.indexOf('+')+1,num1.length()-1));\n int val3 = Integer.parseInt(num2.substring(0, num2.indexOf('+')));\n int val4 = Integer.parseInt(num2.substring(num2.indexOf('+')+1,num2.length()-1));\n \n return \"\" + (val1*val3 - val2*val4) + \"+\" + (val1*val4 + val3*val2) + \"i\";\n }\n}", "solution_c": "class Solution {\npublic: \n pair seprateRealAndImg(string &s){\n int i = 0;\n string real,img;\n while(s[i] != '+') real += s[i++];\n while(s[++i] != 'i') img += s[i];\n \n return {stoi(real),stoi(img)};\n }\n string complexNumberMultiply(string num1, string num2) {\n pair x = seprateRealAndImg(num1);\n pair y = seprateRealAndImg(num2);\n \n int a1 = x.first,b1 = x.second;\n int a2 = y.first,b2 = y.second;\n \n int real = (a1 * a2) - (b1*b2);\n int img = (b1*a2) + (a1 * b2);\n \n return to_string(real) + \"+\" + to_string(img) + \"i\";\n }\n};" }, { "title": "Palindrome Partitioning III", "algo_input": "You are given a string s containing lowercase letters and an integer k. You need to :\n\n\n\tFirst, change some characters of s to other lowercase English letters.\n\tThen divide s into k non-empty disjoint substrings such that each substring is a palindrome.\n\n\nReturn the minimal number of characters that you need to change to divide the string.\n\n \nExample 1:\n\nInput: s = \"abc\", k = 2\nOutput: 1\nExplanation: You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n\n\nExample 2:\n\nInput: s = \"aabbc\", k = 3\nOutput: 0\nExplanation: You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n\nExample 3:\n\nInput: s = \"leetcode\", k = 8\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= k <= s.length <= 100.\n\ts only contains lowercase English letters.\n\n", "solution_py": "class Solution:\n def palindromePartition(self, s: str, t: int) -> int:\n n=len(s)\n @lru_cache(None)\n def is_palin(s): #This function returns min no of chars to change to make s as a palindrome\n cnt=0\n for c1,c2 in zip(s,s[::-1]):\n if c1!=c2: cnt+=1\n if len(s)%2==0:\n return cnt//2\n return (cnt+1)//2\n @lru_cache(None)\n def dp(i,j,k): #We analyse string s[i:j+1] with k divisions left\n if j==n:\n return 0 if k==0 else sys.maxsize\n if k==0: \n return sys.maxsize\n ans=sys.maxsize\n cnt=is_palin(s[i:j+1])\n #terminate here\n ans=min(ans,dp(j+1,j+1,k-1)+cnt)\n #dont terminate\n ans=min(ans,dp(i,j+1,k))\n return ans\n return dp(0,0,t)\n \n \n ", "solution_js": "var palindromePartition = function(s, k) {\n const len = s.length;\n\n const cost = (i = 0, j = 0) => {\n let c = 0;\n while(i <= j) {\n if(s[i] != s[j]) c++;\n i++, j--;\n }\n return c;\n }\n\n const dp = Array.from({ length: len }, () => {\n return new Array(k + 1).fill(-1);\n })\n\n const splitHelper = (idx = 0, sl = k) => {\n if(sl < 0) return Infinity;\n if(idx == len) {\n if(sl == 0) return 0;\n return Infinity;\n }\n\n if(dp[idx][sl] != -1) return dp[idx][sl];\n\n let ans = Infinity;\n\n for(let i = idx; i < len; i++) {\n ans = Math.min(ans, splitHelper(i + 1, sl - 1) + cost(idx, i));\n }\n return dp[idx][sl] = ans;\n }\n\n return splitHelper();\n};", "solution_java": "class Solution {\n public int mismatchCount(String s) {\n int n = s.length()-1;\n int count = 0;\n for(int i=0,j=n;i=n)\n return 105;\n if(k<0)\n return 105;\n if(dp[i][j][k] != null) {\n return dp[i][j][k];\n }\n if(n-j List[int]:\n ans=[]\n def post(root):\n nonlocal ans\n if not root:\n return\n for i in root.children:\n post(i)\n ans.append(root.val)\n post(root)\n return ans", "solution_js": "var postorder = function(root) {\n const res = [];\n function post(node) {\n if (!node) return;\n for (let child of node.children) {\n post(child);\n }\n res.push(node.val);\n }\n post(root);\n return res;\n};", "solution_java": "class Solution {\n List result = new ArrayList<>();\n public List postorder(Node root) {\n addNodes(root);\n return result;\n }\n \n void addNodes(Node root) {\n if (root == null) return;\n for (Node child : root.children) addNodes(child);\n result.add(root.val);\n }\n}", "solution_c": " class Solution {\npublic:\n void solve(Node*root,vector&ans){\n if(root==NULL)return;\n for(int i=0;ichildren.size();i++){\n solve(root->children[i],ans);\n }\n ans.push_back(root->val);\n }\n vector postorder(Node* root) {\n vectorans;\n solve(root,ans);\n return ans;\n }\n\t\t" }, { "title": "Find the Kth Smallest Sum of a Matrix With Sorted Rows", "algo_input": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.\n\nYou are allowed to choose exactly one element from each row to form an array.\n\nReturn the kth smallest array sum among all possible arrays.\n\n \nExample 1:\n\nInput: mat = [[1,3,11],[2,4,6]], k = 5\nOutput: 7\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\n\n\nExample 2:\n\nInput: mat = [[1,3,11],[2,4,6]], k = 9\nOutput: 17\n\n\nExample 3:\n\nInput: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput: 9\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat.length[i]\n\t1 <= m, n <= 40\n\t1 <= mat[i][j] <= 5000\n\t1 <= k <= min(200, nm)\n\tmat[i] is a non-decreasing array.\n\n", "solution_py": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n def kSmallestPairs(nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n h = [(nums1[0]+nums2[0],0,0)]\n visited = set()\n res = []\n while h and k > 0:\n e, i, j = heappop(h)\n if (i,j) in visited: continue\n res.append(e)\n visited.add((i,j))\n if j+1 < len(nums2):\n heappush(h,(nums1[i]+nums2[j+1],i,j+1))\n if i+1 < len(nums1):\n heappush(h,(nums1[i+1]+nums2[j],i+1,j))\n k -= 1\n return res\n res = mat[0]\n for i in range(1, len(mat)):\n res = kSmallestPairs(res, mat[i], k)\n return res[-1]", "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number}\n */\nvar kthSmallest = function(mat, k) {\n var m = mat.length;\n var n = m ? mat[0].length : 0;\n if (!m || !n) return -1;\n var sums = [0];\n for (var idx = 0; idx < m; idx++) {\n var newSums = []\n for (var sum of sums) {\n for (var i = 0; i < n && i < k; i++) {\n var newSum = sum + mat[idx][i];\n if (newSums.length < k) {\n newSums.push(newSum);\n } else if (newSum < newSums[k-1]) {\n newSums.pop();\n newSums.push(newSum);\n } else {\n break;\n }\n newSums.sort((a, b) => a - b);\n }\n }\n sums = newSums;\n }\n return sums[k-1];\n};", "solution_java": "class Solution {\n public int kthSmallest(int[][] mat, int k) {\n int[] row = mat[0];\n \n for(int i=1; i list = new ArrayList<>();\n PriorityQueue minHeap = new PriorityQueue<>((a,b) -> (a[0]+a[1]) - (b[0]+b[1]));\n \n for(int i=0; ii).toArray();\n }\n}", "solution_c": "class Solution {\npublic:\nvector kSmallestPairs(vector& nums1, vector& nums2, int k) {\n auto cmp = [&nums1,&nums2](pair a, pairb){\n return nums1[a.first]+nums2[a.second] >\n nums1[b.first]+nums2[b.second];\n };\n int n = nums1.size();\n int m = nums2.size();\n vector ans;\n if(n==0 || m==0)\n return ans;\n priority_queue,vector>,decltype(cmp)>pq(cmp);\n pq.push({0,0});\n while(k-- && !pq.empty())\n {\n int i = pq.top().first;\n int j = pq.top().second;\n pq.pop();\n \n if(j+1>& mat, int k) {\n vector nums1 = mat[0];\n int n = mat.size();\n for(int i = 1; i int:\n ans=0\n fruitdict=defaultdict()\n stack=[]\n i,j=0,0\n\n while jfruitdict[stack[1]] :\n i = fruitdict[stack[1]]+1\n del fruitdict[stack[1]]\n stack.pop()\n else:\n i = fruitdict[stack[0]]+1\n del fruitdict[stack[0]] \n stack.pop(0) \n \n ans=max(ans,j-i)\n return ans", "solution_js": "var totalFruit = function(fruits) {\n let myFruits = {};\n let n = fruits.length;\n let windowStart = 0;\n let ans = -Number.MAX_VALUE;\n \n for(let windowEnd = 0; windowEnd < n; windowEnd++) {\n let fruit = fruits[windowEnd];\n \n if(fruit in myFruits) {\n myFruits[fruit]++;\n }\n else {\n myFruits[fruit] = 1;\n }\n \n while(Object.keys(myFruits).length > 2) {\n let throwOut = fruits[windowStart];\n myFruits[throwOut]--;\n if(myFruits[throwOut] == 0) {\n delete myFruits[throwOut];\n }\n windowStart++;\n }\n ans = Math.max(ans, windowEnd - windowStart + 1);\n }\n return ans;\n};", "solution_java": "class Solution {\n public int totalFruit(int[] fruits) {\n if (fruits == null || fruits.length == 0) {\n return 0;\n }\n int start = 0, end = 0, res = 0;\n HashMap map = new HashMap<>(); //key = type of fruit on tree, value = last index / newest index of that fruit\n\n while (end < fruits.length) {\n if (map.size() <= 2) {\n map.put(fruits[end], end);\n end++;\n }\n\n if (map.size() > 2) {\n int leftMost = fruits.length;\n for (int num : map.values()) {\n leftMost = Math.min(leftMost, num);\n }\n map.remove(fruits[leftMost]);\n start = leftMost + 1;\n }\n\n res = Math.max(res, end - start);\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int totalFruit(vector& fruits) {\n int i=0, j=0, ans = 1;\n unordered_mapmp;\n while(j2){\n while(mp.size()>2){\n mp[fruits[i]]--;\n if(mp[fruits[i]]==0)\n mp.erase(fruits[i]);\n i++;\n }\n if(mp.size()==2){\n ans = max(ans, j-i+1);\n }\n j++;\n }\n }\n return ans;\n }\n};" }, { "title": "Convert 1D Array Into 2D Array", "algo_input": "You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.\n\nThe elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.\n\nReturn an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.\n\n \nExample 1:\n\nInput: original = [1,2,3,4], m = 2, n = 2\nOutput: [[1,2],[3,4]]\nExplanation: The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\n\n\nExample 2:\n\nInput: original = [1,2,3], m = 1, n = 3\nOutput: [[1,2,3]]\nExplanation: The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.\n\n\nExample 3:\n\nInput: original = [1,2], m = 1, n = 1\nOutput: []\nExplanation: There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n\n\n \nConstraints:\n\n\n\t1 <= original.length <= 5 * 104\n\t1 <= original[i] <= 105\n\t1 <= m, n <= 4 * 104\n\n", "solution_py": "class Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []\n ", "solution_js": "var construct2DArray = function(original, m, n) {\n if (original.length !== (m*n)) return []\n let result = []\n let arr = []\n for (let i = 0; i < original.length; i++){\n arr.push(original[i])\n if (arr.length === n){\n result.push(arr)\n arr = []\n }\n }\n return result\n};", "solution_java": "class Solution {\n public int[][] construct2DArray(int[] original, int m, int n) { \n if (original.length != m * n) return new int[0][];\n \n int[][] ans = new int[m][n];\n int currRow = 0, currCol = 0;\n \n for (int num : original) {\n ans[currRow][currCol++] = num;\n \n if (currCol == n) {\n currCol = 0;\n currRow++;\n }\n }\n \n return ans;\n }\n}\n\n// TC: O(n), SC: O(m * n)", "solution_c": "class Solution {\npublic:\n vector> construct2DArray(vector& original, int m, int n) {\n if (m * n != original.size()) return {};\n\n vector> res;\n for (int i = 0; i < m*n; i+=n)\n res.push_back(vector(original.begin()+i, original.begin()+i+n));\n\n return res;\n }\n};" }, { "title": "Integer Replacement", "algo_input": "Given a positive integer n, you can apply one of the following operations:\n\n\n\tIf n is even, replace n with n / 2.\n\tIf n is odd, replace n with either n + 1 or n - 1.\n\n\nReturn the minimum number of operations needed for n to become 1.\n\n \nExample 1:\n\nInput: n = 8\nOutput: 3\nExplanation: 8 -> 4 -> 2 -> 1\n\n\nExample 2:\n\nInput: n = 7\nOutput: 4\nExplanation: 7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1\n\n\nExample 3:\n\nInput: n = 4\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def integerReplacement(self, n: int) -> int:\n dp = {}\n def dfs(num):\n if num == 1:\n return 0\n\n if num in dp:\n return dp[num]\n\n # if num is even, we have only one option -> n / 2\n even = odd = 0\n if num % 2 == 0:\n even = 1 + dfs(num // 2)\n else:\n # if num is odd, we have two option, either we increment the num or decrement the num\n odd1 = 1 + dfs(num - 1)\n odd2 = 1 + dfs(num + 1)\n # take the min of both operation\n odd = min(odd1, odd2)\n\n dp[num] = even + odd\n return dp[num]\n\n return dfs(n)", "solution_js": "var integerReplacement = function(n) {\n let count=0;\n while(n>1){\n if(n%2===0){n/=2;}\n else{\n if(n!==3 && (n+1)%4===0){n++;}\n else{n--;}\n } \n count++; \n }\n return count; \n}; ", "solution_java": "class Solution {\n public int integerReplacement(int n) {\n return (int)calc(n,0);\n }\n public long calc(long n,int i){\n if(n==1) \n return i;\n if(n<1) \n return 0;\n \n long a=Long.MAX_VALUE,b=Long.MAX_VALUE,c=Long.MAX_VALUE;\n \n if(n%2==0) \n a=calc(n/2,i+1);\n else{\n b=calc(n-1,i+1);\n c=calc(n+1,i+1);\n }\n long d=Math.min(a,Math.min(b,c));\n return d;\n }\n}", "solution_c": "class Solution {\npublic:\n int integerReplacement(int n) {\n\n return helper(n);\n }\n\n int helper(long n)\n {\n if(n == 1)\n return 0;\n\n if(n % 2)\n return 1 + min(helper(n - 1), helper(n + 1));\n\n return 1 + helper(n / 2);\n }\n};" }, { "title": "Root Equals Sum of Children", "algo_input": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.\n\nReturn true if the value of the root is equal to the sum of the values of its two children, or false otherwise.\n\n \nExample 1:\n\nInput: root = [10,4,6]\nOutput: true\nExplanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.\n\n\nExample 2:\n\nInput: root = [5,3,1]\nOutput: false\nExplanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.\n\n\n \nConstraints:\n\n\n\tThe tree consists only of the root, its left child, and its right child.\n\t-100 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)", "solution_js": "var checkTree = function(root) {\n return root.val === root.left.val + root.right.val;\n};", "solution_java": "class Solution\n{\n public boolean checkTree(TreeNode root)\n {\n return root.val == root.left.val + root.right.val; // O(1)\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkTree(TreeNode* root) {\n if(root->left->val+root->right->val==root->val){\n return true;\n }\n return false;\n }\n};" }, { "title": "Concatenated Words", "algo_input": "Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.\n\nA concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.\n\n \nExample 1:\n\nInput: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\nOutput: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\nExplanation: \"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n\"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n\"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".\n\nExample 2:\n\nInput: words = [\"cat\",\"dog\",\"catdog\"]\nOutput: [\"catdog\"]\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 104\n\t1 <= words[i].length <= 30\n\twords[i] consists of only lowercase English letters.\n\tAll the strings of words are unique.\n\t1 <= sum(words[i].length) <= 105\n\n", "solution_py": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n \n set_words = set(words)\n\n def check(word, seen):\n if word == '':\n return True\n for i in range(len(word) if seen else len(word) - 1):\n if word[:i+1] in set_words:\n if check(word[i+1:], seen | {word[:i+1]}):\n return True\n return False\n\n return [word for word in words if check(word, set())]", "solution_js": "class Node {\n val;\n children;\n isWord = false;\n constructor(val) {\n this.val = val;\n }\n\n}\nclass Trie {\n nodes = Array(26);\n addWord(w) {\n let idx = this.getIdx(w[0]);\n let node = this.nodes[idx] || new Node(w[0]);\n this.nodes[idx] = node;\n for (let i=1; i < w.length; ++i) {\n node.children = node.children || Array(26);\n idx = this.getIdx(w[i]);\n let childNode = node.children[idx] || new Node(w[i]);\n node.children[idx] = childNode;\n node = childNode;\n }\n\n node.isWord = true;\n }\n\n getExistingWords(w, start) {\n const rslt = [];\n let node = {children: this.nodes};\n for (let i=start; i < w.length; ++i) {\n node = (node.children || [])[this.getIdx(w[i])];\n if (!node) {\n break;\n }\n\n if (node.isWord) {\n rslt.push(i-start+1);\n }\n }\n\n return rslt;\n }\n\n getIdx(ch) {\n return ch.charCodeAt(0) - \"a\".charCodeAt(0);\n }\n}\n\nvar findAllConcatenatedWordsInADict = function(words) {\n const rslt = [];\n words = words.sort((a,b) => a.length-b.length);\n let start = 0;\n if (words[0].length === 0) {\n ++start;\n }\n const tr = new Trie();\n for (let i = start; i < words.length; ++i) {\n if (check(words[i], 0, tr, Array(words[i].length))) {\n rslt.push(words[i]);\n }\n tr.addWord(words[i]);\n }\n\n return rslt;\n};\n\nfunction check(word, i, trie, dp) {\n if (i > word.length || dp[i] === false) {\n return false;\n }\n if (i === word.length || dp[i] === true) {\n return true;\n }\n const lens = trie.getExistingWords(word, i);\n if (!lens.length) {\n dp[i] = false;\n return false;\n }\n\n dp[i] = true;\n for (let l of lens) {\n if (check(word, i+l, trie, dp)) {\n return true;\n }\n }\n\n dp[i] = false;\n\n return false;\n}", "solution_java": "class Solution {\n\tSet set = new HashSet<>();\n\tSet res = new HashSet<>();\n\tint index = 0;\n public List findAllConcatenatedWordsInADict(String[] words) {\n for (String word: words) set.add(word);\n\t\tfor (String word: words) {\n\t int len = word.length();\n\t index = 0;\n\t backtrack(len, word, 0);\n }\n List list = new ArrayList<>();\n for (String word: res) list.add(word);\n return list;\n }\n\tpublic void backtrack (int len, String word, int num) {\n\t if (index == len && num >= 2) {\n res.add(word);\n }\n\t int indexCopy = index;\n\t for (int i = index + 1; i <= len; i++) {\n\t\t if (set.contains(word.substring(index, i))) {\n\t index = i;\n\t backtrack(len, word, num + 1);\n\t index = indexCopy;\n } \n }\n return;\n }\n}", "solution_c": "class Solution {\npublic:\n int checkForConcatenation( unordered_set& st, string w, int i, vector& dp){\n if(i == w.size()) return 1;\n if(dp[i] != -1) return dp[i];\n for(int j = i; j < w.size(); ++j ){\n string t = w.substr(i, j-i+1);\n if(t.size() != w.size() && st.find(t) != st.end()){\n if(checkForConcatenation(st, w, j+1, dp)) return dp[i] = 1;\n }\n }\n return dp[i] = 0;\n }\n \n vector findAllConcatenatedWordsInADict(vector& words) {\n vector ans;\n unordered_set st;\n for(auto w: words) st.insert(w);\n for(auto w: words){\n vector dp(w.size(), -1);\n if(checkForConcatenation(st, w, 0, dp)) ans.push_back(w);\n }\n return ans;\n }\n};" }, { "title": "K-Similar Strings", "algo_input": "Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.\n\nGiven two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.\n\n \nExample 1:\n\nInput: s1 = \"ab\", s2 = \"ba\"\nOutput: 1\n\n\nExample 2:\n\nInput: s1 = \"abc\", s2 = \"bca\"\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= s1.length <= 20\n\ts2.length == s1.length\n\ts1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.\n\ts2 is an anagram of s1.\n\n", "solution_py": "class Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n n = len(s1)\n \n def helper(i, curr, dp):\n if curr == s2:\n return 0\n \n if curr not in dp[i]:\n if curr[i] == s2[i]:\n dp[i][curr] = helper(i+1, curr, dp)\n else:\n temp = sys.maxsize\n for j in range(i+1, n):\n if curr[j] == s2[i]:\n temp = min(temp, 1+helper(i+1, curr[:i]+curr[j]+curr[i+1:j]+curr[i]+curr[j+1:], dp))\n\n dp[i][curr] = temp\n return dp[i][curr]\n \n dp = [{} for _ in range(n)]\n return helper(0, s1, dp)", "solution_js": "var kSimilarity = function(s1, s2) {\n // abc --> bca\n // swap from 0: a !== b, find next b, swap(0,1) --> bac\n // swap from 1: a !== c, find next c, swap(1,2) --> bca\n return bfs(s1, s2); \n};\n\nconst bfs = (a,b)=>{\n if(a===b)\n return 0;\n const visited = new Set();\n const queue = [];\n queue.push([a,0,0]); // str, idx, swapCount\n while(queue.length>0)\n {\n let [s, idx, cnt] = queue.shift();\n while(s[idx]===b[idx])\n {\n idx++;\n }\n for(let j = idx+1; j{\n let arr = s.split('');\n let tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n return arr.join('');\n}", "solution_java": "class Solution {\n public int kSimilarity(String s1, String s2) {\n HashSet vis = new HashSet<>();\n \n ArrayDeque queue = new ArrayDeque<>();\n int level = 0;\n queue.add(s1);\n \n while(queue.size() > 0){\n int size = queue.size();\n for(int i=0;i getNeighbors(String rem,String s2){\n ArrayList res = new ArrayList<>();\n \n int idx = -1;\n for(int i=0;im;\n int solve(string &s1,string &s2,int i)\n {\n if(i==s1.length())\n return 0;\n if(m.find(s1)!=m.end())return m[s1];\n if(s1[i]==s2[i])\n return m[s1]=solve(s1,s2,i+1);\n int ans=1e5;\n for(int j=i+1;j None:\n if key not in self.dict:\n self.dict[key] = ([], [])\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n else:\n self.dict[key][0].append(value)\n self.dict[key][1].append(timestamp)\n \n \n def bsearch(self, nums, target):\n beg = 0\n end = len(nums)-1\n lastIndex = len(nums)-1\n \n while beg<=end:\n mid = (beg+end)//2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n end = mid-1\n elif target > nums[mid]:\n beg = mid+1\n \n \n if target < nums[mid] and mid == 0:\n return -1\n if target > nums[mid]:\n return mid\n return mid-1\n \n def get(self, key: str, timestamp: int) -> str:\n if key not in self.dict:\n return \"\"\n \n index = self.bsearch(self.dict[key][1], timestamp)\n return self.dict[key][0][index] if 0 <= index < len(self.dict[key][0]) else \"\"\n \n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)", "solution_js": "var TimeMap = function() {\n this.data = new Map();\n};\n\n/** \n * @param {string} key \n * @param {string} value \n * @param {number} timestamp\n * @return {void}\n */\nTimeMap.prototype.set = function(key, value, timestamp) {\n if(!this.data.has(key)){\n this.data.set(key, [{timestamp: timestamp, value: value}])\n } else {\n let temp_store = this.data.get(key);\n temp_store.push({timestamp: timestamp, value: value});\n this.data.set(key, temp_store);\n }\n};\n\n/** \n * @param {string} key \n * @param {number} timestamp\n * @return {string}\n */\nTimeMap.prototype.get = function(key, timestamp) {\n if(this.data.has(key)){\n const keyArray = this.data.get(key);\n \n //Optimize with binary search - Ordered by insert time, O(log n) devide and conq method (Like searching a dictionary)\n const index = keyArray.binarySearch(timestamp); \n if(keyArray[index].timestamp > timestamp){\n return ''\n }\n \n return keyArray[index].value || prev;\n }\n \n return '';\n};\n\nArray.prototype.binarySearch = function(key){\n let left = 0;\n let right = this.length - 1;\n \n while (left < right) {\n const i = Math.floor((left + right + 1) / 2);\n if (this[i].timestamp > key) {\n right = i - 1;\n } else {\n left = i;\n }\n }\n \n return left;\n}\n\n\n/** \n * Your TimeMap object will be instantiated and called as such:\n * var obj = new TimeMap()\n * obj.set(key,value,timestamp)\n * var param_2 = obj.get(key,timestamp)\n */", "solution_java": "class TimeMap {\n private Map> map;\n private final String NOT_FOUND = \"\";\n public TimeMap() {\n map = new HashMap<>();\n }\n \n public void set(String key, String value, int timestamp) {\n List entries = map.getOrDefault(key, new ArrayList<>());\n entries.add(new Entry(value, timestamp));\n map.put(key, entries);\n }\n \n public String get(String key, int timestamp) {\n List entries = map.get(key);\n if (entries == null) {\n return NOT_FOUND;\n }\n return binarySearch(entries, timestamp);\n }\n \n private String binarySearch(List entries, int timestamp) {\n int lo = 0, hi = entries.size() - 1, mid = -1;\n String ans = \"\";\n \n // Base cases - if value is not set, return empty\n if (entries.get(lo).timestamp > timestamp) {\n return NOT_FOUND;\n }\n // If timestamp is equal or greater, return the last value saved in map against this key, since that will have the largest timestamp\n else if (entries.get(hi).timestamp <= timestamp) {\n return entries.get(hi).value;\n }\n \n // Else apply binary search to get correct value\n while (lo <= hi) {\n mid = lo + (hi-lo)/2;\n Entry entry = entries.get(mid);\n // System.out.println(\"mid: \"+mid);\n if (entry.timestamp == timestamp) {\n return entry.value;\n }\n // Save ans, and look for ans on right half to find greater timestamp\n else if (entry.timestamp < timestamp) {\n ans = entry.value;\n lo = mid + 1;\n }\n else {\n hi = mid - 1;\n }\n }\n return ans;\n }\n}\n\nclass Entry {\n String value;\n int timestamp;\n \n public Entry(String value, int timestamp) {\n this.value = value;\n this.timestamp = timestamp;\n }\n}", "solution_c": "class TimeMap {\npublic:\n map>> mp;\n string Max;\n TimeMap() {\n Max = \"\";\n }\n \n void set(string key, string value, int timestamp) {\n mp[key].push_back(make_pair(timestamp,value));\n Max = max(Max,value);\n }\n \n string get(string key, int timestamp) {\n pair p = make_pair(timestamp,Max);\n int l = upper_bound(mp[key].begin(),mp[key].end(),p)-mp[key].begin();\n if(l==0){\n return \"\";\n }\n return mp[key][l-1].second;\n }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */" }, { "title": "Number of Students Doing Homework at a Given Time", "algo_input": "Given two integer arrays startTime and endTime and given an integer queryTime.\n\nThe ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].\n\nReturn the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.\n\n \nExample 1:\n\nInput: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput: 1\nExplanation: We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\n\n\nExample 2:\n\nInput: startTime = [4], endTime = [4], queryTime = 4\nOutput: 1\nExplanation: The only student was doing their homework at the queryTime.\n\n\n \nConstraints:\n\n\n\tstartTime.length == endTime.length\n\t1 <= startTime.length <= 100\n\t1 <= startTime[i] <= endTime[i] <= 1000\n\t1 <= queryTime <= 1000\n\n", "solution_py": "class Solution(object):\n def busyStudent(self, startTime, endTime, queryTime):\n res = 0\n for i in range(len(startTime)):\n if startTime[i] <= queryTime <= endTime[i]:\n res += 1\n else:\n pass\n return res", "solution_js": "var busyStudent = function(startTime, endTime, queryTime) {\n let res = 0;\n\n for (let i = 0; i < startTime.length; i++) {\n if (startTime[i] <= queryTime && endTime[i] >= queryTime) res++;\n }\n\n return res;\n};", "solution_java": "class Solution {\n public int busyStudent(int[] startTime, int[] endTime, int queryTime) {\n int count = 0;\n for (int i = 0; i < startTime.length; ++i) {\n if (queryTime>=startTime[i] && queryTime<=endTime[i]) ++count;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int busyStudent(vector& startTime, vector& endTime, int queryTime) {\n int ans = 0 ;\n for(int i = 0 ; i < size(startTime); ++i )\n if(queryTime >= startTime[i] and queryTime <= endTime[i]) ++ans ;\n \n return ans ;\n }\n};" }, { "title": "Distance Between Bus Stops", "algo_input": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.\n\nThe bus goes along both directions i.e. clockwise and counterclockwise.\n\nReturn the shortest distance between the given start and destination stops.\n\n \nExample 1:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 1\nOutput: 1\nExplanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\n\n \n\nExample 2:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 2\nOutput: 3\nExplanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\n\n\n \n\nExample 3:\n\n\n\nInput: distance = [1,2,3,4], start = 0, destination = 3\nOutput: 4\nExplanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 10^4\n\tdistance.length == n\n\t0 <= start, destination < n\n\t0 <= distance[i] <= 10^4\n", "solution_py": "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n # switch start and destination if destination is before start\n if start>destination: \n start,destination=destination,start\n #find minimum for clockwise and counterclockwise direction\n return min(sum(distance[start:destination]),sum(distance[:start]+distance[destination:]))", "solution_js": "/**\n * @param {number[]} distance\n * @param {number} start\n * @param {number} destination\n * @return {number}\n */\nlet sumArray = (arr) => {\n return arr.reduce((prev, curr) => prev + curr, 0)\n}\n\nvar distanceBetweenBusStops = function(distance, start, destination) {\n let dist = sumArray(distance.slice((start < destination)?start:destination, (start < destination)?destination:start));\n return Math.min(dist, sumArray(distance) - dist)\n};", "solution_java": "class Solution {\n public int distanceBetweenBusStops(int[] distance, int start, int destination) {\n int firstDistance = 0;\n int secondDistance = 0;\n if (start < destination) {\n //check clockwise rotation\n for (int i = start; i < destination; i++)\n firstDistance += distance[i];\n //check clockwise rotation from destination to end\n for (int i = destination; i < distance.length; i++)\n secondDistance += distance[i];\n //continues checking till start (if needed)\n for (int i = 0; i < start; i++)\n secondDistance += distance[i];\n }\n else {\n for (int i = start; i < distance.length; i++)\n firstDistance += distance[i];\n for (int i = 0; i < destination; i++)\n firstDistance += distance[i];\n for (int i = start - 1; i >= destination; i--)\n secondDistance += distance[i];\n }\n return Math.min(firstDistance, secondDistance);\n }\n}", "solution_c": "class Solution {\npublic:\n int distanceBetweenBusStops(vector& distance, int start, int destination) {\n int n = distance.size();\n if (start == destination)\n return 0;\n\n int one_way = 0;\n int i = start;\n while (i != destination) // find distance of one way\n {\n one_way += distance[i];\n i = (i+1)%n;\n }\n \n int second_way = 0;\n i = destination;\n while (i != start) // find distance of second way\n {\n second_way += distance[i];\n i = (i+1)%n;\n }\n \n return one_way int:\n\t\t# First, using XOR Bitwise Operator, we take all distinct set bits.\n z = x ^ y\n\t\t# We inicialize our answer with zero.\n ans = 0\n\t\t# Iterate while our z is not zero.\n while z:\n\t\t\t# Every iteration we add one to our answer.\n ans += 1\n\t\t\t# Using the expression z & (z - 1), we erase the lowest set bit in z.\n z &= z - 1\n return ans", "solution_js": "var hammingDistance = function(x, y) {\n x = x.toString(2).split('')\n y = y.toString(2).split('')\n \n let count = 0;\n const len = Math.max(x.length,y.length);\n\n if (x.length < y.length) {\n x = Array(len - x.length).fill('0').concat(x)\n } else {\n y = Array(len - y.length).fill('0').concat(y)\n } \n\n for (let i = 1; i <= len; i++) {\n x.at(-i) !== y.at(-i)? count++ : null \n }\n\n return count\n};", "solution_java": "class Solution {\n public int hammingDistance(int x, int y) {\n int ans=x^y;\n int count=0;\n while(ans>0){\n count+=ans&1;\n ans>>=1;\n }\n \n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int hammingDistance(int x, int y) {\n int val = (x^y);\n int ans = 0;\n for(int i = 31; i >= 0; --i){\n if(val & (1 << i)) ans++;\n }\n return ans;\n }\n};" }, { "title": "Self Dividing Numbers", "algo_input": "A self-dividing number is a number that is divisible by every digit it contains.\n\n\n\tFor example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\n\n\nA self-dividing number is not allowed to contain the digit zero.\n\nGiven two integers left and right, return a list of all the self-dividing numbers in the range [left, right].\n\n \nExample 1:\nInput: left = 1, right = 22\nOutput: [1,2,3,4,5,6,7,8,9,11,12,15,22]\nExample 2:\nInput: left = 47, right = 85\nOutput: [48,55,66,77]\n\n \nConstraints:\n\n\n\t1 <= left <= right <= 104\n\n", "solution_py": "class Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n res = []\n for num in range(left, right + 1):\n num_str = str(num)\n if '0' in num_str:\n continue\n elif all([num % int(digit_str) == 0 for digit_str in num_str]):\n res.append(num)\n return res", "solution_js": "/**\n * @param {number} left\n * @param {number} right\n * @return {number[]}\n */\nvar selfDividingNumbers = function(left, right) {\n const selfDivisibles = [];\n for (let i = left; i <= right; i++) {\n if (checkDivisibility(i)) {\n selfDivisibles.push(i);\n }\n }\n return selfDivisibles;\n};\n\nfunction checkDivisibility(num) {\n let status = true;\n let mod;\n let original = num;\n while (num !== 0) {\n mod = Math.trunc(num % 10);\n if (original % mod !== 0) {\n status = false;\n break;\n }\n num = Math.trunc(num / 10);\n }\n return status;\n}", "solution_java": "class Solution {\n public List selfDividingNumbers(int left, int right) {\n List ans= new ArrayList<>();\n while(left<=right){\n if(fun(left))\n ans.add(left); \n left++;\n }\n return ans;\n }\n boolean fun(int x){\n int k=x;\n while(k>0)\n {\n int y=k%10;\n k=k/10;\n if(y==0||x%y!=0)\n return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool check(int n){\n vector isif(10);\n for(int i = 1; i <= 9; i++){\n if(n % i == 0) isif[i] = 1;\n }\n \n while(n > 0){\n if(isif[n%10] == 0) return false;\n n /= 10;\n }\n return true;\n }\n vector selfDividingNumbers(int left, int right) {\n vector ans;\n for(int i = left; i <= right; i++){\n if(check(i)) ans.push_back(i);\n }\n return ans;\n }\n};" }, { "title": "Valid Palindrome", "algo_input": "A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.\n\nGiven a string s, return true if it is a palindrome, or false otherwise.\n\n \nExample 1:\n\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\nExplanation: \"amanaplanacanalpanama\" is a palindrome.\n\n\nExample 2:\n\nInput: s = \"race a car\"\nOutput: false\nExplanation: \"raceacar\" is not a palindrome.\n\n\nExample 3:\n\nInput: s = \" \"\nOutput: true\nExplanation: s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 2 * 105\n\ts consists only of printable ASCII characters.\n\n", "solution_py": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n cleaned = \"\"\n for c in s:\n if c.isalnum():\n cleaned += c.lower()\n return (cleaned == cleaned[::-1])\n\n ", "solution_js": "var isPalindrome = function(s) {\n const toLower = s.toLowerCase().replace(/[\\W_\\s]+/g, '').replace(/ /g, '')\n let m = 0\n let n = toLower.length - 1\n\n while (m < n) {\n if (toLower[m] !== toLower[n]) {\n return false\n }\n m++\n n--\n }\n return true\n}", "solution_java": "class Solution {\n public boolean isPalindrome(String s) {\n if(s.length()==1 || s.length()==0)\n {\n return true;\n }\n\n s=s.trim().toLowerCase();\n //s=s.toLowerCase();\n String a=\"\";\n boolean bool=false;\n for(int i=0;i='a' && s.charAt(i)<='z') || (s.charAt(i)>='0' && s.charAt(i)<='9'))\n {\n a=a+s.charAt(i);\n }\n }\n if(a.length()==1 || a.length()==0)\n {\n return true;\n }\n for(int i=0;i str:\n beg = 0\n end = len(letters)-1\n while beg <= end:\n mid = (beg+end)//2\n if letters[mid]>target:\n end = mid -1\n else:\n beg = mid +1\n return letters[beg] if begtarget){\n result.push(letter);\n }\n }\n if (result.length){\n return result[0];\n }\n else{\n return letters[0];\n }\n \n};", "solution_java": "class Solution {\n public char nextGreatestLetter(char[] letters, char target) {\n int start=0,end=letters.length-1;\n while(start<=end){\n int mid=start+(end-start)/2;\n if(letters[mid]>target){ //strictly greater is the solution we want\n end = mid-1;\n }else{\n start=mid+1;\n }\n }\n return letters[start % letters.length]; // this is the wrap around condition , we use modulo %\n }\n}", "solution_c": "class Solution {\npublic:\n char nextGreatestLetter(vector& letters, char target) {\n\n int siz = letters.size();\n bool isPresent = false;\n char ans;\n char temp = target;\n\n if (target == letters[siz-1]) return letters[0];\n\n for(int i=0; i int:\n\n\t\tfrom sortedcontainers import SortedList\n\n\t\tfor i in range(len(nums)):\n\n\t\t\tif nums[i]%2!=0:\n\t\t\t\tnums[i]=nums[i]*2\n\n\t\tnums = SortedList(nums)\n\n\t\tresult = 100000000000\n\n\t\twhile True:\n\t\t\tmin_value = nums[0]\n\t\t\tmax_value = nums[-1]\n\n\t\t\tif max_value % 2 == 0:\n\t\t\t\tnums.pop()\n\t\t\t\tnums.add(max_value // 2)\n\t\t\t\tmax_value = nums[-1]\n\t\t\t\tmin_value = nums[0]\n\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\telse:\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\t\tbreak\n\n\t\treturn result", "solution_js": "var minimumDeviation = function(nums) {\n let pq = new MaxPriorityQueue({priority: x => x})\n for (let n of nums) {\n if (n % 2) n *= 2\n pq.enqueue(n)\n }\n let ans = pq.front().element - pq.back().element\n while (pq.front().element % 2 === 0) {\n pq.enqueue(pq.dequeue().element / 2)\n ans = Math.min(ans, pq.front().element - pq.back().element)\n }\n return ans\n};", "solution_java": "class Solution {\n public int minimumDeviation(int[] nums) {\n TreeSet temp = new TreeSet<>();\n for(int i: nums){\n if(i % 2 == 0){\n temp.add(i);\n }\n else{\n temp.add(i * 2);\n }\n }\n\n int md = temp.last() - temp.first();\n int m = 0;\n\n while(temp.size() > 0 && temp.last() % 2 == 0){\n m = temp.last();\n temp.remove(m);\n temp.add(m / 2);\n\n md = Math.min(md, temp.last() - temp.first());\n }\n return md;\n }\n}", "solution_c": "\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n int minimumDeviation(vector& nums) {\n int n = nums.size();\n int mx = INT_MIN, mn = INT_MAX;\n \n // Increasing all elements to as maximum as it can and tranck the minimum,\n // number and also the resutl\n for(int i = 0; i pq;\n // Inserting into Priority queue (Max Heap) and try to decrease as much we can\n for(int i = 0; i None:\n rows = len(matrix)\n cols = len(matrix[0])\n visited=set()\n for r in range(rows):\n for c in range(cols):\n \n if matrix[r][c]==0 and (r,c) not in visited :\n for t in range(cols):\n if matrix[r][t]!=0:\n matrix[r][t]=0\n visited.add((r,t))\n for h in range(rows):\n if matrix[h][c]!=0:\n matrix[h][c]=0\n visited.add((h,c))\n ##Time Complexity :- O(m*n)\n ##Space Complexity:- O(m+n)\n\t\t\n\t\t```", "solution_js": "var setZeroes = function(matrix) {\nlet rows = new Array(matrix.length).fill(0); //to store the index of rows to be set to 0\nlet cols = new Array(matrix[0].length).fill(0);//to store the index of columns to be set to 0\nfor(let i=0; i>& matrix) {\n unordered_mapump;\n unordered_mapmp;\n for(int i=0;i str:\n cnt = Counter(s)\n return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), \"\")", "solution_js": "var greatestLetter = function(s) {\n let set=new Set(s.split(\"\"));\n\t// ASCII(A-Z, a-z)=(65-90, 97-122).\n for(let i=90; i>=65; i--){\n if(set.has(String.fromCharCode(i)) && set.has(String.fromCharCode(i+32))){\n return String.fromCharCode(i);\n }\n }\n return \"\";\n};", "solution_java": "class Solution\n{\n public String greatestLetter(String s)\n {\n Set set = new HashSet<>();\n for(char ch : s.toCharArray())\n set.add(ch);\n \n for(char ch = 'Z'; ch >= 'A'; ch--)\n if(set.contains(ch) && set.contains((char)('a'+(ch-'A'))))\n return \"\"+ch;\n return \"\";\n }\n}", "solution_c": "class Solution {\npublic:\n\n string greatestLetter(string s)\n {\n vector low(26), upp(26); //storing occurences of lower and upper case letters\n string res = \"\";\n\n for(auto it : s) //iterate over each char and mark it in respective vector\n {\n if(it-'A'>=0 && it-'A'<26)\n upp[it-'A']++;\n else\n low[it-'a']++;\n }\n\n for(int i=25; i>=0; i--) //start from greater char\n {\n if(low[i] && upp[i]) //if char found in upp and low that will be the result\n {\n res += 'A'+i;\n break;\n }\n\n }\n return res;\n }\n};" }, { "title": "Wildcard Matching", "algo_input": "Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:\n\n\n\t'?' Matches any single character.\n\t'*' Matches any sequence of characters (including the empty sequence).\n\n\nThe matching should cover the entire input string (not partial).\n\n \nExample 1:\n\nInput: s = \"aa\", p = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\n\n\nExample 2:\n\nInput: s = \"aa\", p = \"*\"\nOutput: true\nExplanation: '*' matches any sequence.\n\n\nExample 3:\n\nInput: s = \"cb\", p = \"?a\"\nOutput: false\nExplanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n\n\n \nConstraints:\n\n\n\t0 <= s.length, p.length <= 2000\n\ts contains only lowercase English letters.\n\tp contains only lowercase English letters, '?' or '*'.\n\n", "solution_py": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n m= len(s)\n n= len(p)\n\n dp = [[False]*(n+1) for i in range(m+1)]\n\n dp[0][0] = True\n\n for j in range(len(p)):\n if p[j] == \"*\":\n dp[0][j+1] = dp[0][j]\n\n for i in range(1,m+1):\n for j in range(1,n+1):\n if p[j-1] == \"*\":\n dp[i][j] = dp[i-1][j] or dp[i][j-1]\n\n elif s[i-1] == p[j-1] or p[j-1] == \"?\":\n dp[i][j] = dp[i-1][j-1]\n\n return dp[-1][-1]", "solution_js": "var isMatch = function(s, p) {\n const slen = s.length, plen = p.length;\n const dp = new Map();\n \n const solve = (si = 0, pi = 0) => {\n // both are compared and are equal till end\n if(si == slen && pi == plen) return true;\n // we have consumed are wildcard string and still s is remaining\n if(pi == plen) return false;\n // we still have wildcard characters remaining\n if(si == slen) {\n while(p[pi] == '*') pi++;\n return pi == plen;\n }\n \n const key = [si, pi].join(':');\n if(dp.has(key)) return dp.get(key);\n \n let ans = false;\n if(p[pi] == '*') {\n\t\t\t// drop * or use it\n ans = solve(si, pi + 1) || solve(si + 1, pi);\n } else {\n const match = s[si] == p[pi] || p[pi] == '?';\n if(match) ans = solve(si + 1, pi + 1); \n }\n \n dp.set(key, ans);\n \n return ans;\n }\n return solve();\n};", "solution_java": "class Solution {\n public boolean isMatch(String s, String p) {\n int i=0;\n int j=0;\n int starIdx=-1;\n int lastMatch=-1;\n\n while(i>&dp)\n {\n if(i<0 && j<0) return true;\n if(i>=0 && j<0) return false;\n if(i<0 && j>=0)\n {\n for(;j>-1;j--) if(b[j]!='*') return false;\n return true;\n }\n if(dp[i][j]!=-1) return dp[i][j];\n if(a[i]==b[j] || b[j]=='?') return dp[i][j] = match(i-1,j-1,a,b,dp);\n if(b[j]=='*') return dp[i][j] = (match(i-1,j,a,b,dp) | match(i,j-1,a,b,dp));\n return false;\n }\n bool isMatch(string s, string p) {\n int n=s.size(), m=p.size();\n vector>dp(n+1,vector(m+1,-1));\n return match(n-1,m-1,s,p,dp);\n }\n};" }, { "title": "Reverse Linked List II", "algo_input": "Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5], left = 2, right = 4\nOutput: [1,4,3,2,5]\n\n\nExample 2:\n\nInput: head = [5], left = 1, right = 1\nOutput: [5]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 <= n <= 500\n\t-500 <= Node.val <= 500\n\t1 <= left <= right <= n\n\n\n \nFollow up: Could you do it in one pass?", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n # revrese api\n def reverse(start, end):\n prev = None\n cur = start\n while prev != end:\n nextNode = cur.next\n cur.next = prev\n prev = cur\n cur = nextNode\n return prev\n \n if not head or not head.next or right <= left:\n return head\n \n start, end = head, head\n node, afterRight = 0, 0\n \n # At the begining\n if left == 1:\n # start index \n inc = left-1\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n reverse(start, end)\n head = end\n else: # Left other then begining\n # start index \n inc = left-2\n while inc > 0:\n start = start.next\n inc -= 1\n # end index\n inc = right-1\n while inc > 0:\n end = end.next\n inc -= 1\n afterRight = end.next\n begin = start # node before left\n start = start.next\n reverse(start, end)\n begin.next = end\n \n # If their's ll chain left agter right chain it to the updated ll\n if afterRight:\n start.next = afterRight\n\n return head\n \n\"\"\"\nTC : O(n)\nSc : O(1)\n\n\"\"\"", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} left\n * @param {number} right\n * @return {ListNode}\n */\n\nvar reverseBetween = function(head, left, right) {\n \n if (!head || !head.next || left === right) {\n \n return head;\n }\n \n let dummyHead = new ListNode(-1);\n\n dummyHead.next = head;\n\n let prev = dummyHead;\n\n for (let i = 1; i < left; i++) {\n \n prev = prev.next;\n }\n\n let curr = prev.next;\n\n for (let i = left; i < right; i++) {\n\n let next = curr.next;\n curr.next = next.next;\n next.next = prev.next;\n prev.next = next;\n }\n \n return dummyHead.next;\n};", "solution_java": "class Solution {\n public ListNode reverseBetween(ListNode head, int left, int right) {\n if(left==right) return head;\n ListNode last = null;\n ListNode present = head;\n \n for(int i=0; present != null && inext;\n head->next = prev;\n prev = head;\n head = temp;\n }\n return prev;\n }\n\n ListNode* reverseN(ListNode* head,int right)\n {\n ListNode* temp = head;\n while(right != 1)\n temp = temp->next,right--;\n\n ListNode* temp2 = temp->next;\n temp->next = NULL;\n\n ListNode* ans = reverse(head);\n head->next = temp2;\n return ans;\n\n }\n\n ListNode* reverseBetween(ListNode* head, int left, int right) {\n\n if(left == right)\n return head;\n\n if(left == 1)\n {\n return reverseN(head,right);\n }\n else\n {\n ListNode* temp = head;\n right--;\n while(left != 2)\n {\n temp = temp->next;\n left--;\n right--;\n }\n ListNode* temp2 = reverseN(temp->next,right);\n temp->next = temp2;\n return head;\n }\n\n return NULL;\n\n }\n};" }, { "title": "Count Operations to Obtain Zero", "algo_input": "You are given two non-negative integers num1 and num2.\n\nIn one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.\n\n\n\tFor example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.\n\n\nReturn the number of operations required to make either num1 = 0 or num2 = 0.\n\n \nExample 1:\n\nInput: num1 = 2, num2 = 3\nOutput: 3\nExplanation: \n- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.\n\n\nExample 2:\n\nInput: num1 = 10, num2 = 10\nOutput: 1\nExplanation: \n- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.\n\n\n \nConstraints:\n\n\n\t0 <= num1, num2 <= 105\n\n", "solution_py": "class Solution:\n def countOperations(self, num1: int, num2: int) -> int:\n ct=0\n while num2 and num1:\n if num1>=num2:\n num1=num1-num2\n else:\n num2=num2-num1\n ct+=1\n return ct", "solution_js": "/**\n * @param {number} num1\n * @param {number} num2\n * @return {number}\n */\nvar countOperations = function(num1, num2) {\n let count = 0;\n while (num1 !== 0 && num2 !== 0) {\n if (num1 <= num2) num2 -= num1;\n else num1 -= num2;\n count++;\n }\n return count;\n};", "solution_java": "class Solution {\n public int countOperations(int num1, int num2) {\n int count=0;\n while(num1!=0 && num2!=0){\n if(num1=num2) num1=num1-num2;\n else if(num2>num1) num2=num2-num1;\n return 1+countOperations(num1,num2);\n }\n};" }, { "title": "Delete Columns to Make Sorted", "algo_input": "You are given an array of n strings strs, all of the same length.\n\nThe strings can be arranged such that there is one on each line, making a grid. For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as:\n\nabc\nbce\ncae\n\n\nYou want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1.\n\nReturn the number of columns that you will delete.\n\n \nExample 1:\n\nInput: strs = [\"cba\",\"daf\",\"ghi\"]\nOutput: 1\nExplanation: The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.\n\n\nExample 2:\n\nInput: strs = [\"a\",\"b\"]\nOutput: 0\nExplanation: The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.\n\n\nExample 3:\n\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.\n\n\n \nConstraints:\n\n\n\tn == strs.length\n\t1 <= n <= 100\n\t1 <= strs[i].length <= 1000\n\tstrs[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n cols={}\n l=len(strs)\n l_s = len(strs[0])\n delete = set()\n for i in range(l):\n for col in range(l_s):\n if col in cols:\n if cols[col]>strs[i][col]:\n delete.add(col)\n cols[col] = strs[i][col]\n return len(delete)", "solution_js": "/**\n * @param {string[]} strs\n * @return {number}\n */\nvar minDeletionSize = function(strs) {\n let count = 0;\n for(let i=0; i strs[j+1].charAt(i)){\n count++;\n break;\n }\n }\n }\n return count;\n};", "solution_java": "class Solution {\n public int minDeletionSize(String[] strs) {\n int count = 0;\n for(int i = 0; i < strs[0].length(); i++){ //strs[0].length() is used to find the length of the column\n for(int j = 0; j < strs.length-1; j++){\n if((int) strs[j].charAt(i) <= (int) strs[j+1].charAt(i)){\n continue;\n }else{\n count++;\n break;\n }\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int minDeletionSize(vector& strs) {\n int col = strs[0].size();\n int row = strs.size();\n int count = 0;\n for(int c = 0 ; c < col ; c++){\n for(int r = 1 ; r < row ; r++){\n if(strs[r][c] - strs[r - 1][c] < 0){\n count++;\n break;\n }\n }\n }\n return count;\n }\n};" }, { "title": "Shuffle the Array", "algo_input": "Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\n\nReturn the array in the form [x1,y1,x2,y2,...,xn,yn].\n\n \nExample 1:\n\nInput: nums = [2,5,1,3,4,7], n = 3\nOutput: [2,3,5,4,1,7] \nExplanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,4,3,2,1], n = 4\nOutput: [1,4,2,3,3,2,4,1]\n\n\nExample 3:\n\nInput: nums = [1,1,2,2], n = 2\nOutput: [1,2,1,2]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 500\n\tnums.length == 2n\n\t1 <= nums[i] <= 10^3\n", "solution_py": "'''\nFirst of all, I'm making a few tuples using zip function.\nThen extracting every created tuple. (for tup in zip())\nAfter that, I can take numbers from the extracted tuples, in order to add them to a list and return. (for number in tup)\n'''\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n return [number for tup in zip(nums[:n], nums[n:]) for number in tup]", "solution_js": "var shuffle = function(nums, n) {\n while (n--) {\n nums.splice(n + 1, 0, nums.pop());\n }\n return nums;\n};", "solution_java": "class Solution {\n public int[] shuffle(int[] nums, int n)\n {\n int[] arr = new int[2*n];\n int j = 0;\n int k = n;\n for(int i =0; i<2*n; i++)\n {\n if(i%2==0)\n {\n arr[i] = nums[j];\n j++;\n }\n else\n {\n arr[i] = nums[k];\n k++;\n }\n }\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector shuffle(vector& nums, int n) {\n vector ans;\n int size = nums.size();\n int i = 0, j =0;\n for(i=0,j=n; i List[List[int]]:\n winners, losers, table = [], [], {}\n for winner, loser in matches:\n # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.\n # map.get(key, 0) returns map[key] if key exists and 0 if it does not.\n table[winner] = table.get(winner, 0) # Winner\n table[loser] = table.get(loser, 0) + 1\n for k, v in table.items(): # Player k with losses v\n if v == 0:\n winners.append(k) # If player k has no loss ie v == 0\n if v == 1:\n losers.append(k) # If player k has one loss ie v == 1\n return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.", "solution_js": "/**\n * @param {number[][]} matches\n * @return {number[][]}\n */\nvar findWinners = function(matches) {\n var looser = {};\n var allPlayer={};\n for(var i=0; i> findWinners(int[][] matches) {\n int[] won = new int[100001];\n int[] loss = new int[100001];\n \n for(int[] match : matches) {\n won[match[0]]++;\n loss[match[1]]++;\n }\n \n // System.out.print(Arrays.toString(won));\n // System.out.print(Arrays.toString(loss));\n \n List> ans = new ArrayList<>();\n \n List wonAllMatches = new ArrayList<>();\n List lostOneMatch = new ArrayList<>();\n \n for(int i = 0; i < won.length; i++) {\n if(won[i] > 0 && loss[i] == 0) { //for checking players that have not lost any match.\n wonAllMatches.add(i);\n }\n \n if(loss[i] == 1) {\n lostOneMatch.add(i); //for checking players that have lost exactly one match.\n }\n }\n \n ans.add(wonAllMatches);\n ans.add(lostOneMatch);\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> findWinners(vector>& matches) {\n unordered_map umap;\n vector> result(2);\n for(int i=0;isecond==1)\n {\n result[1].push_back(i->first);\n }\n }\n for(int i=0;i> zigzagLevelOrder(TreeNode root) {\n Queue q=new LinkedList();\n List> res=new ArrayList<>();\n if(root==null){\n return res;\n }\n q.offer(root);\n boolean flag=true;\n while(!q.isEmpty()){\n int size=q.size();\n List curr=new ArrayList<>();\n for(int i=0;i> zigzagLevelOrder(TreeNode* root) {\n vector> ans;\n if(!root) return ans;\n vector r;\n queue q;\n int count=1;\n q.push(root);\n q.push(NULL);\n while(1){\n if(q.front()==NULL){\n q.pop();\n if(count%2==0) reverse(r.begin(),r.end());\n ans.push_back(r);\n if (q.empty()) return ans;\n q.push(NULL);\n r.resize(0);\n count++;\n continue;\n }\n \n r.push_back((q.front())->val);\n if(q.front()->left)q.push((q.front())->left); \n if(q.front()->right)q.push((q.front())->right);\n \n q.pop();\n }\n return ans;\n\n }\n};" }, { "title": "Minimum Number of Swaps to Make the Binary String Alternating", "algo_input": "Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.\n\nThe string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n\nAny two characters may be swapped, even if they are not adjacent.\n\n \nExample 1:\n\nInput: s = \"111000\"\nOutput: 1\nExplanation: Swap positions 1 and 4: \"111000\" -> \"101010\"\nThe string is now alternating.\n\n\nExample 2:\n\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating, no swaps are needed.\n\n\nExample 3:\n\nInput: s = \"1110\"\nOutput: -1\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\ndef minSwaps(self, st: str) -> int:\n \n def swap(st,c):\n n = len(st)\n mis = 0\n for i in range(n):\n if i%2==0 and st[i]!=c:\n mis+=1\n if i%2==1 and st[i]==c:\n mis+=1\n return mis//2\n \n dic = Counter(st)\n z = dic['0']\n o = dic['1']\n res=0\n if abs(z-o)>1:\n return -1\n elif z>o:\n res = swap(st,'0')\n elif o>z:\n res = swap(st,'1')\n else:\n res = min(swap(st,'0'),swap(st,'1'))\n \n return res", "solution_js": "var minSwaps = function(s) {\n let ones = 0;\n let zeroes = 0;\n \n for(let c of s) {\n if(c === \"1\") ones++\n else zeroes++\n }\n \n if(Math.abs(ones - zeroes) > 1) return -1\n \n function count(i) {\n let res = 0\n for(let c of s) {\n if(i !== c) res++;\n if(i === \"1\") i = \"0\";\n else i = \"1\";\n }\n \n return res/2;\n };\n \n if(ones > zeroes) return count(\"1\")\n if(zeroes > ones) return count(\"0\")\n\n return Math.min(count(\"1\"), count(\"0\"));\n};", "solution_java": "class Solution {\n public int minSwaps(String s) {\n int cntZero=0 , cntOne=0;\n for(char ch:s.toCharArray()){\n if(ch=='0') cntZero++;\n else cntOne++;\n }\n \n //Invalid\n if(Math.abs(cntOne-cntZero)>1) return -1;\n \n \n if(cntOne>cntZero){ //one must be at even posotion\n return countSwaps(s,'1'); \n }else if(cntOne 1) return -1;\n if(oneCount > zeroCount) return minFillPos(s,'1');\n if(zeroCount > oneCount) return minFillPos(s,'0');\n return min(minFillPos(s,'0'), minFillPos(s,'1'));\n }\n};" }, { "title": "Corporate Flight Bookings", "algo_input": "There are n flights that are labeled from 1 to n.\n\nYou are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.\n\nReturn an array answer of length n, where answer[i] is the total number of seats reserved for flight i.\n\n \nExample 1:\n\nInput: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput: [10,55,45,25,25]\nExplanation:\nFlight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]\n\n\nExample 2:\n\nInput: bookings = [[1,2,10],[2,2,15]], n = 2\nOutput: [10,25]\nExplanation:\nFlight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]\n\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 104\n\t1 <= bookings.length <= 2 * 104\n\tbookings[i].length == 3\n\t1 <= firsti <= lasti <= n\n\t1 <= seatsi <= 104\n\n", "solution_py": "class Solution:\n\tdef corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n\n\t\tflights = [0]*n\n\t\tfor start,end,seats in bookings:\n\t\t\tflights[start-1] += seats\n\t\t\tif end < n: flights[end] -= seats\n\t\tfor i in range(n-1):\n\t\t\tflights[i+1] += flights[i]\n\t\treturn flights", "solution_js": "var corpFlightBookings = function(bookings, n) {\n \n // +1 as dummy guard on the tail, which allow us not to check right boundary every time\n let unitStep = Array(n+1).fill(0);\n \n for(const [first, last, seatVector ] of bookings ){\n \n // -1 because booking flight is 1-indexed, given by description\n let [left, right] = [first-1, last-1];\n \n unitStep[ left ] += seatVector;\n unitStep[ right+1 ] -= seatVector;\n }\n \n // Reconstruct booking as drawing combination of retangle signal, built with unit step impulse\n for( let i = 1; i < unitStep.length ; i++ ){\n unitStep[ i ] += unitStep[ i-1 ];\n }\n \n \n // last one is dummy guard on the tail, no need to return\n return unitStep.slice(0, n);\n};", "solution_java": "class Solution {\n public int[] corpFlightBookings(int[][] bookings, int n) {\n // nums all equals to zero\n int[] nums = new int[n];\n // construct the diffs\n Difference df = new Difference(nums);\n\n for (int[] booking : bookings) {\n // pay attention to the index\n int i = booking[0] - 1;\n int j = booking[1] - 1;\n int val = booking[2];\n // increase nums[i..j] by val\n df.increment(i, j, val);\n }\n // return the final array\n return df.result();\n }\n\n class Difference {\n // diff array\n private int[] diff;\n\n public Difference(int[] nums) {\n assert nums.length > 0;\n diff = new int[nums.length];\n // construct the diffs\n diff[0] = nums[0];\n for (int i = 1; i < nums.length; i++) {\n diff[i] = nums[i] - nums[i - 1];\n }\n }\n\n // increase nums[i..j] by val\n public void increment(int i, int j, int val) {\n diff[i] += val;\n if (j + 1 < diff.length) {\n diff[j + 1] -= val;\n }\n }\n\n public int[] result() {\n int[] res = new int[diff.length];\n // contract the diff array based on the result\n res[0] = diff[0];\n for (int i = 1; i < diff.length; i++) {\n res[i] = res[i - 1] + diff[i];\n }\n return res;\n }\n }\n\n}", "solution_c": "class Solution {\npublic:\n vector corpFlightBookings(vector>& bookings, int n) {\n vector arr(n);\n for (const auto& b : bookings) {\n int start = b[0] - 1, end = b[1], seats = b[2];\n arr[start] += seats;\n if (end < n) {\n arr[end] -= seats;\n }\n }\n partial_sum(begin(arr), end(arr), begin(arr));\n return arr;\n }\n};" }, { "title": "Max Chunks To Make Sorted", "algo_input": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].\n\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\n\nReturn the largest number of chunks we can make to sort the array.\n\n \nExample 1:\n\nInput: arr = [4,3,2,1,0]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\n\n\nExample 2:\n\nInput: arr = [1,0,2,3,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n\n\n \nConstraints:\n\n\n\tn == arr.length\n\t1 <= n <= 10\n\t0 <= arr[i] < n\n\tAll the elements of arr are unique.\n\n", "solution_py": "class Solution(object):\n def maxChunksToSorted(self, arr):\n n= len(arr)\n\n count=0\n currentmax= -2**63\n for i in range(0,n):\n currentmax=max(currentmax, arr[i])\n if (currentmax==i):\n count+=1\n return count\n \n \n ", "solution_js": "var maxChunksToSorted = function(arr) {\n let count = 0, cumSum = 0;\n arr.forEach((el, index) => {\n cumSum += el-index;\n if (cumSum === 0) count++;\n });\n return count;\n};", "solution_java": "class Solution {\n public int maxChunksToSorted(int[] arr) {\n\n int max=0, count=0;\n for(int i=0; i& arr) {\n // using chaining technique\n int maxi=INT_MIN;\n int ans =0;\n\n for(int i=0;i int:\n ones = 0\n\n # Count number of Ones\n for char in s:\n if char == \"1\":\n ones += 1\n\n # Can't be grouped equally if the ones are not divisible by 3\n if ones > 0 and ones % 3 != 0:\n return 0\n\n # Ways of selecting two dividers from n - 1 dividers \n if ones == 0:\n n = len(s)\n\t\t\t# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }\n return (((n - 1) * (n - 2)) // 2) % ((10 ** 9) + 7)\n\n # Number of ones in each group\n ones_interval = ones // 3\n\n # Number of zeroes which lie on the borders\n left, right = 0, 0\n\n # Iterator\n i = 0\n temp = 0\n\n # Finding the zeroes on the left and right border\n while i < len(s):\n temp += int(s[i]) & 1\n if temp == ones_interval:\n if s[i] == '0':\n left += 1\n if temp == 2 * ones_interval:\n if s[i] == '0':\n right += 1\n i += 1\n \n # The result is the product of number of (left + 1) and (right + 1)\n # Because let's assume it as we only want to fill up the middle group\n # The solution would be if we have zero then there might be a zero in the middle\n # Or there might not be the zero, so this might case is added and then\n\t\t# the events are independent so product of both the events\n return ((left + 1) * (right + 1)) % ((10 ** 9) + 7)", "solution_js": "var numWays = function(s) {\n let one = 0;\n let list = [];\n for(let i = 0; i < s.length; i++){\n if(s[i]===\"1\") one++, list.push(i);\n }\n if(one%3!==0) return 0;\n if(one===0) return ((s.length-1)*(s.length-2)/2) % 1000000007;\n one/=3;\n return ((list[one]-list[one-1])*(list[2*one]-list[2*one-1])) % 1000000007;\n};", "solution_java": "class Solution {\n public int numWays(String s) {\n long n=s.length();\n long one=0;//to count number of ones\n long mod=1_000_000_007;\n char[] c=s.toCharArray();\n for(int i=0;i bool:\n if len(hand) % groupSize:\n return False\n\n freq = collections.defaultdict(int)\n\n for num in hand:\n freq[num] += 1\n\n min_heap = list(freq.keys())\n heapq.heapify(min_heap)\n\n while min_heap:\n smallest = min_heap[0]\n for num in range(smallest, smallest + groupSize):\n if num not in freq:\n return False\n freq[num] -= 1\n\n if freq[num] == 0:\n if num != min_heap[0]:\n return False\n heapq.heappop(min_heap)\n return True", "solution_js": "var isNStraightHand = function(hand, groupSize) {\n if(hand.length%groupSize!==0) return false;\n\t\n const map = new Map();\n hand.forEach(h=>{\n map.set(h,map.get(h)+1||1);\n });\n \n\t// sort based on the key in asc order\n const sortedMap = new Map([...map.entries()].sort((a,b)=>a[0]-b[0]));\n \n while(sortedMap.size){\n\t// getting the first key\n const firstKey = sortedMap.keys().next().value; \n for(let i=firstKey;i map = new HashMap<>();\n PriorityQueue minHeap = new PriorityQueue<>();\n\n for(int card : hand){\n if(map.containsKey(card))\n map.put(card, map.get(card) + 1);\n else {\n map.put(card, 1);\n minHeap.add(card);\n }\n }\n\n while(!minHeap.isEmpty()){\n int min = minHeap.peek();\n for(int i=min; i < min + groupSize; i++){\n if(!map.containsKey(i) || map.get(i) == 0)\n return false;\n map.put(i, map.get(i) - 1);\n if(map.get(i) == 0){\n if(minHeap.peek() != i)\n return false;\n minHeap.poll();\n }\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isNStraightHand(vector& hand, int groupSize) {\n int n = hand.size();\n if(n%groupSize != 0) // We can't rearrange elements of size groupsize so return false\n return false;\n mapmp;\n for(auto it : hand)\n mp[it]++;\n while(mp.size() > 0){\n int start = mp.begin()->first; // Taking the topmost element of map\n\n for(int i=0; i bool:\n target,m=divmod(sum(matchsticks),4)\n if m:return False\n targetLst=[0]*4\n length=len(matchsticks)\n matchsticks.sort(reverse=True)\n def bt(i):\n if i==length:\n return len(set(targetLst))==1\n for j in range(4):\n if matchsticks[i]+targetLst[j]>target:\n continue\n targetLst[j]+=matchsticks[i]\n if bt(i+1):\n return True\n targetLst[j]-=matchsticks[i]\n if not targetLst[j]:break\n return False\n return matchsticks[0]<=target and bt(0)", "solution_js": "var makesquare = function(matchsticks) {\n const perimeter = matchsticks.reduce((a, b) => a + b, 0);\n if(perimeter % 4 != 0 || matchsticks.length < 4) return false;\n \n const sideLen = perimeter / 4;\n // find a way to divide the array in 4 group of sum side length\n const sides = new Array(4).fill(0);\n const len = matchsticks.length;\n matchsticks.sort((a, b) => b - a);\n \n const solve = (x = 0) => {\n if(x == len) {\n return sides.every(side => side == sideLen);\n }\n \n for(let i = 0; i < 4; i++) {\n if(sides[i] + matchsticks[x] > sideLen) {\n continue;\n }\n sides[i] += matchsticks[x];\n if(solve(x + 1)) return true;\n sides[i] -= matchsticks[x];\n }\n return false;\n }\n return solve();\n};", "solution_java": "/*\n Time complexity: O(2 ^ n)\n Space complexity: O(n)\n\n Inutition:\n ---------\n Same as \"Partition to K Equal Sum Subsets\"\n*/\n\nclass Solution {\n public boolean backtrack(int[] nums, int idx, int k, int subsetSum, int target, boolean[] vis) {\n // base case\n if (k == 0)\n return true;\n if (target == subsetSum) {\n // if one of the side is found then keep finding the other k - 1 sides starting again from the beginning\n return backtrack(nums, 0, k - 1, 0, target, vis);\n }\n\n // hypothesis\n for(int i = idx; i < nums.length; i++) {\n // if number is already visited or sum if out of range then skip\n if (vis[i] || subsetSum + nums[i] > target)\n continue;\n\n // Pruning\n // if the last position (i - 1) is not visited, that means the current combination didn't work,\n // and since this position (i) has the same value, it won't work for it as well. Thus, skip it.\n if (i - 1 >= 0 && nums[i] == nums[i - 1] && !vis[i - 1])\n continue;\n\n vis[i] = true;\n if (backtrack(nums, i + 1, k, subsetSum + nums[i], target, vis))\n return true;\n\n // backtrack\n vis[i] = false;\n }\n\n return false;\n }\n\n private void reverse(int[] arr) {\n for (int i = 0, j = arr.length - 1; i < j; i++, j--) {\n int tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n }\n\n public boolean makesquare(int[] matchsticks) {\n int sum = 0;\n int k = 4;\n int n = matchsticks.length;\n // sort the array in descending order to make the recursion hit the base case quicker\n Arrays.sort(matchsticks);\n reverse(matchsticks);\n\n for(int match: matchsticks)\n sum += match;\n\n if (sum % k != 0)\n return false;\n\n int target = sum / k;\n boolean[] vis = new boolean[n];\n\n return backtrack(matchsticks, 0, k, 0, target, vis);\n }\n}", "solution_c": "class Solution {\npublic:\n bool makesquare(vector& matchsticks) {\n int goal = 0, totalSum = 0;\n for (int i : matchsticks) {\n totalSum += i;\n }\n goal = totalSum / 4;\n sort(matchsticks.begin(), matchsticks.end(), [](auto left, auto right) {\n return left > right;\n });\n int b = 0;\n if (totalSum % 4) {\n return false;\n }\n return backtrack(0, b, 0, goal, 4, matchsticks);\n }\n \n bool backtrack(int start, int &b, int sum, int &goal, int groups, vector& matchsticks) {\n if (sum == goal) {\n //set sum to 0, groups--\n return backtrack(0, b, 0, goal, groups-1, matchsticks);\n }\n if (groups == 1) {\n return true;\n }\n for (int i = start; i < matchsticks.size(); i++) {\n if ((i > 0) && (!(b & (1 << (i - 1)))) && (matchsticks[i] == matchsticks[i-1])) {\n continue;\n }\n //if element not used and element value doesnt go over group sum\n if (((b & (1 << i)) == 0) && (sum + matchsticks[i] <= goal)) {\n //set element to used, recursion\n b ^= (1 << i); \n if (backtrack(i + 1, b, sum + matchsticks[i], goal, groups, matchsticks)) {\n return true;\n }\n //if here, received a false, set element to unused again\n b ^= (1 << i);\n }\n }\n return false;\n }\n};" }, { "title": "Construct Binary Tree from Inorder and Postorder Traversal", "algo_input": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.\n\n \nExample 1:\n\nInput: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput: [3,9,20,null,null,15,7]\n\n\nExample 2:\n\nInput: inorder = [-1], postorder = [-1]\nOutput: [-1]\n\n\n \nConstraints:\n\n\n\t1 <= inorder.length <= 3000\n\tpostorder.length == inorder.length\n\t-3000 <= inorder[i], postorder[i] <= 3000\n\tinorder and postorder consist of unique values.\n\tEach value of postorder also appears in inorder.\n\tinorder is guaranteed to be the inorder traversal of the tree.\n\tpostorder is guaranteed to be the postorder traversal of the tree.\n\n", "solution_py": "import bisect\n# 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\n def buildTree(self, inorder, postorder):\n \"\"\"\n 7\n 2\n -8 \n :type inorder: List[int]\n :type postorder: List[int]\n :rtype: TreeNode\n ([-4,-10,3,-1], [7]) ((11,-8,2), [7])\n \"\"\"\n currentSplits = [(inorder, [], [])]\n nodeDirectory = {}\n finalSplits = []\n for nodeVal in reversed(postorder):\n nodeDirectory[nodeVal] = TreeNode(nodeVal)\n for splits, nodes, directions in reversed(currentSplits):\n removing = None\n if nodeVal in splits:\n removing = (splits, nodes, directions)\n left = splits[:splits.index(nodeVal)]\n right = splits[splits.index(nodeVal)+1:]\n currentSplits.append((left, nodes+[nodeVal], directions + ['left']))\n if len(left) <= 1:\n finalSplits.append((left, nodes+[nodeVal], directions + ['left']))\n currentSplits.append((right, nodes+[nodeVal], directions + ['right']))\n if len(right) <= 1:\n finalSplits.append((right, nodes+[nodeVal], directions + ['right']))\n break\n if removing:\n currentSplits.remove(removing)\n finalSplits = [splits for splits in finalSplits if splits[0]]\n\n while finalSplits:\n nodeVal, nodes, directions = finalSplits.pop()\n bottomNode = nodeDirectory[nodeVal[0]] if nodeVal else None\n while nodes:\n attachingNode = nodeDirectory[nodes.pop()]\n attachingDir = directions.pop()\n if attachingDir == 'left':\n attachingNode.left = bottomNode\n else:\n attachingNode.right = bottomNode\n bottomNode = attachingNode\n return nodeDirectory[postorder[-1]]", "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[]} inorder\n * @param {number[]} postorder\n * @return {TreeNode}\n */\nvar buildTree = function(inorder, postorder) {\n let postIndex = postorder.length - 1\n\n const dfs = (left, right) => {\n if (left > right) return null\n\n const val = postorder[postIndex--]\n const mid = inorder.findIndex(e => e === val)\n const root = new TreeNode(val)\n\n root.right = dfs(mid + 1, right)\n root.left = dfs(left, mid - 1)\n\n return root\n }\n\n return dfs(0, inorder.length - 1)\n};", "solution_java": "class Solution {\n int[] io; int[] po;\n int n; // nth post order node \n public TreeNode buildTree(int[] inorder, int[] postorder) {\n this.n = inorder.length-1; this.io = inorder; this.po = postorder; \n return buildTree(0, n); \n }\n public TreeNode buildTree(int low, int high) {\n if(n < 0 || low > high) return null;\n int currNode = po[n--];\n int idxInInorder = low;\n TreeNode root = new TreeNode(currNode); \n if(low == high) return root; // no more nodes\n \n while(io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder\n root.right = buildTree(idxInInorder+1, high);\n root.left = buildTree(low, idxInInorder-1);\n return root; \n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* buildTree(vector& ino, vector& post) {\n int i1 = post.size()-1;\n return solve(i1,ino,post,0,ino.size()-1);\n }\n TreeNode* solve(int &i,vector &in,vector &post,int l,int r){\n if(l>r)return NULL;\n int x = r;\n while(post[i] != in[x]){\n x--;\n }\n i--;\n // cout<right = solve(i,in,post,x+1,r);\n root->left = solve(i,in,post,l,x-1);\n return root;\n }\n};" }, { "title": "Remove Sub-Folders from the Filesystem", "algo_input": "Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.\n\nIf a folder[i] is located within another folder[j], it is called a sub-folder of it.\n\nThe format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.\n\n\n\tFor example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not.\n\n\n \nExample 1:\n\nInput: folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput: [\"/a\",\"/c/d\",\"/c/f\"]\nExplanation: Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.\n\n\nExample 2:\n\nInput: folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput: [\"/a\"]\nExplanation: Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".\n\n\nExample 3:\n\nInput: folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput: [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n\n\n \nConstraints:\n\n\n\t1 <= folder.length <= 4 * 104\n\t2 <= folder[i].length <= 100\n\tfolder[i] contains only lowercase letters and '/'.\n\tfolder[i] always starts with the character '/'.\n\tEach folder name is unique.\n\n", "solution_py": "# a TrieNode class for creating new node\nclass TrieNode():\n def __init__(self):\n self.children = {}\n self.main = False\n \n# the main class\nclass Solution(object):\n def removeSubfolders(self, folder): \n node = TrieNode()\n res = []\n # sort the list to prevent adding the subfolder to the Trie first\n folder.sort()\n for dir in folder:\n name = dir.split(\"/\")\n if self.addTrie(name,node):\n res.append(dir)\n return res\n\n # usign the same addTrie template and modify the else part\n def addTrie(self,name,node): \n trie = node\n for c in name:\n if c not in trie.children:\n trie.children[c] = TrieNode()\n # if char is in trie,\n else:\n # check if it's the last sub folder. \n if trie.children[c].main == True:\n return False\n trie = trie.children[c]\n trie.main = True\n return True", "solution_js": "var removeSubfolders = function(folder) {\n folder = folder.sort()\n const result = [];\n for(let i in folder){\n const f = folder[i];\n if(result.length == 0 || !f.startsWith(result[result.length -1] + \"/\"))\n result.push(f);\n }\n return result;\n};", "solution_java": "class Solution {\n TrieNode root;\n public List removeSubfolders(String[] folder) {\n List res = new ArrayList<>();\n Arrays.sort(folder, (a, b) -> (a.length() - b.length()));\n root = new TrieNode();\n for (String f : folder) {\n if (insert(f)) {\n res.add(f);\n }\n }\n return res;\n }\n \n private boolean insert(String folder) {\n TrieNode node = root;\n char[] chs = folder.toCharArray();\n for (int i = 0; i < chs.length; i++) {\n char ch = chs[i];\n node.children.putIfAbsent(ch, new TrieNode());\n node = node.children.get(ch);\n if (node.isFolder && (i+1 < chs.length && chs[i+1] == '/')) {\n return false;\n }\n }\n node.isFolder = true;\n return true;\n }\n}\n\nclass TrieNode {\n Map children = new HashMap<>();\n boolean isFolder;\n}", "solution_c": "class Solution {\npublic:\n \n int check(string &s,unordered_map&mp)\n {\n string temp;\n temp.push_back(s[0]); //for maintaining prefix string \n \n for(int i=1;i removeSubfolders(vector& folder) {\n unordered_mapmp;\n sort(folder.begin(),folder.end());\n vectorans;\n \n for(auto it:folder)\n {\n if(!check(it,mp))\n ans.push_back(it);\n }\n \n return ans;\n \n }\n};" }, { "title": "Longest Palindrome", "algo_input": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.\n\nLetters are case sensitive, for example, \"Aa\" is not considered a palindrome here.\n\n \nExample 1:\n\nInput: s = \"abccccdd\"\nOutput: 7\nExplanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7.\n\n\nExample 2:\n\nInput: s = \"a\"\nOutput: 1\nExplanation: The longest palindrome that can be built is \"a\", whose length is 1.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 2000\n\ts consists of lowercase and/or uppercase English letters only.\n\n", "solution_py": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n letters = {} \n for letter in s: #count each letter and update letters dict\n if letter in letters:\n letters[letter] += 1\n else:\n letters[letter] = 1\n \n \n plus1 = 0 # if there is a letter with count of odd ans must +=1 \n ans = 0\n for n in letters.values():\n if n == 1: #1 can only appear in the middle of our word\n plus1 = 1\n elif n%2 == 0:\n ans += n\n else:\n ans += n - 1\n plus1 = 1\n \n return ans + plus1", "solution_js": "var longestPalindrome = function(s) {\n const hashMap = {};\n let ouput = 0;\n let hashOdd = false;\n\n for (let i = 0; i < s.length; i++) {\n if (!hashMap[s[i]]) {\n hashMap[s[i]] = 0;\n }\n hashMap[s[i]] += 1;\n }\n\n Object.values(hashMap)?.forEach(character => {\n ouput += character%2 ? character - 1 : character;\n if (character%2 && !hashOdd) {\n hashOdd = true;\n }\n });\n\n return ouput + (hashOdd ? 1 : 0);\n};", "solution_java": "class Solution {\n public int longestPalindrome(String s) {\n HashMap map = new HashMap<>();\n\n int evenNo = 0;\n int oddNo = 0;\n\n for ( int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (map.containsKey(c)) {\n map.put(c, map.get(c) + 1);\n } else {\n map.put(c, 1);\n }\n\n }\n for (Map.Entry e : map.entrySet()) {\n int n = (int) e.getValue();\n if (n % 2 != 0) {\n oddNo += n;\n }\n evenNo += (n / 2) * 2;\n }\n\n if (oddNo > 0) {\n evenNo += 1;\n }\n return evenNo;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestPalindrome(string s) {\n map mp;\n for(int i=0;i List[int]:\n pre = [1]* (len(nums)+1)\n back = [1]*(len(nums)+1)\n\n for i in range(len(nums)):\n pre[i+1] = pre[i]*nums[i]\n\n for i in range(len(nums)-1,-1,-1):\n back[i-1] = back[i]*nums[i]\n for i in range(len(pre)-1):\n nums[i]=pre[i]*back[i]\n\n return nums", "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar productExceptSelf = function(nums) {\n let result = [];\n let len = nums.length;\n\n let prefix = 1;\n for (let i = 0; i < len; i++) {\n result[i] = prefix;\n prefix *= nums[i];\n }\n let postfix = 1;\n for (let i = len - 1; i >= 0; i--) {\n result[i] *= postfix;\n postfix *= nums[i];\n }\n return result;\n};", "solution_java": "class Solution {\n public int[] productExceptSelf(int[] nums) {\n int n = nums.length;\n int pre[] = new int[n];\n int suff[] = new int[n];\n pre[0] = 1;\n suff[n - 1] = 1;\n \n for(int i = 1; i < n; i++) {\n pre[i] = pre[i - 1] * nums[i - 1];\n }\n for(int i = n - 2; i >= 0; i--) {\n suff[i] = suff[i + 1] * nums[i + 1];\n }\n \n int ans[] = new int[n];\n for(int i = 0; i < n; i++) {\n ans[i] = pre[i] * suff[i];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector productExceptSelf(vector& nums) {\n int zero=0,product=1;\n for(auto i:nums){\n if(i==0)\n zero++;\n else product*=i;\n }\n for(int i=0;i1){\n nums[i]=0;\n }\n else if(nums[i] == 0){\n nums[i]=product;\n }\n else if(zero > 0){\n nums[i]=0;\n }\n else nums[i]=product/nums[i];\n }\n return nums;\n }\n};" }, { "title": "Maximum Equal Frequency", "algo_input": "Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\n\nIf after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n\n \nExample 1:\n\nInput: nums = [2,2,1,1,5,3,3,5]\nOutput: 7\nExplanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n\n\nExample 2:\n\nInput: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput: 13\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n ans = 0\n n = len(nums)\n countToFreq = defaultdict(int)\n # key = count value = Freq ex 2 occured 3 times in nums so 2 : 3\n freqToCount = defaultdict(int)\n # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3\n \n for i,val in enumerate(nums):\n \n x = countToFreq[val] + 1\n freqToCount[x - 1] -= 1\n if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)\n freqToCount[x] += 1\n countToFreq[val] = x\n \n # if a single item is repeated for i + 1 times like [1,1,1]\n if countToFreq[val] == i + 1 :ans = i + 1\n \n # if all items are having same frequency like [2,2,1,1,3,3]\n elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1\n \n # if all items have same frequency except one having 1 freq like [2,2,3,3,1]\n elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1\n \n # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]\n elif len(freqToCount) == 2:\n keys,values = [],[]\n for j in freqToCount:keys.append(j) , values.append(freqToCount[j])\n if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1\n return ans", "solution_js": "// *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value\n\nvar maxEqualFreq = function(nums) {\n // create cache to count the frequency of each number\n const numCnt = {};\n \n // create cache to count the number of 'number of frequencies'\n // e.g. [1,2,3,2,4,4,3,1,5]\n // { 1: 1 1 number appeared with a frequency of 1\n // 2: 3 } 3 numbers appeared with a frequency of 2\n const cntFreq = {};\n \n // holds the maximum frequency a number has appeared\n let maxFreq = 0;\n \n // holds solution\n let result = 0;\n \n // iterate through numbers\n for (let i = 0; i < nums.length; i++) {\n // get current number;\n const num = nums[i];\n\t \n\t // subtract one from the current frequency of the current number\n cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] - 1 : -1;\n\t \n\t // increase the count of the current number\n numCnt[num] = numCnt[num] ? numCnt[num] + 1 : 1;\n\t \n\t // add one to the current frequency of the current number\n cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] + 1 : 1;\n\t \n\t // if the current frequency is more than the max frequency update the max frequency\n if (maxFreq < numCnt[num]) maxFreq = numCnt[num];\n\t \n\t // if max frequency is 1 or\n\t // if the max frequency multiplied by the number of values with that frequency equals the current index or\n\t // if the result of the 1 less than the max frequency equals to the current index\n\t // update result\n if (maxFreq === 1 || maxFreq * cntFreq[maxFreq] === i || (maxFreq - 1) * (cntFreq[maxFreq - 1] + 1) === i) {\n result = i + 1;\n }\n }\n return result;\n};", "solution_java": "import java.util.TreeMap;\nimport java.util.NavigableMap;\nclass Solution {\n public int maxEqualFreq(int[] nums) {\n Map F = new HashMap<>(); //Frequencies\n NavigableMap V = new TreeMap<>(); //Values for frequencies\n int max = 0;\n for (int i = 0; i < nums.length; i++) {\n increaseCount(F, nums[i]);\n int frequency = F.get(nums[i]);\n decreaseCount(V, frequency - 1);\n increaseCount(V, frequency);\n if (isPossibleToRemove(V)) max = i;\n }\n return max + 1;\n }\n \n public boolean isPossibleToRemove(NavigableMap frequenciesMap) {\n if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies\n Map.Entry first = frequenciesMap.firstEntry();\n Map.Entry last = frequenciesMap.lastEntry();\n if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d]\n int firstReduced = removeElement(first);\n int lastReduced = removeElement(last);\n if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false;\n return true;\n }\n \n //Try to remove element which contributes to this frequency:\n //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1\n //if there are more than 1 occurences of such frequency, removing 1 element will not change it\n public int removeElement(Map.Entry frequencyValue) {\n if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1;\n return frequencyValue.getKey();\n }\n \n public void decreaseCount(Map map, int element) {\n if (!map.containsKey(element)) return;\n map.put(element, map.get(element) - 1);\n if (map.get(element) == 0) map.remove(element);\n }\n \n public void increaseCount(Map map, int element) {\n if (!map.containsKey(element)) map.put(element, 0);\n map.put(element, map.get(element) + 1);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxEqualFreq(vector& nums) {\n int n=nums.size();\n unordered_map mp1,mp2; //one to store the frequency of each number , and one which will store the frequency of the frequency\n int ans=0;\n for(int i=0;i len(self.front):\n self.front.append(self.back.popleft())\n\n while len(self.front) > len(self.back) + 1:\n self.back.appendleft(self.front.pop())\n\n def pushFront(self, val: int) -> None:\n self.front.appendleft(val)\n self._correct_size()\n\n def pushMiddle(self, val: int) -> None:\n if len(self.front) > len(self.back):\n self.back.appendleft(self.front.pop())\n self.front.append(val)\n self._correct_size()\n\n def pushBack(self, val: int) -> None:\n self.back.append(val)\n self._correct_size()\n\n def popFront(self) -> int:\n front = self.front if self.front else self.back\n ret = front.popleft() if front else -1\n self._correct_size()\n return ret\n\n def popMiddle(self) -> int:\n ret = self.front.pop() if self.front else -1\n self._correct_size()\n return ret\n\n def popBack(self) -> int:\n back = self.back if self.back else self.front\n ret = back.pop() if back else -1\n self._correct_size()\n return ret", "solution_js": "// T.C: \n// O(1) for init and methods other than pushMiddle(), popMiddle()\n// O(N) for pushMiddle(), popMiddle()\n// S.C: O(N) for storage \n\n// Doubly linked list node\nfunction ListNode(val, prev, next) {\n this.val = val || 0;\n this.prev = prev || null;\n this.next = next || null;\n}\n\nvar FrontMiddleBackQueue = function() {\n this.head = null;\n this.tail = null;\n this.len = 0;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushFront = function(val) {\n if (this.len === 0) {\n this.head = new ListNode(val);\n this.tail = this.head;\n this.len += 1;\n return;\n }\n \n let newNode = new ListNode(val);\n newNode.next = this.head;\n this.head.prev = newNode;\n this.head = newNode; // the new node becomes the new head\n this.len += 1;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushMiddle = function(val) {\n if (this.len <= 1) {\n this.pushFront(val);\n return;\n }\n let cur = this.head;\n for (let i = 1; i < Math.floor(this.len / 2); i++) { // we go to previous node of median\n cur = cur.next; \n }\n let newNode = new ListNode(val);\n let next = cur.next;\n cur.next = newNode;\n newNode.prev = cur;\n newNode.next = next;\n if (next) next.prev = newNode;\n this.len += 1;\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nFrontMiddleBackQueue.prototype.pushBack = function(val) {\n if (this.len === 0) {\n this.pushFront(val);\n return;\n }\n \n let newNode = new ListNode(val);\n this.tail.next = newNode;\n newNode.prev = this.tail;\n this.tail = newNode; // end node becomes the new tail\n this.len += 1;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popFront = function() {\n if (this.len === 0) {\n return -1;\n }\n let front = this.head;\n let next = front.next;\n if (next) next.prev = null;\n this.head = next;\n this.len -= 1;\n return front.val;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popMiddle = function() {\n if (this.len <= 2) {\n return this.popFront();\n }\n let cur = this.head;\n for (let i = 1; i < Math.ceil(this.len / 2); i++) { // we go to median node\n cur = cur.next; \n }\n\n let prev = cur.prev;\n let next = cur.next;\n cur.prev = null;\n cur.next = null;\n if (prev) prev.next = next; \n if (next) next.prev = prev;\n this.len -= 1;\n return cur.val;\n};\n\n/**\n * @return {number}\n */\nFrontMiddleBackQueue.prototype.popBack = function() {\n if (this.len <= 1) {\n return this.popFront();\n }\n let end = this.tail;\n let prev = end.prev;\n end.prev = null;\n prev.next = null;\n this.tail = prev;\n this.len -= 1;\n return end.val;\n};\n\n/** \n * Your FrontMiddleBackQueue object will be instantiated and called as such:\n * var obj = new FrontMiddleBackQueue()\n * obj.pushFront(val)\n * obj.pushMiddle(val)\n * obj.pushBack(val)\n * var param_4 = obj.popFront()\n * var param_5 = obj.popMiddle()\n * var param_6 = obj.popBack()\n */", "solution_java": "class FrontMiddleBackQueue {\n\n Deque dq1, dq2;\n public FrontMiddleBackQueue() { \n dq1 = new ArrayDeque();\n dq2 = new ArrayDeque();\n }\n \n public void pushFront(int val) {\n dq1.addFirst(val);\n } \n \n public void pushBack(int val) {\n dq2.addLast(val);\n } \n \n public void pushMiddle(int val) {\n while(dq1.size() + 1 < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size())\n dq2.addFirst(dq1.removeLast()); \n dq1.addLast(val); \n } \n \n public int popFront() {\n if(!dq1.isEmpty())\n return dq1.removeFirst();\n if(!dq2.isEmpty())\n return dq2.removeFirst();\n return -1; \n } \n \n public int popMiddle() {\n if(dq1.isEmpty() && dq2.isEmpty())\n return -1; \n while(dq1.size() < dq2.size())\n dq1.addLast(dq2.removeFirst()); \n while(dq1.size() > dq2.size() + 1)\n dq2.addFirst(dq1.removeLast());\n return !dq1.isEmpty() ? dq1.removeLast() : dq2.removeFirst();\n } \n \n public int popBack() {\n if(!dq2.isEmpty())\n return dq2.removeLast();\n if(!dq1.isEmpty())\n return dq1.removeLast();\n return -1; \n } \n}", "solution_c": "class FrontMiddleBackQueue {\npublic:\n deque list1;\n deque list2;\n int size;\n \n FrontMiddleBackQueue() {\n size = 0; \n }\n \n void pushFront(int val) {\n \n if(list1.size()- list2.size() == 0)\n {\n list1.push_front(val);\n }\n else\n {\n list1.push_front(val);\n list2.push_front(list1.back());\n list1.pop_back();\n }\n \n size++;\n }\n \n void pushMiddle(int val) {\n \n if(list1.size() - list2.size() == 0)\n {\n list1.push_back(val);\n }\n else\n {\n list2.push_front(list1.back());\n list1.pop_back();\n list1.push_back(val);\n }\n \n size++;\n }\n \n void pushBack(int val) {\n \n if(list1.size() - list2.size() == 0)\n {\n list2.push_back(val);\n list1.push_back(list2.front());\n list2.pop_front();\n }\n else\n {\n list2.push_back(val);\n }\n \n size++;\n }\n \n int popFront() {\n\n if(size ==0) return -1;\n \n int val = list1.front();\n list1.pop_front();\n \n if(list1.size() 1)\n {\n list2.push_front(list1.back());\n list1.pop_back();\n } \n }\n \n size--;\n return val; \n }\n};" }, { "title": "Maximize Sum Of Array After K Negations", "algo_input": "Given an integer array nums and an integer k, modify the array in the following way:\n\n\n\tchoose an index i and replace nums[i] with -nums[i].\n\n\nYou should apply this process exactly k times. You may choose the same index i multiple times.\n\nReturn the largest possible sum of the array after modifying it in this way.\n\n \nExample 1:\n\nInput: nums = [4,2,3], k = 1\nOutput: 5\nExplanation: Choose index 1 and nums becomes [4,-2,3].\n\n\nExample 2:\n\nInput: nums = [3,-1,0,2], k = 3\nOutput: 6\nExplanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\n\n\nExample 3:\n\nInput: nums = [2,-3,-1,5,-4], k = 2\nOutput: 13\nExplanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-100 <= nums[i] <= 100\n\t1 <= k <= 104\n\n", "solution_py": "from heapq import heapify, heapreplace\n\nclass Solution:\n def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:\n heapify(nums)\n while k and nums[0] < 0:\n heapreplace(nums, -nums[0])\n k -= 1\n if k % 2:\n heapreplace(nums, -nums[0])\n return sum(nums)", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar largestSumAfterKNegations = function(nums, k) {\n let negations = k\n let index = 0\n const sortedNums = [...nums]\n\n // Sort in increasing order\n sortedNums.sort((a, b) => a - b)\n\n // loop into the sorted array using the\n // number of negations\n while (negations > 0) {\n negations--\n\n const currentNumber = -sortedNums[index]\n const nextNumber = sortedNums[index + 1]\n\n sortedNums[index] = currentNumber\n\n // if the number is 0, undefined or\n // the current number is less than the\n // next number (meaning it will be\n // less the amount if it's a negative\n // number) just use the same number\n // again to flip.\n if (\n currentNumber === 0 ||\n nextNumber === undefined ||\n currentNumber < nextNumber\n ) continue\n\n index++\n }\n\n return sortedNums.reduce((sum, num) => sum + num, 0)\n};", "solution_java": "class Solution {\n public int largestSumAfterKNegations(int[] nums, int k) {\n\n PriorityQueue minHeap = new PriorityQueue<>();\n for(int val : nums) minHeap.add(val);\n\n while(k > 0){\n\n int curr = minHeap.poll();\n minHeap.add(-curr);\n k--;\n }\n\n int sum = 0;\n while(!minHeap.isEmpty()){\n sum += minHeap.poll();\n }\n return sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int largestSumAfterKNegations(vector& A, int k) {\n priority_queue, greater> pq(A.begin(), A.end());\n while(k--){\n int t=pq.top();pq.pop();\n pq.push(t*-1);\n }\n \n int n=0;\n while(!pq.empty()){\n int t=pq.top();pq.pop();\n n+=t;\n }\n return n;\n }\n};" }, { "title": "Minimum Difference Between Highest and Lowest of K Scores", "algo_input": "You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.\n\nPick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.\n\nReturn the minimum possible difference.\n\n \nExample 1:\n\nInput: nums = [90], k = 1\nOutput: 0\nExplanation: There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.\n\n\nExample 2:\n\nInput: nums = [9,4,1,7], k = 2\nOutput: 2\nExplanation: There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.\n\n \nConstraints:\n\n\n\t1 <= k <= nums.length <= 1000\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n cur = float('inf')\n for i in range(len(nums)-k+1):\n cur = min(cur, nums[i+k-1]-nums[i])", "solution_js": "```/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minimumDifference = function(nums, k) {\n nums.sort((a,b)=>a-b)\n let min=nums[0],max=nums[k-1],diff=max-min\n for(let i=k;i& nums, int k) {\n sort(nums.begin(), nums.end());\n int res = nums[k-1] - nums[0];\n for (int i = k; i < nums.size(); i++) res = min(res, nums[i] - nums[i-k+1]);\n return res;\n }\n};" }, { "title": "Number Complement", "algo_input": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\n\n\n\tFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n\n\nGiven an integer num, return its complement.\n\n \nExample 1:\n\nInput: num = 5\nOutput: 2\nExplanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\n\n\nExample 2:\n\nInput: num = 1\nOutput: 0\nExplanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n\n\n \nConstraints:\n\n\n\t1 <= num < 231\n\n\n \nNote: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/\n", "solution_py": "class Solution:\n def findComplement(self, num: int) -> int:\n i = 0\n while(2**i <= num):\n i += 1\n return (2**i - num - 1)", "solution_js": "var findComplement = function(num) {\n return num ^ parseInt(Array(num.toString(2).length).fill(\"1\").join(\"\"), 2)\n}", "solution_java": "class Solution {\n public int findComplement(int num) {\n int x=0;int sum=0;\n while(num>0){\n int i = num%2;\n if(i==0){\n sum+=Math.pow(2,x++);\n }\n else{\n x++;\n }\n num/=2;\n }\n return sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int findComplement(int num) {\n long n=1;\n while(n-1 List[int]:\n nums.sort(reverse=True)\n val = sum(nums)\n temp = []\n for i in range(len(nums)):\n temp.append(nums[i])\n if sum(temp)>val-sum(temp):\n return temp\n ", "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar minSubsequence = function(nums) {\n const target = nums.reduce((a, b) => a + b) / 2;\n nums.sort((a, b) => b - a);\n let i = 0, sum = 0;\n while (sum <= target) {\n sum += nums[i++];\n }\n return nums.slice(0, i);\n};", "solution_java": "class Solution {\n public List minSubsequence(int[] nums) {\n int total = 0;\n for(int i=0;i ans = new ArrayList<>();\n for(int i=nums.length-1;i>=0;i--){\n ans.add(nums[i]);\n sum += nums[i];\n if(sum>total-sum){\n return ans;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector minSubsequence(vector& nums) {\n \n sort(nums.begin(), nums.end(),greater());\n vector res;\n int sum = 0;\n for(int i: nums)\n sum += i;\n \n int x=0;\n for(int i=0; isum)\n break;\n \n }\n return res;\n }\n};" }, { "title": "Filling Bookcase Shelves", "algo_input": "You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.\n\nWe want to place these books in order onto bookcase shelves that have a total width shelfWidth.\n\nWe choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.\n\nNote that at each step of the above process, the order of the books we place is the same order as the given sequence of books.\n\n\n\tFor example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.\n\n\nReturn the minimum possible height that the total bookshelf can be after placing shelves in this manner.\n\n \nExample 1:\n\nInput: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4\nOutput: 6\nExplanation:\nThe sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.\n\n\nExample 2:\n\nInput: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= books.length <= 1000\n\t1 <= thicknessi <= shelfWidth <= 1000\n\t1 <= heighti <= 1000\n\n", "solution_py": "class Solution:\n def minHeightShelves(self, books, shelf_width: int) -> int:\n n, dp = len(books), [float('inf')] * (len(books)+1)\n dp[0] = 0\n\n for i in range(1, n+1):\n max_width, max_height, j = shelf_width, 0, i - 1\n \n while j >= 0 and max_width - books[j][0] >= 0:\n max_width -= books[j][0]\n max_height = max(max_height, books[j][1])\n dp[i] = max_height\n j -= 1\n\n if j >= 0 and max_width - books[j][0] < 0:\n j = i - 1\n dp[i] = float('inf')\n width, height = 0, 0\n while j >= 0 and width + books[j][0] <= shelf_width:\n width = width + books[j][0]\n height = max(books[j][1], height)\n dp[i] = min(dp[i], height + dp[j])\n j -= 1\n\n return dp[n]", "solution_js": "var minHeightShelves = function(books, shelfWidth) {\n let booksArr = []\n\n for(let i = 0; i < books.length; i++) {\n let remainingWidth = shelfWidth - books[i][0]\n let bookHeight = books[i][1]\n\n let maxHeight = bookHeight\n\n let prevSum = booksArr[i - 1] !== undefined ? booksArr[i - 1] : 0\n let minSumHeight = bookHeight + prevSum\n\n for(let x = i - 1; x >= 0 ; x--) {\n\n let prevBookWidth = books[x][0]\n let prevBookHeight = books[x][1]\n if(remainingWidth - prevBookWidth < 0) break\n remainingWidth -= prevBookWidth\n\n prevSum = booksArr[x - 1] !== undefined ? booksArr[x - 1] : 0\n\n maxHeight = Math.max(maxHeight, prevBookHeight)\n\n minSumHeight = Math.min(prevSum + maxHeight, minSumHeight)\n }\n booksArr[i] = minSumHeight\n }\n\n return booksArr[books.length - 1]\n};", "solution_java": "class Solution {\n int[][] books;\n int shefWidth;\n\n Map memo = new HashMap();\n\n public int findMinHeight(int curr, int maxHeight, int wRem) {\n String key = curr + \":\" + wRem ;\n \n if(memo.containsKey(key)) return memo.get(key);\n\n\n if(curr == books.length ) return maxHeight;\n int[] currBook = books[curr];\n\n memo.put( key, currBook[0] <= wRem ? Math.min( maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0]) , // new shelf\n findMinHeight(curr + 1, Math.max(maxHeight, currBook[1]),wRem - currBook[0] )) // same shelf\n : maxHeight + findMinHeight(curr + 1, currBook[1], shefWidth - currBook[0])\n ); // new shelf\n\n return memo.get(key);\n }\n\n\n public int minHeightShelves(int[][] books, int shelfWidth) {\n this.books = books;\n this.shefWidth = shelfWidth;\n return findMinHeight(0, 0, shelfWidth);\n }\n}", "solution_c": "class Solution {\npublic:\n int minHeightShelves(vector>& books, int shelfWidth) {\n int n=books.size();\n vector> cost(n+1,vector(n+1));\n for(int i=1;i<=n;i++)\n {\n int height=books[i-1][1];\n int width=books[i-1][0];\n cost[i][i]=height;\n for(int j=i+1;j<=n;j++)\n {\n height=max(height,books[j-1][1]);\n width+=books[j-1][0];\n if(width<=shelfWidth) cost[i][j]=height;\n else cost[i][j]=-1;\n }\n }\n vector ans(n+1);\n ans[0]=0;\n for(int i=1;i<=n;i++)\n {\n ans[i]=INT_MAX;\n for(int j=1;j<=i;j++)\n {\n if(cost[j][i]==-1) continue;\n if(ans[j-1]!=INT_MAX) ans[i]=min(ans[i],ans[j-1]+cost[j][i]);\n }\n }\n return ans[n];\n }\n};" }, { "title": "First Bad Version", "algo_input": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.\n\nSuppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.\n\nYou are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.\n\n \nExample 1:\n\nInput: n = 5, bad = 4\nOutput: 4\nExplanation:\ncall isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.\n\n\nExample 2:\n\nInput: n = 1, bad = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= bad <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n fast, slow = int(n/2), n\n diff = abs(fast-slow)\n while isBadVersion(fast) == isBadVersion(slow) or diff > 1:\n fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast\n diff = abs(fast-slow)\n return fast if isBadVersion(fast) else slow", "solution_js": "/**\n * Definition for isBadVersion()\n *\n * @param {integer} version number\n * @return {boolean} whether the version is bad\n * isBadVersion = function(version) {\n * ...\n * };\n */\n\n/**\n * @param {function} isBadVersion()\n * @return {function}\n */\nvar solution = function(isBadVersion) {\n /**\n * @param {integer} n Total versions\n * @return {integer} The first bad version\n */\n return function(n) {\n let ceiling = n\n let floor = 1\n let firstBadVersion = -1\n\n while (floor <= ceiling) {\n const middle = Math.floor((ceiling + floor) / 2)\n\n if (isBadVersion(middle)) {\n\n firstBadVersion = middle\n ceiling = middle - 1\n } else {\n floor = middle + 1\n }\n }\n\n return firstBadVersion\n };\n};", "solution_java": "/* The isBadVersion API is defined in the parent class VersionControl.\n boolean isBadVersion(int version); */\n\npublic class Solution extends VersionControl {\n public int firstBadVersion(int n) {\n int s = 0; int e = n;\n \n while(s < e) {\n int mid = s +(e-s)/2;\n \n if(isBadVersion(mid)){\n e = mid ;\n } else {\n s = mid +1;\n }\n }\n return e ;\n }\n}", "solution_c": "class Solution {\npublic:\n int firstBadVersion(int n) {\n\t//Using Binary Search\n int lo = 1, hi = n, mid;\n while (lo < hi) {\n mid = lo + (hi - lo) / 2;\n if (isBadVersion(mid)) hi = mid;\n else lo = mid+1;\n }\n return lo;\n }\n};" }, { "title": "Minimum Limit of Balls in a Bag", "algo_input": "You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.\n\nYou can perform the following operation at most maxOperations times:\n\n\n\tTake any bag of balls and divide it into two new bags with a positive number of balls.\n\n\t\n\t\tFor example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.\n\t\n\t\n\n\nYour penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.\n\nReturn the minimum possible penalty after performing the operations.\n\n \nExample 1:\n\nInput: nums = [9], maxOperations = 2\nOutput: 3\nExplanation: \n- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n\n\nExample 2:\n\nInput: nums = [2,4,8,2], maxOperations = 4\nOutput: 2\nExplanation:\n- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2 an you should return 2.\n\n\nExample 3:\n\nInput: nums = [7,17], maxOperations = 2\nOutput: 7\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= maxOperations, nums[i] <= 109\n\n", "solution_py": "class Solution:\n def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n l, r = 1, max(nums)\n while l < r:\n mid = (l + r) // 2\n if sum([(n - 1) // mid for n in nums]) > maxOperations: \n l = mid + 1\n else:\n r = mid\n return l", "solution_js": "var minimumSize = function(nums, maxOperations) {\n let i = 1\n let j = Math.max(...nums)\n\n while (i <= j) {\n let mid = Math.floor((j-i)/2 + i)\n let count = 0\n nums.forEach(n => count += Math.floor((n-1)/mid))\n\n if (count <= maxOperations) {\n j = mid - 1\n } else {\n i = mid + 1\n }\n }\n return i\n};", "solution_java": "class Solution {\n public int minimumSize(int[] nums, int maxOperations) {\n\t//initiate the boundary for possible answers, here if you let min=1 it will still work for most cases except for some corner cases. We make max=100000000 because nums[i] <= 10^9. You can choose to sort the array and make the max= arr.max, at the price of time consumption.\n\t//The answer should be the minimized max value.\n int min = 0;\n int max = 1000000000;\n\t\t//Compared with min math.ceil(a/mid) gives the number of divided bags, we subtract the number by 1 to get the subdivision operation times.\n count+=(a-1)/mid;\n }\n\t\t\t//if count < maxOperations, max WOULD be further minimized and set to mid; \n\t\t\t//if count = maxOperations, max still COULD be further minimized and set to mid. \n\t\t\t//so we combine < and = cases together in one if condition\n if (count <= maxOperations) {\n\t\t\t//max = mid - 1 will not work in this case becasue mid could be the correct answer. \n\t\t\t//To not miss the correct answer we set a relatively \"loose\" boundary for max and min.\n max = mid;\n } else{\n min = mid;\n }\n }\n\t\t//Now we find the minimized max value\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPossible(vector&nums,int mid_penalty,int maxOperations)\n {\n int operations=0;\n\n for(int i=0;i& nums, int maxOperations) {\n int low_penalty=1,high_penalty=*max_element(nums.begin(),nums.end());\n int ans=high_penalty;\n while(low_penalty<=high_penalty)\n {\n int mid_penalty=low_penalty+(high_penalty-low_penalty)/2;\n if(mid_penalty==0) //To avoid divison by zero.\n break;\n if(isPossible(nums,mid_penalty,maxOperations))\n {\n ans=mid_penalty;\n high_penalty=mid_penalty-1;\n }\n else\n low_penalty=mid_penalty+1;\n }\n return ans;\n }\n};" }, { "title": "Count Servers that Communicate", "algo_input": "You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers that communicate with any other server.\n\n \nExample 1:\n\n\n\nInput: grid = [[1,0],[0,1]]\nOutput: 0\nExplanation: No servers can communicate with others.\n\nExample 2:\n\n\n\nInput: grid = [[1,0],[1,1]]\nOutput: 3\nExplanation: All three servers can communicate with at least one other server.\n\n\nExample 3:\n\n\n\nInput: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput: 4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m <= 250\n\t1 <= n <= 250\n\tgrid[i][j] == 0 or 1\n\n", "solution_py": "class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n def helper(row,col,count):\n for c in range(len(grid[0])):\n if c == col:\n continue\n if grid[row][c] == 1:\n count += 1\n return count\n for r in range(len(grid)):\n if r == row:\n continue\n if grid[r][col] == 1:\n count += 1\n return count\n return count\n count = 0\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if grid[row][col] == 1:\n count = helper(row,col,count)\n return count", "solution_js": "var countServers = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n \n const lastRows = [];\n const lastCols = [];\n \n const set = new Set();\n \n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) { \n const currIdx = (i * n) + j;\n \n const rowNeiIdx = lastRows[i];\n \n if (rowNeiIdx != null) {\n set.add(currIdx).add(rowNeiIdx);\n }\n \n const colNeiIdx = lastCols[j];\n \n if (colNeiIdx != null) {\n set.add(currIdx).add(colNeiIdx);\n }\n \n lastRows[i] = currIdx;\n lastCols[j] = currIdx;\n }\n }\n }\n \n return set.size; \n};", "solution_java": "class Solution {\n int []parent;\n int []rank;\n public int countServers(int[][] grid) {\n parent=new int[grid.length*grid[0].length];\n rank=new int[grid.length*grid[0].length];\n for(int i=0;i0){\n count++;\n }\n }\n return count;\n }\n public void check(int sr,int sc,int [][]grid){\n int mbox=sr*grid[0].length+sc;\n for(int i=sr;irank[y]){\n parent[y]=x;\n }else if(rank[y]>rank[x]){\n parent[x]=y;\n }else{\n parent[x]=y;\n rank[y]++;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int countServers(vector>& grid) {\n int n=grid.size(),m=grid[0].size();\n vector>visited(n,vector(m,false));\n for(int i=0;i None:\n \n curr = self.root\n \n for c in word:\n \n if c not in curr.children:\n curr.children[c] = TrieNode(c)\n \n curr = curr.children[c]\n \n curr.isEnd = True\n \n def search(self, word: str) -> bool:\n \n def dfs(root, word):\n curr = root\n\n for i in range(len(word)):\n\n if word[i] == \".\":\n for l in curr.children.values():\n if dfs(l, word[i+1:]) == True:\n return True\n \n return False\n\n if word[i] not in curr.children:\n return False\n\n curr = curr.children[word[i]]\n\n return curr.isEnd\n \n return dfs(self.root, word)", "solution_js": "var WordDictionary = function() {\n this.aryWordList = [];\n};\n\n/** \n * @param {string} word\n * @return {void}\n */\nWordDictionary.prototype.addWord = function(word) {\n this.aryWordList.push(word);\n};\n\n/** \n * @param {string} word\n * @return {boolean}\n */\nWordDictionary.prototype.search = function(word) {\n \nconst isWordsMatch = (first, second) =>\n {\n if (first.length !== second.length) return false; \n \n if (first.length == 0 && second.length == 0) return true; // Exit case for recursion\n\n if( first[0] === second[0] || first[0] === \".\" || second[0] === \".\")\n return isWordsMatch(first.substring(1),\n second.substring(1));\n\n return false;\n}\n \n const isWordFound = () => {\n let isFound = false;\n for(var indexI=0; indexI next;\n tr() {\n next.resize(26, NULL);\n isword = false;\n }\n };\n\n tr *root;\n WordDictionary() {\n root = new tr();\n }\n\n void addWord(string word) {\n tr *cur = root;\n\n for(auto c: word) {\n if(cur->next[c-'a'] == NULL) {\n cur->next[c-'a'] = new tr();\n }\n cur = cur->next[c-'a'];\n }\n\n cur->isword = true;\n }\n\n bool dfs(string& word, int i, tr* cur) {\n if(!cur ){\n return false;\n }\n\n if(i == word.size()) {\n return cur->isword;\n }\n\n for (; i < word.size(); i++) {\n char c = word[i];\n if (c == '.') {\n for (auto it: cur->next) {\n if(dfs(word, i+1, it)) {\n return true;\n }\n }\n return false;\n }\n else {\n if(cur->next[c-'a'] == NULL) {\n return false;\n }\n cur = cur->next[c-'a'];\n }\n }\n\n return cur->isword;\n }\n\n bool search(string word) {\n return dfs(word, 0, root);\n }\n};\n\n/**\n * Your WordDictionary object will be instantiated and called as such:\n * WordDictionary* obj = new WordDictionary();\n * obj->addWord(word);\n * bool param_2 = obj->search(word);\n */" }, { "title": "Lowest Common Ancestor of a Binary Search Tree", "algo_input": "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”\n\n \nExample 1:\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput: 6\nExplanation: The LCA of nodes 2 and 8 is 6.\n\n\nExample 2:\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput: 2\nExplanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n\n\nExample 3:\n\nInput: root = [2,1], p = 2, q = 1\nOutput: 2\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 105].\n\t-109 <= Node.val <= 109\n\tAll Node.val are unique.\n\tp != q\n\tp and q will exist in the BST.\n\n", "solution_py": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \n if ((root.val >= p.val) and (root.val <= q.val)) or ((root.val >= q.val) and (root.val <= p.val)):\n return root\n elif (root.val > p.val):\n return self.lowestCommonAncestor(root.left, p, q)\n else:\n return self.lowestCommonAncestor(root.right, p , q)", "solution_js": "var lowestCommonAncestor = function(root, p, q) {\n while(root){\n if(p.val>root.val && q.val>root.val){\n root=root.right\n }else if(p.valvalval && q->valval) return lowestCommonAncestor(root->left,p,q);\n else if(p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right,p,q);\n return root;\n }\n};" }, { "title": "Painting a Grid With Three Different Colors", "algo_input": "You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.\n\nReturn the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: m = 1, n = 1\nOutput: 3\nExplanation: The three possible colorings are shown in the image above.\n\n\nExample 2:\n\nInput: m = 1, n = 2\nOutput: 6\nExplanation: The six possible colorings are shown in the image above.\n\n\nExample 3:\n\nInput: m = 5, n = 5\nOutput: 580986\n\n\n \nConstraints:\n\n\n\t1 <= m <= 5\n\t1 <= n <= 1000\n\n", "solution_py": "class Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n from functools import reduce\n MOD = 10**9 + 7\n sum_mod = lambda x,y: (x+y)%MOD\n \n def normalize(pat_var):\n mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n return tuple([ mapping[e] for e in pat_var])\n \n def get_pats(m, i, pat, pats):\n if i == m-1:\n pats.append(tuple(pat))\n return\n i_nx = i+1\n for p_it_nx in (1,2,3):\n if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n pat.append(p_it_nx)\n get_pats(m, i_nx, pat, pats)\n pat.pop()\n return pats\n \n def get_trans(pat, i, pat_pre, trans):\n if i == len(pat)-1:\n pat_nl = normalize(pat_pre)\n trans[pat_nl] = trans.get(pat_nl, 0) + 1\n return\n for p_it_pre in (1,2,3):\n i_nx = i+1\n if (p_it_pre != pat[i_nx]\n and (not pat_pre or p_it_pre != pat_pre[-1])):\n pat_pre.append(p_it_pre)\n get_trans(pat, i_nx, pat_pre, trans)\n pat_pre.pop()\n return trans\n\n pats = get_pats(m, -1, [], [])\n # {pattern_i: {pattern_pre:count}}\n pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } \n \n p_counts = { pat:1 for pat in pat_trans.keys() }\n for i in range(n-1):\n p_counts_new = {}\n for pat, trans in pat_trans.items():\n p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n p_counts = p_counts_new\n \n res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n return (res * perms) % MOD", "solution_js": "// transform any decimal number to its ternary representation\nlet ternary=(num,len)=>{\n let A=[],times=0\n while(times++Array.every((d,i)=>i==0||d!==Array[i-1])\n//main\nvar colorTheGrid = function(n, m) {\n let mod=1e9+7,adj=[...Array(3**(n))].map(d=>new Set()),\n //1.turn every potential state to a ternary(base3) representation\n base3=[...Array(3**n)].map((d,i)=>ternary(i,n)),\n\t\t//3 conditions such that state a can be previous to state b \n ok=(a,b)=>adjdiff(base3[a])&& adjdiff(base3[b])&& base3[a].every( (d,i)=>d!==base3[b][i])\n //2.determine what are the acceptable adjacent states of any given state\n for(let m1=0;m1<3**n;m1++)\n for(let m2=0;m2<3**n;m2++)\n if(ok(m1,m2))\n adj[m1].add(m2),adj[m2].add(m1)\n //3.do 2-row dp, where dp[state]= the number of colorings where the last line is colored based on state\n let dp=[...Array(3**n)].map((d,i)=>Number(adjdiff(base3[i])))\n for(let i=1,dp2=[...Array(3**n)].map(d=>0);i (a+c) %mod ,0)\n};", "solution_java": "class Solution \n{\n static int mod=(int)(1e9+7);\n public static int dfs(int n,ArrayList> arr,int src,int dp[][])\n {\n if(n==0)\n {\n return 1;\n }\n if(dp[n][src]!=-1)\n {\n return dp[n][src];\n }\n int val=0;\n for(Integer ap:arr.get(src))\n {\n val=(val%mod+dfs(n-1,arr,ap,dp)%mod)%mod;\n }\n return dp[n][src]=val;\n }\n public static void val(ArrayList arr,int color,int m,String s)\n {\n if(m==0)\n {\n arr.add(s);\n return;\n }\n for(int i=0;i<3;i++)\n {\n if(color!=i)\n val(arr,i,m-1,s+i);\n }\n }\n public static boolean Match(String s,String s1)\n {\n for(int i=0;i arr=new ArrayList();\n for(int i=0;i<3;i++)\n {\n String s=\"\";\n val(arr,i,m-1,s+i);\n }\n ArrayList> adj=new ArrayList>();\n for(int i=0;i());\n }\n \n for(int i=0;i moves;\nint MOD = 1e9 + 7;\nvoid fill(string s, int n, int p){\n if(n==0){\n moves.push_back(s);\n return;\n }\n for(int i=1; i<4; i++){\n if(p==i){\n continue;\n }\n string m = to_string(i);\n fill(s+m, n-1, i);\n }\n return;\n}\nclass Solution {\npublic:\n vector>memo;\n int solve(int n, int lastIdx, int m){\n if (n == 0) return 1;\n int ret = 0;\n if (memo[n][lastIdx] != -1) return memo[n][lastIdx];\n string last = moves[lastIdx];\n for (int idx = 0; idx(moves.size(), -1));\n int ret = 0;\n for (int idx = 0; idx < moves.size(); idx++)\n ret = (ret + solve(n-1, idx, m)%MOD)%MOD;\n return ret;\n }\n};" }, { "title": "Count Words Obtained After Adding a Letter", "algo_input": "You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.\n\nFor each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.\n\nThe conversion operation is described in the following two steps:\n\n\n\tAppend any lowercase letter that is not present in the string to its end.\n\n\t\n\t\tFor example, if the string is \"abc\", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be \"abcd\".\n\t\n\t\n\tRearrange the letters of the new string in any arbitrary order.\n\t\n\t\tFor example, \"abcd\" can be rearranged to \"acbd\", \"bacd\", \"cbda\", and so on. Note that it can also be rearranged to \"abcd\" itself.\n\t\n\t\n\n\nReturn the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.\n\nNote that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.\n\n \nExample 1:\n\nInput: startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\nOutput: 2\nExplanation:\n- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n Note that \"act\" does exist in startWords, but we must append one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.\n\n\nExample 2:\n\nInput: startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\nOutput: 1\nExplanation:\n- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".\n\n\n \nConstraints:\n\n\n\t1 <= startWords.length, targetWords.length <= 5 * 104\n\t1 <= startWords[i].length, targetWords[j].length <= 26\n\tEach string of startWords and targetWords consists of lowercase English letters only.\n\tNo letter occurs more than once in any string of startWords or targetWords.\n\n", "solution_py": "# Brute Force\n# O(S * T); S := len(startWors); T := len(targetWords)\n# TLE\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n cnt = 0\n for target in targetWords:\n for start in startWords:\n if len(target) - len(start) == 1 and len(set(list(target)) - set(list(start))) == 1:\n cnt += 1\n break\n return cnt\n\n# Sort + HashSet Lookup\n# O(S + T) Time\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n # Sort each start word and add it to a hash set\n startWords_sorted = set()\n # O(S*26*log(26))\n for word in startWords:\n startWords_sorted.add(\"\".join(sorted(list(word))))\n \n # sort each target word and add it to a list\n # O(T*26*log(26))\n targetWords_sorted = []\n for word in targetWords:\n targetWords_sorted.append(sorted(list(word)))\n \n # for each sorted target word, we remove a single character and \n # check if the resulting word is in the startWords_sorted\n # if it is, we increment cnt and break the inner loop\n # otherwise we keep removing until we either find a hit or reach the\n # end of the string\n # O(T*26) = O(T)\n cnt = 0\n for target in targetWords_sorted:\n for i in range(len(target)):\n w = target[:i] + target[i+1:]\n w = \"\".join(w)\n if w in startWords_sorted:\n cnt += 1\n break\n \n return cnt\n\n# Using Bit Mask\n# O(S + T) Time\n# Similar algorithm as the one above, implemented using a bit mask to avoid the sorts\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n start_set = set()\n # O(S * 26)\n for word in startWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n start_set.add(m)\n \n # O(T * 2 * 26)\n cnt = 0\n for word in targetWords:\n m = 0\n for ch in word:\n i = ord(ch) - ord('a')\n m |= (1 << i)\n \n for ch in word:\n i = ord(ch) - ord('a')\n if m ^ (1 << i) in start_set:\n cnt += 1\n break\n return cnt", "solution_js": "var wordCount = function(startWords, targetWords) {\n const startMap = {};\n for(let word of startWords) {\n startMap[word.split('').sort().join('')] = true;\n }\n\n let ans = 0;\n for(let word of targetWords) {\n for(let i=0;i set = new HashSet<>();\n \n //1. store lexicographically sorted letters of startword in set\n for(String start: startWords){\n char[] sAr = start.toCharArray();\n Arrays.sort(sAr);\n set.add(new String(sAr));\n }\n int m = targetWords.length;\n boolean ans = false;\n for(int i = 0; i < m; i++){\n //2. sort lexicographically letters of targetword and store in new string s\n char[] tAr = targetWords[i].toCharArray();\n Arrays.sort(tAr);\n int k = tAr.length;\n String s = String.valueOf(tAr);\n \n ans = false;\n for(int j = 0; j < k; j++){\n //3. make a new string by omitting one letter from word and check if it is present in set than increase count value\n String str = s.substring(0,j) + s.substring(j+1);\n if(set.contains(str)){\n count++;\n break;\n }\n }\n }\n return count; \n }\n \n}", "solution_c": "class Solution {\npublic:\n int wordCount(vector& startWords, vector& targetWords) {\n set> hash;\n for (int i = 0; i < startWords.size(); i++) {\n vector counter(26, 0);\n for (char &x : startWords[i]) {\n counter[x - 'a']++;\n }\n hash.insert(counter); \n }\n \n \n int ans = 0;\n \n for (int i = 0; i < targetWords.size(); i++) {\n vector counter(26, 0);\n for (char &x : targetWords[i]) {\n counter[x - 'a']++;\n }\n \n for (int j = 0; j < 26; j++) {\n if (counter[j] == 1) {\n counter[j] = 0;\n \n if (hash.find(counter) != hash.end()) {\n ans++;\n break;\n }\n \n counter[j] = 1;\n }\n }\n }\n \n return ans;\n }\n};" }, { "title": "Delete Leaves With a Given Value", "algo_input": "Given a binary tree root and an integer target, delete all the leaf nodes with value target.\n\nNote that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).\n\n \nExample 1:\n\n\n\nInput: root = [1,2,3,2,null,2,4], target = 2\nOutput: [1,null,3,null,4]\nExplanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\n\n\nExample 2:\n\n\n\nInput: root = [1,3,3,3,2], target = 3\nOutput: [1,3,null,null,2]\n\n\nExample 3:\n\n\n\nInput: root = [1,2,null,2,null,2], target = 2\nOutput: [1]\nExplanation: Leaf nodes in green with value (target = 2) are removed at each step.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 3000].\n\t1 <= Node.val, target <= 1000\n\n", "solution_py": "class Solution:\n def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:\n if not root:\n return None\n root.left = self.removeLeafNodes(root.left, target)\n root.right = self.removeLeafNodes(root.right, target)\n if not root.left and not root.right and root.val == target:\n return None\n return root", "solution_js": "var removeLeafNodes = function(root, target) {\n const parent = new TreeNode(-1, root, null);\n\n const traverse = (r = root, p = parent, child = -1) => {\n if(!r) return null;\n traverse(r.left, r, -1);\n traverse(r.right, r, 1);\n if(r.left == null && r.right == null && r.val == target) {\n if(child == -1) p.left = null;\n else p.right = null;\n }\n }\n traverse();\n return parent.left;\n};", "solution_java": "class Solution {\n public TreeNode removeLeafNodes(TreeNode root, int target) {\n if(root==null)\n return root;\n root.left = removeLeafNodes(root.left,target);\n root.right = removeLeafNodes(root.right,target);\n if(root.left == null && root.right == null && root.val == target)\n root = null;\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 TreeNode* removeLeafNodes(TreeNode* root, int target) {\n if(root==NULL || root->left == NULL && root->right == NULL && root->val == target)\n return NULL;\n\n root->left = removeLeafNodes(root->left,target);\n root->right = removeLeafNodes(root->right,target);\n\n if(root->left == NULL && root->right == NULL && root->val == target)\n {\n return NULL;\n }\n\n return root;\n\n }\n};" }, { "title": "Maximum Value of K Coins From Piles", "algo_input": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.\n\nIn one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.\n\nGiven a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.\n\n \nExample 1:\n\nInput: piles = [[1,100,3],[7,8,9]], k = 2\nOutput: 101\nExplanation:\nThe above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.\n\n\nExample 2:\n\nInput: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput: 706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.\n\n\n \nConstraints:\n\n\n\tn == piles.length\n\t1 <= n <= 1000\n\t1 <= piles[i][j] <= 105\n\t1 <= k <= sum(piles[i].length) <= 2000\n\n", "solution_py": "class Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n n = len(piles)\n prefixSum = []\n for i in range(n):\n temp = [0]\n for j in range(len(piles[i])):\n temp.append(temp[-1] + piles[i][j])\n prefixSum.append(temp)\n \n dp = [[0] * (k + 1) for _ in range(n)]\n for j in range(1, k + 1):\n if j < len(prefixSum[0]):\n dp[0][j] = prefixSum[0][j]\n \n for i in range(1, n):\n for j in range(1, k + 1):\n for l in range(len(prefixSum[i])):\n if l > j:\n break\n dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l])\n return dp[n - 1][k]", "solution_js": "/**\n * @param {number[][]} piles\n * @param {number} k\n * @return {number}\n */\nvar maxValueOfCoins = function(piles, k) {\n var n = piles.length;\n var cache = {};\n \n var getMax = function(i, k) {\n if (i >= n || k <= 0) return 0;\n var key = i + ',' + k;\n if (cache[key] !== undefined) return cache[key];\n var ans = getMax(i + 1, k);\n var cur = 0;\n \n for (var j = 0; j < piles[i].length && j < k; j++) {\n cur+=piles[i][j];\n ans = Math.max(ans, cur + getMax(i + 1, k - j - 1));\n }\n \n return cache[key] = ans;\n }\n \n return getMax(0, k);\n};", "solution_java": "class Solution {\n public int maxValueOfCoins(List> piles, int k) {\n int n = piles.size();\n int[][] ans = new int[n+1][2001];\n Collections.sort(piles, (List a, List b) -> b.size() - a.size());\n for(int i = 1; i <= k; i++) {\n for(int j = 1; j <= n; j++) {\n int sizeOfPile = piles.get(j-1).size();\n List pile = piles.get(j-1);\n int sum = 0;\n ans[j][i] = ans[j-1][i];\n for(int l = 1; l <= Math.min(i, sizeOfPile); l++) {\n // Take K from this pile + remaining from previous piles\n sum += pile.get(l-1);\n int rem = i - l;\n ans[j][i] = Math.max(ans[j][i], sum + ans[j-1][rem]);\n }\n }\n }\n\n return ans[n][k];\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[1001][2001]; //Dp array For Memoization.\n int solve(vector>&v,int index,int coin)\n {\n if(index>=v.size()||coin==0) //Base Condition\n return 0;\n if(dp[index][coin]!=-1) //Check wheather It is Already Calculated Or not.\n return dp[index][coin];\n\n /* Our 1st choice :- We not take any Coin from that pile*/\n int ans=solve(v,index+1,coin); //Just Call function for next Pile.\n\n /*Otherwise we can take Coins from that Pile.*/\n int loop=v[index].size()-1;\n int sum=0;\n\n for(int j=0;j<=min(coin-1,loop);j++) //\n {\n sum=sum+v[index][j];\n ans=max(ans,sum+solve(v,index+1,coin-(j+1)));\n\n /*Aove we Pass coin-(j+1). Because till j'th index we have taken j+1 coin from that pile.*/\n }\n\n return dp[index][coin]=ans;\n }\n int maxValueOfCoins(vector>& piles, int k) {\n memset(dp,-1,sizeof(dp));\n return solve(piles,0,k);\n }\n};" }, { "title": "Couples Holding Hands", "algo_input": "There are n couples sitting in 2n seats arranged in a row and want to hold hands.\n\nThe people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).\n\nReturn the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.\n\n \nExample 1:\n\nInput: row = [0,2,1,3]\nOutput: 1\nExplanation: We only need to swap the second (row[1]) and third (row[2]) person.\n\n\nExample 2:\n\nInput: row = [3,2,0,1]\nOutput: 0\nExplanation: All couples are already seated side by side.\n\n\n \nConstraints:\n\n\n\t2n == row.length\n\t2 <= n <= 30\n\tn is even.\n\t0 <= row[i] < 2n\n\tAll the elements of row are unique.\n\n", "solution_py": "class Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n count = 0\n for i in range(0, len(row)-2, 2):\n idx = i+1\n if(row[i]%2 == 0):\n n = (row[i] + 2)//2\n newNo = 2*n - 1\n else:\n n = (row[i] + 1) //2;\n newNo = 2*n - 2\n for j in range(i, len(row)):\n if row[j] == newNo:\n idx = j\n break\n if idx != i+1:\n count += 1\n row[idx], row[i+1] = row[i+1], row[idx]\n return count\n\t\t```", "solution_js": "/**\n * @param {number[]} row\n * @return {number}\n */\nvar minSwapsCouples = function(row) {\n let currentPositions = [];\n\n for(let i=0;i parents=new HashMap<>();\n int count=0;\n for(int i=0;i7 , also place smaller number as parent for eg)//0,4 ; 1,3\n parents.put(i,i+1);\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n\tint minSwapsCouples(vector& row) {\n\t\tint cnt=0,n=row.size();\n\t\t// first of all making row element equal ex for [0,1],[2,3] --> [0,0] ,[2,2]\n\t\tfor(auto &x : row){\n\t\t\tif(x&1){\n\t\t\t\tx--;\n\t\t\t}\n\t\t}\n\n\t\tfor( int i=0; i{\n\n\tif(!curr) return false\n\n\tcurrentSum += curr.val;\n\n\tif(!curr.left && !curr.right) return currentSum === targetSum;\n\n\treturn DFS(curr.left, currentSum, targetSum) || DFS(curr.right, currentSum, targetSum)\n}", "solution_java": "class Solution {\n public boolean hasPathSum(TreeNode root, int targetSum) {\n if(root == null) return false;\n \n if(root.left == null && root.right == null) return root.val == targetSum;\n \n return hasPathSum(root.right, targetSum - root.val) || hasPathSum(root.left, targetSum - root.val);\n }\n}", "solution_c": "class Solution {\npublic:\n bool ans=false;\n int sum=0;\n void recur(TreeNode* root, int target){\n if(root==NULL)return;\n \n sum+=root->val;\n recur(root->left,target);\n recur(root->right,target);\n if(root->left==NULL && root->right==NULL&&sum == target){ // !!Check only if it is a leaf node....\n ans = true;\n return;\n }\n sum-=root->val; //backtracking\n return;\n \n }\n bool hasPathSum(TreeNode* root, int targetSum) {\n recur(root,targetSum);\n return ans;\n }\n};" }, { "title": "Building Boxes", "algo_input": "You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\n\n\n\tYou can place the boxes anywhere on the floor.\n\tIf box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.\n\n\nGiven an integer n, return the minimum possible number of boxes touching the floor.\n\n \nExample 1:\n\n\n\nInput: n = 3\nOutput: 3\nExplanation: The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\nExample 2:\n\n\n\nInput: n = 4\nOutput: 3\nExplanation: The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\nExample 3:\n\n\n\nInput: n = 10\nOutput: 6\nExplanation: The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\n", "solution_py": "class Solution:\n def minimumBoxes(self, n: int) -> int:\n r = 0\n while (n_upper := r*(r+1)*(r+2)//6) < n:\n r += 1\n m = r*(r+1)//2\n for i in range(r, 0, -1):\n if (n_upper - i) < n:\n break\n n_upper -= i\n m -= 1\n return m", "solution_js": "var minimumBoxes = function(n) {\n //Binary search for the height of the biggest triangle I can create with n cubes available.\n let lo=1,hi=n,result\n let totalCubes=x=>x*(x+1)*(x+2)/6 //the total cubes of a triangle with height x \n while(lo+1>1\n if(totalCubes(mid)<=n)\n lo=mid\n else \n hi=mid\n }\n\tlet f=(x)=>Math.floor(Math.sqrt(2*x)+1/2)// the i-th element of the sequence 1,2,2,3,3,3,4,4,4,4,5,...\n result=(lo)*(lo+1)/2// the base of the largest complete triangle 1+2+3+..+H\n n-=totalCubes(lo) //remove the cubes of the complete triangle\n return result+f(n) // the base of the largest+ the extra floor cubes\n};", "solution_java": "class Solution {\n\n static final double ONE_THIRD = 1.0d / 3.0d;\n\n public int minimumBoxes(int n) {\n int k = findLargestTetrahedralNotGreaterThan(n);\n int used = tetrahedral(k);\n int floor = triangular(k);\n int unused = (n - used);\n if (unused == 0) {\n return floor;\n }\n int r = findSmallestTriangularNotLessThan(unused);\n return (floor + r);\n }\n\n private final int findLargestTetrahedralNotGreaterThan(int te) {\n int a = (int) Math.ceil(Math.pow(product(6, te), ONE_THIRD));\n while (tetrahedral(a) > te) {\n a--;\n }\n return a;\n }\n\n private final int findSmallestTriangularNotLessThan(int t) {\n int a = -1 + (int) Math.floor(Math.sqrt(product(t, 2)));\n while (triangular(a) < t) {\n a++;\n }\n return a;\n }\n\n private final int tetrahedral(int a) {\n return (int) ratio(product(a, a + 1, a + 2), 6);\n }\n\n private final int triangular(int a) {\n return (int) ratio(product(a, a + 1), 2);\n }\n\n private final long product(long... vals) {\n long product = 1L;\n for (long val : vals) {\n product *= val;\n }\n return product;\n }\n\n private final long ratio(long a, long b) {\n return (a / b);\n }\n\n}", "solution_c": "class Solution {\npublic:\n int minimumBoxes(int n) {\n \n // Find the biggest perfect pyramid\n uint32_t h = cbrt((long)6*n);\n uint32_t pyramid_box_num = h*(h+1)/2*(h+2)/3; // /6 is split to /2 and /3 to avoid long to save space\n if ( pyramid_box_num > n ){\n h--;\n pyramid_box_num = h*(h+1)/2*(h+2)/3; // /6 is split to /2 and /3 to avoid long to save space\n }\n \n // Calculate how many floor-touching boxes in the pyramid\n int pyramid_base_num = (h)*(h+1)/2;\n \n // Get the number of boxes to be added to the perfect pyramid\n n -= pyramid_box_num;\n \n // Find how many floor-touching boxes are added\n int z = sqrt(2*n);\n int max_box_added = z*(z+1)/2;\n if ( max_box_added < n)\n z++;\n \n return pyramid_base_num+z;\n }\n};" }, { "title": "Deepest Leaves Sum", "algo_input": "Given the root of a binary tree, return the sum of values of its deepest leaves.\n \nExample 1:\n\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\n\n\nExample 2:\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 19\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 <= Node.val <= 100\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 \n \"\"\"\n THOUGHT PROCESS:\n 1) find the height of the tree, this way we would know how deep we need to go.\n 2) we need a counter to check how deep we are and this is not available in deepestLeavesSum so we create a new function deepestLeave.\n 3) now we go in depth, if we are at bottom, we return the value, we recursively visit both left and right nodes.\n \n \"\"\"\n \n def height(self, root):\n if root is None:\n return 0\n else:\n x, y = 1, 1\n if root.left:\n x = self.height(root.left)+1\n if root.right:\n y = self.height(root.right)+1\n \n return max(x, y)\n \n \n def deepestLeave(self, root, depth):\n \n if root is None:\n return 0\n \n if root.left is None and root.right is None:\n if depth == 1:\n return root.val\n \n return self.deepestLeave(root.left, depth-1) + self.deepestLeave(root.right, depth-1)\n \n def deepestLeavesSum(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.deepestLeave(root, self.height(root))\n \n \n \n \n ", "solution_js": "var deepestLeavesSum = function(root) {\n let queue = [];\n queue.push([root, 0]);\n let sum = 0;\n let curLevel = 0\n let i = 0;\n while(queue.length-i > 0) {\n let [node, level] = queue[i];\n queue[i] = null;\n i++;\n if(level > curLevel) {\n sum = 0;\n curLevel = level;\n }\n sum += node.val;\n if(node.left != null) queue.push([node.left, level+1]);\n if(node.right != null) queue.push([node.right, level+1]);\n }\n return sum;\n //time: o(n)\n //space: o(n)\n};", "solution_java": "class Solution {\n public int height(TreeNode root)\n {\n if(root == null)\n return 0;\n return Math.max(height(root.left), height(root.right)) + 1;\n }\n public int deepestLeavesSum(TreeNode root) {\n if(root == null) return 0;\n if(root.left == null && root.right == null) return root.val;\n Queue q = new LinkedList<>();\n q.add(root);\n q.add(null);\n int hght = height(root);\n int sum = 0;\n while(q.size()>0 && q.peek()!=null)\n {\n TreeNode temp = q.remove();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n if(q.peek() == null)\n {\n q.remove();\n q.add(null);\n hght--;\n }\n if(hght == 1)\n {\n while(q.size()>0 && q.peek()!=null)\n {\n sum+=q.remove().val;\n }\n }\n\n }\n return sum;\n }\n}", "solution_c": "\t\t\t\t\t\t**\t#Vote if u like ❤️**\n\t\t\t\t\t\t\t\n\tclass Solution {\n\tpublic:\n\t\tvoid fun(TreeNode *root , int l , map> &m)\n\t\t{\n\t\t\tif(root == NULL) return; //If root is NULL it will return \n\t\t\tm[l].push_back(root -> val); //With level as key inserting the value to the vector\n\t\t\tfun(root -> left, l + 1, m); // passing the left with level + 1 \n\t\t\tfun(root -> right, l + 1 , m); // passing right with level + 1\n\t\t}\n\t\tint deepestLeavesSum(TreeNode* root) {\n\t\t\tmap> m; // Map with key as level and value of vector for storing the values\n\t\t\tfun(root , 0 , m); // A void fun with map and level as 0\n\t\t auto itr = m.rbegin(); //Hence we need the leaves node the nodes are present in last level \n\t\t\tint sum = 0; // Sum Variable \n\t\t\tfor(int i = 0; i < itr-> second.size(); i++) {sum += itr -> second[i];}\n\t\t\treturn sum;\n\t\t}\n\t};\n\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t-Yash:)" }, { "title": "Final Prices With a Special Discount in a Shop", "algo_input": "Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.\n\nReturn an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.\n\n \nExample 1:\n\nInput: prices = [8,4,6,2,3]\nOutput: [4,2,4,2,3]\nExplanation: \nFor item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4. \nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2. \nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4. \nFor items 3 and 4 you will not receive any discount at all.\n\n\nExample 2:\n\nInput: prices = [1,2,3,4,5]\nOutput: [1,2,3,4,5]\nExplanation: In this case, for all items, you will not receive any discount at all.\n\n\nExample 3:\n\nInput: prices = [10,1,1,6]\nOutput: [9,0,1,6]\n\n\n \nConstraints:\n\n\n\t1 <= prices.length <= 500\n\t1 <= prices[i] <= 10^3\n\n", "solution_py": "class Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n ## RC ##\n ## APPROACH : STACK ##\n ## LOGIC ## \n ## 1. Use Monotonic Increasing Stack Concept\n ## 2. Main idea is to find the Next Smaller Element in O(N) using #1\n stack = []\n for i, num in enumerate(prices):\n while(stack and prices[stack[-1]] >= num):\n popIndex = stack.pop()\n prices[popIndex] -= num\n stack.append(i)\n return prices", "solution_js": "var finalPrices = function(prices) {\n let adjPrices = [];\n while(prices.length) {\n let currentPrice = prices[0];\n \n // Remove first price in original array\n // Since we're looking for a price less than or equal to\n prices.shift();\n \n let lowerPrice = prices.find((a) => a <= currentPrice);\n adjPrices.push(lowerPrice ? currentPrice - lowerPrice : currentPrice);\n }\n \n return adjPrices;\n};", "solution_java": "class Solution {\n public int[] finalPrices(int[] prices) {\n for(int i = 0; i < prices.length; i++){\n for(int j = i + 1; j < prices.length; j++){\n if(j > i && prices[j] <= prices[i]){\n prices[i] -= prices[j];\n break;\n }\n }\n }\n return prices;\n }\n}", "solution_c": "class Solution {\npublic:\n vector finalPrices(vector& prices) {\n vectorsk;\n for(int i=0;i=prices[j]){\n discount=prices[i]-prices[j];\n break;\n }\n\n }\n sk.push_back(discount);\n }\n return sk;\n }\n};" }, { "title": "Median of Two Sorted Arrays", "algo_input": "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\n\nThe overall run time complexity should be O(log (m+n)).\n\n \nExample 1:\n\nInput: nums1 = [1,3], nums2 = [2]\nOutput: 2.00000\nExplanation: merged array = [1,2,3] and median is 2.\n\n\nExample 2:\n\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 2.50000\nExplanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n\n\n \nConstraints:\n\n\n\tnums1.length == m\n\tnums2.length == n\n\t0 <= m <= 1000\n\t0 <= n <= 1000\n\t1 <= m + n <= 2000\n\t-106 <= nums1[i], nums2[i] <= 106\n\n", "solution_py": "class Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n lis = nums1 + nums2\n lis.sort()\n hi = len(lis)\n print(5/2)\n if hi%2 == 0:\n if (lis[hi/2] + lis[hi/2-1])%2 == 0:\n return (lis[hi/2] + lis[hi/2-1] )/2\n return (lis[hi/2] + lis[hi/2-1])/2 + 0.5\n else:\n return lis[hi//2]", "solution_js": "var findMedianSortedArrays = function(nums1, nums2) {\n let nums3 = nums1.concat(nums2).sort((a,b) => a - b)\n if(nums3.length % 2 !== 0) return nums3[(nums3.length-1)/2]\n return (nums3[nums3.length/2] + nums3[nums3.length/2 - 1])/2\n};", "solution_java": "class Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n if(nums1.length==1 && nums2.length==1) return (double)(nums1[0]+nums2[0])/2.0;\n int i = 0;\n int j = 0;\n int k = 0;\n int nums[] = new int[nums1.length + nums2.length];\n if(nums1.length !=0 && nums2.length != 0){\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] < nums2[j]){\n nums[k] = nums1[i];\n i++;\n k++;\n }else{\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n while(i < nums1.length){\n nums[k] = nums1[i];\n i++;\n k++;\n }\n while(j < nums2.length){\n nums[k] = nums2[j];\n j++;\n k++;\n }\n }\n if(nums1.length==0){\n for(int h: nums2){\n nums[k] = h;\n k++;\n }\n }\n\n if(nums2.length==0){\n for(int d : nums1){\n nums[k] = d;\n k++;\n }\n }\n\n int mid = (nums.length / 2);\n\n if (nums.length % 2 == 0) {\n return ((double) nums[mid] + (double) nums[mid - 1]) / 2.0;\n } else {\n return nums[mid];\n }\n }\n}", "solution_c": "class Solution {\npublic:\n \n \n //Merging two arrays :- \n vector mergeSortedArrays(vector&arr1,vector&arr2){\n int n = arr1.size();\n int m = arr2.size();\n vector ans(m+n);\n int i = 0;\n int j = 0;\n int mainIndex = 0;\n \n while( i < n && j < m ){\n if(arr1[i] <= arr2[j])ans[mainIndex++] = arr1[i++];\n else ans[mainIndex++] = arr2[j++];\n }\n \n while( i < n){\n ans[mainIndex++] = arr1[i++];\n }\n \n while( j < m){\n ans[mainIndex++] = arr2[j++];\n }\n return ans;\n }\n double findMedianSortedArrays(vector& nums1, vector& nums2) {\n vector ans = mergeSortedArrays(nums1,nums2);\n float median = 0;\n int n = ans.size()-1;\n \n if(n%2 != 0)\n median=(ans[n/2]+ans[(n/2)+1])/2.0; \n else\n median=ans[n/2]; \n return median;\n \n }\n};" }, { "title": "Search Suggestions System", "algo_input": "You are given an array of strings products and a string searchWord.\n\nDesign a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.\n\nReturn a list of lists of the suggested products after each character of searchWord is typed.\n\n \nExample 1:\n\nInput: products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput: [\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mobile\",\"moneypot\",\"monitor\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"],\n[\"mouse\",\"mousepad\"]\n]\nExplanation: products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"]\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"]\n\n\nExample 2:\n\nInput: products = [\"havana\"], searchWord = \"havana\"\nOutput: [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n\n\nExample 3:\n\nInput: products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\nOutput: [[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"],[\"bags\"]]\n\n\n \nConstraints:\n\n\n\t1 <= products.length <= 1000\n\t1 <= products[i].length <= 3000\n\t1 <= sum(products[i].length) <= 2 * 104\n\tAll the strings of products are unique.\n\tproducts[i] consists of lowercase English letters.\n\t1 <= searchWord.length <= 1000\n\tsearchWord consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n sorted_products = sorted(products)\n res = []\n prefix = ''\n for letter in searchWord:\n prefix += letter\n words = []\n for product in sorted_products:\n if len(words) == 3:\n break\n if product.startswith(prefix):\n words.append(product)\n res.append(words) \n return res", "solution_js": "function TrieNode(key) {\n this.key = key\n this.parent = null\n this.children = {}\n this.end = false\n \n this.getWord = function() {\n let output = []\n let node = this\n \n while(node !== null) {\n output.unshift(node.key)\n node = node.parent\n }\n \n return output.join('')\n }\n} \n\nfunction Trie() {\n this.root = new TrieNode(null)\n \n this.insert = function(word) {\n let node = this.root\n \n for (let i = 0; i < word.length; i++) {\n if (!node.children[word[i]]) {\n node.children[word[i]] = new TrieNode(word[i])\n node.children[word[i]].parent = node\n }\n \n node = node.children[word[i]]\n \n if (i === word.length - 1) {\n node.end = true\n }\n }\n }\n \n this.findAllWords = function (node, arr) {\n if (node.end) {\n arr.unshift(node.getWord());\n }\n\n for (let child in node.children) {\n this.findAllWords(node.children[child], arr);\n }\n }\n \n this.find = function(prefix) {\n let node = this.root\n let output = []\n\n for(let i = 0; i < prefix.length; i++) {\n if (node.children[prefix[i]]) {\n node = node.children[prefix[i]]\n } else {\n return output\n }\n }\n\n this.findAllWords(node, output)\n \n output.sort()\n\n return output.slice(0, 3)\n }\n \n this.search = function(word) {\n let node = this.root\n let output = []\n \n for (let i = 0; i < word.length; i++) {\n output.push(this.find(word.substring(0, i + 1)))\n }\n \n return output\n }\n}\n\n/**\n * @param {string[]} products\n * @param {string} searchWord\n * @return {string[][]}\n */\nvar suggestedProducts = function(products, searchWord) {\n let trie = new Trie()\n \n for (let product of products) {\n trie.insert(product)\n }\n \n return trie.search(searchWord)\n};", "solution_java": "class Solution\n{\n public List> suggestedProducts(String[] products, String searchWord)\n {\n PriorityQueue pq= new PriorityQueue();\n List> res= new LinkedList>();\n List segment= new LinkedList();\n for(int i=0;i();\n pq= reduce(pq,searchWord.substring(0,j+1));\n PriorityQueue pri= new PriorityQueue<>(pq);\n int p=0;\n while(p reduce(PriorityQueue pr, String filter)\n {\n PriorityQueue p= new PriorityQueue<>();\n String s=\"\";\n while(!pr.isEmpty())\n {\n s=pr.poll();\n if(s.startsWith(filter))\n p.add(s);\n }\n return p;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> suggestedProducts(vector& products, string searchWord) {\n map> m;\n vector> res;\n for (int i = 0; i < products.size(); i++)\n {\n int j = 0;\n while (products[i][j] == searchWord[j] && j < searchWord.size())\n {\n if (m.count(j) == 0)\n {\n vector v;\n v.push_back(products[i]);\n m.insert(make_pair(j, v));\n }\n else\n {\n m[j].push_back(products[i]);\n }\n j++;\n }\n }\n for (int i = 0; i < searchWord.size(); i++)\n {\n if (i < m.size())\n {\n sort(m[i].begin(), m[i].end());\n int a;\n if (3 <= m[i].size())\n {\n a = 3;\n }\n else\n {\n a = m[i].size();\n }\n m[i].resize(a);\n res.push_back(m[i]);\n }\n else\n {\n res.push_back({});\n }\n }\n return res;\n }\n};" }, { "title": "Check if the Sentence Is Pangram", "algo_input": "A pangram is a sentence where every letter of the English alphabet appears at least once.\n\nGiven a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.\n\n \nExample 1:\n\nInput: sentence = \"thequickbrownfoxjumpsoverthelazydog\"\nOutput: true\nExplanation: sentence contains at least one of every letter of the English alphabet.\n\n\nExample 2:\n\nInput: sentence = \"leetcode\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= sentence.length <= 1000\n\tsentence consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n return len(set(sentence))==26", "solution_js": "var checkIfPangram = function(sentence) {\n return new Set(sentence.split(\"\")).size == 26;\n};", "solution_java": "class Solution {\n public boolean checkIfPangram(String sentence) {\n int seen = 0;\n for(char c : sentence.toCharArray()) {\n int ci = c - 'a';\n seen = seen | (1 << ci);\n }\n return seen == ((1 << 26) - 1);\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkIfPangram(string sentence) {\n vector v(26,0);\n for(auto x:sentence)\n {\n v[x-'a'] = 1;\n }\n return accumulate(begin(v),end(v),0) == 26;\n }\n};" }, { "title": "Alphabet Board Path", "algo_input": "On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].\n\nHere, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"], as shown in the diagram below.\n\n\n\nWe may make the following moves:\n\n\n\t'U' moves our position up one row, if the position exists on the board;\n\t'D' moves our position down one row, if the position exists on the board;\n\t'L' moves our position left one column, if the position exists on the board;\n\t'R' moves our position right one column, if the position exists on the board;\n\t'!' adds the character board[r][c] at our current position (r, c) to the answer.\n\n\n(Here, the only positions that exist on the board are positions with letters on them.)\n\nReturn a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.\n\n \nExample 1:\nInput: target = \"leet\"\nOutput: \"DDR!UURRR!!DDD!\"\nExample 2:\nInput: target = \"code\"\nOutput: \"RR!DDRR!UUL!R!\"\n\n \nConstraints:\n\n\n\t1 <= target.length <= 100\n\ttarget consists only of English lowercase letters.\n", "solution_py": "class Solution:\n def alphabetBoardPath(self, target: str) -> str:\n def shortestPath(r,c,tr,tc):\n path = \"\"\n pr = r\n while r > tr:\n path += 'U'\n r -= 1\n while r < tr:\n path += 'D'\n r += 1\n if tr == 5 and pr != tr: path = path[:len(path) - 1]\n while c > tc:\n path += 'L'\n c -= 1\n while c < tc:\n path += 'R'\n c += 1\n if tr == 5 and pr != tr: path = path + 'D'\n return path\n\n table = ['abcde','fghij','klmno','pqrst','uvwxy','z']\n r,c = 0,0\n ans = \"\"\n for character in target:\n t_row = None\n for i,word in enumerate(table):\n if character in word:\n t_row = i\n break\n t_col = table[i].index(character)\n ans += shortestPath(r,c,t_row,t_col) + '!'\n r,c = t_row,t_col\n return ans", "solution_js": "var alphabetBoardPath = function(target) {\n var result = \"\";\n var list = \"abcdefghijklmnopqrstuvwxyz\";\n var curr = 0;\n for(i=0;i0) curr+=diff, result+=\"R\".repeat(diff);\n else curr+=diff, result+=\"L\".repeat(-diff); \n }\n diff = (next-curr)/5;\n if(diff>0) curr+=diff*5, result+=\"D\".repeat(diff);\n else curr+=diff*5, result+=\"U\".repeat(-diff); \n }\n result+='!';\n }\n return result;\n};", "solution_java": "class Solution {\n public String alphabetBoardPath(String target) {\n int x = 0, y = 0;\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < target.length(); i++){\n char ch = target.charAt(i);\n int x1 = (ch - 'a') / 5;\n int y1 = (ch - 'a') % 5;\n while(x1 < x) {x--; sb.append('U');}\n while(y1 > y) {y++; sb.append('R');}\n while(y1 < y) {y--; sb.append('L');}\n while(x1 > x) {x++; sb.append('D');}\n sb.append('!');\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string alphabetBoardPath(string target) {\n string ans = \"\";\n int prevRow = 0;\n int prevCol = 0;\n int curRow = 0;\n int curCol = 0;\n for(int i = 0; i < target.length(); i++){\n prevCol = curCol;\n prevRow = curRow;\n curRow = (target[i] - 'a')/5;\n curCol = (target[i] - 'a')%5;\n if(curRow == 5 and abs(curCol - prevCol) > 0){\n curRow--;\n }\n if(curRow - prevRow > 0){\n ans += string((curRow - prevRow), 'D');\n }else{\n ans += string((prevRow - curRow), 'U');\n }\n if(curCol - prevCol > 0){\n ans += string((curCol - prevCol), 'R');\n }else{\n ans += string((prevCol - curCol), 'L');\n }\n if(((target[i] - 'a')/5) == 5 and abs(curCol - prevCol) > 0){\n ans += 'D';\n curRow++;\n }\n ans += '!';\n }\n return ans;\n\n }\n};" }, { "title": "Maximum Number of Ways to Partition an Array", "algo_input": "You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:\n\n\n\t1 <= pivot < n\n\tnums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]\n\n\nYou are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.\n\nReturn the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.\n\n \nExample 1:\n\nInput: nums = [2,-1,2], k = 3\nOutput: 1\nExplanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\n\n\nExample 2:\n\nInput: nums = [0,0,0], k = 1\nOutput: 2\nExplanation: The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\n\n\nExample 3:\n\nInput: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput: 4\nExplanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t2 <= n <= 105\n\t-105 <= k, nums[i] <= 105\n\n", "solution_py": "class Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix_sums = list(accumulate(nums))\n total_sum = prefix_sums[-1]\n best = 0\n if total_sum % 2 == 0:\n best = prefix_sums[:-1].count(total_sum // 2) # If no change\n\n after_counts = Counter(total_sum - 2 * prefix_sum\n for prefix_sum in prefix_sums[:-1])\n before_counts = Counter()\n\n best = max(best, after_counts[k - nums[0]]) # If we change first num\n\n for prefix, x in zip(prefix_sums, nums[1:]):\n gap = total_sum - 2 * prefix\n after_counts[gap] -= 1\n before_counts[gap] += 1\n\n best = max(best, after_counts[k - x] + before_counts[x - k])\n\n return best", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar waysToPartition = function(nums, k) {\n let totalSum=nums.reduce((acc, curr) => acc+curr)\n let left=0;\n let rightDiff={}\n let leftDiff={}\n \n for(let i=0; i count = new HashMap<>(); //contribution of prefixes without changing\n count.put(pref[0], 1);\n\n for (int i = 1; i < n - 1; i++){\n pref[i] += pref[i - 1] + nums[i];\n count.put(pref[i], count.getOrDefault(pref[i], 0) + 1);\n }\n pref[n - 1] += pref[n - 2] + nums[n - 1]; //last step doesn't add into 'count' map, because we're trying to find at least two parts.\n\n int sum = pref[n - 1];\n int max = 0;\n if (sum % 2 == 0)\n max = count.getOrDefault(sum / 2, 0); //max without changing\n\n Map countPrev = new HashMap<>(); //contribution of prefixes before current step\n for (int i = 0; i < n; i++){\n int diff = k - nums[i];\n int changedSum = sum + diff;\n if (changedSum % 2 == 0)\n max = Math.max(max, count.getOrDefault(changedSum / 2 - diff, 0) + countPrev.getOrDefault(changedSum / 2, 0));\n count.put(pref[i], count.getOrDefault(pref[i], 0) - 1);\n countPrev.put(pref[i], countPrev.getOrDefault(pref[i], 0) + 1);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int waysToPartition(vector& nums, int k) {\n unordered_map left;\n unordered_map right;\n\n long long int sum=accumulate(nums.begin(),nums.end(),0L);\n long long int leftSum=0;\n int n=nums.size();\n\n for(int i=0;i int:\n def util(node: TreeNode, sum_array) -> int:\n t = [e - node.val for e in sum_array]\n zeroes = t.count(0)\n if node.left is None and node.right is None:\n return zeroes\n ansl, ansr = 0, 0\n if node.left:\n ansl = util(node.left, t + [targetSum])\n if node.right:\n ansr = util(node.right, t + [targetSum])\n return ansl + ansr + zeroes\n\n return util(root, [targetSum]) if root is not None else 0", "solution_js": "var pathSum = function(root, targetSum) {\nlet count = 0;\n\nlet hasSum = (node, target) => { //helper function, calculates number of paths having sum equal to target starting from given node\n if(node===null){// base case\n return;\n }\n if(node.val===target){// if at any point path sum meets the requirement\n count++;\n }\n //recursive call\n hasSum(node.left, target-node.val);\n hasSum(node.right, target-node.val);\n}\n\nlet dfs = (node) => {//dfs on every node and find sum equal to target starting from every node\n if(node===null)\n return;\n dfs(node.left);\n dfs(node.right);\n hasSum(node,targetSum);// find sum of path starting on this point\n}\n\ndfs(root);\n\nreturn count;\n};", "solution_java": "class Solution {\n public int pathSum(TreeNode root, int targetSum) {\n HashMap hm = new HashMap<>();\n //hm.put(0L,1); ---> can use this to handle initial condition if c_sum == target sum\n\n int res = solve(hm, root, targetSum, 0);\n\n return res;\n }\n\n public int solve(HashMap hm, TreeNode node, long tgt, long c_sum) {\n\n if(node == null)\n return 0;\n\n c_sum += node.val;\n\n int res = 0;\n\n if(c_sum == tgt) //--> either this condition or the above commented condition.\n res++;\n\n if(hm.containsKey(c_sum-tgt)){\n res += hm.get(c_sum-tgt);\n }\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)+1);\n\n int left = solve(hm, node.left, tgt, c_sum);\n int right = solve(hm, node.right, tgt, c_sum);\n\n res += (left+right);\n\n hm.put(c_sum, hm.getOrDefault(c_sum,0)-1); //remove the calculated cumulative sum\n\n return res;\n\n }\n\n}", "solution_c": "class Solution {\npublic:\n int ans = 0,t;\n \n void dfs(unordered_map &curr,TreeNode* node,long long sm){\n \n if(!node){\n return;\n }\n \n sm += (long long) node->val;\n ans += curr[sm-t];\n curr[sm]++;\n \n dfs(curr,node->left,sm);\n dfs(curr,node->right,sm);\n \n curr[sm]--;\n }\n int pathSum(TreeNode* root, int targetSum) {\n if(!root){\n return 0;\n }\n \n t = targetSum;\n unordered_map curr;\n curr[0] = 1;\n long long sm = 0;\n \n dfs(curr,root,sm);\n\n return ans;\n }\n};" }, { "title": "The k-th Lexicographical String of All Happy Strings of Length n", "algo_input": "A happy string is a string that:\n\n\n\tconsists only of letters of the set ['a', 'b', 'c'].\n\ts[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).\n\n\nFor example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\n\nGiven two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\n\nReturn the kth string of this list or return an empty string if there are less than k happy strings of length n.\n\n \nExample 1:\n\nInput: n = 1, k = 3\nOutput: \"c\"\nExplanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\n\n\nExample 2:\n\nInput: n = 1, k = 4\nOutput: \"\"\nExplanation: There are only 3 happy strings of length 1.\n\n\nExample 3:\n\nInput: n = 3, k = 9\nOutput: \"cab\"\nExplanation: There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9th string = \"cab\"\n\n\n \nConstraints:\n\n\n\t1 <= n <= 10\n\t1 <= k <= 100\n\n", "solution_py": "class Solution:\n def getHappyString(self, n: int, k: int) -> str:\n ans = []\n letters = ['a','b','c']\n def happystr(n,prev,temp):\n if n==0:\n ans.append(\"\".join(temp))\n return \n for l in letters: \n if l!=prev: \n happystr(n-1,l,temp+[l])\n happystr(n,\"\",[])\n if len(ans) innerList = new ArrayList<>();\n getHappyStringUtil(n, k, new char[] { 'a', 'b', 'c' }, new StringBuilder(), innerList);\n if (innerList.size() < k)\n return \"\";\n return innerList.get(k - 1);\n }\n\n public void getHappyStringUtil(int n, int k, char[] letter, StringBuilder tempString, List innerList) {\n // Base case\n if (tempString.length() == n) {\n innerList.add(tempString.toString());\n return;\n }\n\n // Recursive call\n for (int i = 0; i < 3; i++) {\n if (tempString.length() > 0 && tempString.charAt(tempString.length() - 1) == letter[i])\n continue;\n tempString.append(letter[i]);\n getHappyStringUtil(n, k, letter, tempString, innerList);\n tempString.deleteCharAt(tempString.length() - 1);\n }\n\n }\n}", "solution_c": "class Solution {\n private:\n void happy(string s, vector &v, int n, vector &ans){\n if(s.size() == n){\n ans.push_back(s);\n return;\n }\n for(int i=0; i<3; i++){\n if(s.back() != v[i]){\n s.push_back(v[i]);\n happy(s,v,n,ans);\n s.pop_back();\n }\n }\n }\npublic:\n string getHappyString(int n, int k) {\n vector v = {'a', 'b', 'c'};\n vector ans;\n string s = \"\";\n happy(s,v,n,ans);\n if(ans.size() < k){\n return \"\";\n }\n else{\n return ans[k-1];\n }\n }\n};" }, { "title": "Vowel Spellchecker", "algo_input": "Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.\n\nFor a given query word, the spell checker handles two categories of spelling mistakes:\n\n\n\tCapitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.\n\n\t\n\t\tExample: wordlist = [\"yellow\"], query = \"YellOw\": correct = \"yellow\"\n\t\tExample: wordlist = [\"Yellow\"], query = \"yellow\": correct = \"Yellow\"\n\t\tExample: wordlist = [\"yellow\"], query = \"yellow\": correct = \"yellow\"\n\t\n\t\n\tVowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.\n\t\n\t\tExample: wordlist = [\"YellOw\"], query = \"yollow\": correct = \"YellOw\"\n\t\tExample: wordlist = [\"YellOw\"], query = \"yeellow\": correct = \"\" (no match)\n\t\tExample: wordlist = [\"YellOw\"], query = \"yllw\": correct = \"\" (no match)\n\t\n\t\n\n\nIn addition, the spell checker operates under the following precedence rules:\n\n\n\tWhen the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\n\tWhen the query matches a word up to capitlization, you should return the first such match in the wordlist.\n\tWhen the query matches a word up to vowel errors, you should return the first such match in the wordlist.\n\tIf the query has no matches in the wordlist, you should return the empty string.\n\n\nGiven some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].\n\n \nExample 1:\nInput: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\nExample 2:\nInput: wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput: [\"yellow\"]\n\n \nConstraints:\n\n\n\t1 <= wordlist.length, queries.length <= 5000\n\t1 <= wordlist[i].length, queries[i].length <= 7\n\twordlist[i] and queries[i] consist only of only English letters.\n\n", "solution_py": "class Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n n = len(wordlist)\n d = {}\n sd = {}\n vd = {}\n cd = {}\n for i in range(n):\n d[wordlist[i]] = i\n s = wordlist[i].lower()\n if s not in sd:sd[s] = i \n m = len(wordlist[i])\n tmp = []\n emp = \"\"\n for j in range(m):\n if wordlist[i][j] in 'aeiouAEIOU': tmp.append(j)\n else:emp+=wordlist[i][j].lower()\n cd[i] = emp\n vd[i] = tmp\n \n ans = []\n for word in queries:\n word_lower = word.lower()\n if word in d: \n ans.append(word)\n continue \n elif word_lower in sd:\n ans.append(wordlist[sd[word_lower]])\n continue\n else:\n vow_word = []\n con_word = \"\" \n m = len(word)\n for i in range(m):\n if word[i] in 'aeiouAEIOU' : vow_word.append(i)\n else: con_word += word[i].lower()\n if vow_word == []:\n ans.append(\"\")\n continue\n \n flag = False\n for i in range(n):\n vow_tmp = vd[i]\n con_tmp = cd[i]\n if vow_tmp == vow_word and con_tmp == con_word:\n ans.append(wordlist[i])\n flag = True\n break\n if flag == True:continue\n ans.append(\"\")\n return ans", "solution_js": "var spellchecker = function(wordlist, queries) {\n const baseList = new Set(wordlist.reverse());\n const loweredList = wordlist.reduce((map, word) => (map[normalize(word)] = word, map), {});\n const replacedList = wordlist.reduce((map, word) => (map[repVowels(word)] = word, map), {});\n return queries.map(word => (\n baseList.has(word) && word ||\n\tloweredList[normalize(word)] ||\n\treplacedList[repVowels(word)] ||\n\t''\n ));\n};\nvar normalize = function(word) { return word.toLowerCase() };\nvar repVowels = function(word) { return normalize(word).replace(/[eiou]/g, 'a') };", "solution_java": "class Solution {\n public String[] spellchecker(String[] wordlist, String[] queries) {\n String[] ans = new String[queries.length];\n Map[] map = new HashMap[3];\n Arrays.setAll(map, o -> new HashMap<>());\n String pattern = \"[aeiou]\";\n\n for (String w : wordlist){\n String lo = w.toLowerCase();\n map[0].put(w, \"\");\n map[1].putIfAbsent(lo, w);\n map[2].putIfAbsent(lo.replaceAll(pattern, \".\"), map[1].getOrDefault(w, w));\n }\n\n int i = 0;\n for (String q : queries){\n String lo = q.toLowerCase();\n String re = lo.replaceAll(pattern, \".\");\n if (map[0].containsKey(q)){\n ans[i] = q;\n }else if (map[1].containsKey(lo)){\n ans[i] = map[1].get(lo);\n }else if (map[2].containsKey(re)){\n ans[i] = map[2].get(re);\n }else{\n ans[i] = \"\";\n }\n i++;\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector spellchecker(vector& wordlist, vector& queries) {\n unordered_map> umap;\n\n // step 1: add info in umap;\n for(int curr = 0; curr < wordlist.size(); curr++){\n // case 1: add same;\n umap[wordlist[curr]].push_back({curr});\n // notice that the lowercase may appear;\n\n // case 2: add lowercase;\n string tmp = wordlist[curr];\n transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\n if(umap.find(tmp) == umap.end() && tmp != wordlist[curr]) umap[tmp].push_back({curr});\n\n // case 3: add vowel errors;\n // convert aeiou to _;\n for(int c_index = 0; c_index < tmp.size(); c_index++){\n char c = tmp[c_index];\n if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_';\n }\n\n if(umap.find(tmp) == umap.end()) umap[tmp].push_back({curr});\n }\n\n // step 2: convert queries;\n for(int curr = 0; curr < queries.size(); curr++){\n string tmp = queries[curr];\n transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);\n\n // case 1: check same;\n if(umap.find(queries[curr]) != umap.end()){\n queries[curr] = (umap[queries[curr]].size() == 1) ? wordlist[umap[queries[curr]][0]] : wordlist[umap[queries[curr]][1]];\n continue;\n }\n\n // case 2: check lowercase;\n if(umap.find(tmp) != umap.end() && tmp != queries[curr]){\n queries[curr] = wordlist[umap[tmp][0]];\n continue;\n }\n\n // case 3: check vowel errors;\n // convert aeiou to _;\n for(int c_index = 0; c_index < tmp.size(); c_index++){\n char c = tmp[c_index];\n if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') tmp[c_index] = '_';\n }\n\n if(umap.find(tmp) != umap.end()){\n queries[curr] = wordlist[umap[tmp][0]];\n continue;\n }\n\n // case 4: not found;\n queries[curr] = \"\";\n }\n\n return queries;\n }\n};\n\n// 1. When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\n// 2. When the query matches a word up to capitlization, you should return the first such match in the wordlist.\n// 3. When the query matches a word up to vowel errors, you should return the first such match in the wordlist.\n// 4. If the query has no matches in the wordlist, you should return the empty string." }, { "title": "Bulb Switcher", "algo_input": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.\n\nOn the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.\n\nReturn the number of bulbs that are on after n rounds.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 1\nExplanation: At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.\n\nExample 2:\n\nInput: n = 0\nOutput: 0\n\n\nExample 3:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t0 <= n <= 109\n\n", "solution_py": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n return int(sqrt(n))", "solution_js": "var bulbSwitch = function(n) {\n return Math.floor(Math.sqrt(n));\n};", "solution_java": "\tclass Solution {\n public int bulbSwitch(int n) {\n return (int)Math.sqrt(n);\n }\n}", "solution_c": "class Solution {\npublic:\n int bulbSwitch(int n) {\n return sqrt(n);\n }\n};" }, { "title": "Latest Time by Replacing Hidden Digits", "algo_input": "You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).\n\nThe valid times are those inclusively between 00:00 and 23:59.\n\nReturn the latest valid time you can get from time by replacing the hidden digits.\n\n \nExample 1:\n\nInput: time = \"2?:?0\"\nOutput: \"23:50\"\nExplanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\n\n\nExample 2:\n\nInput: time = \"0?:3?\"\nOutput: \"09:39\"\n\n\nExample 3:\n\nInput: time = \"1?:22\"\nOutput: \"19:22\"\n\n\n \nConstraints:\n\n\n\ttime is in the format hh:mm.\n\tIt is guaranteed that you can produce a valid time from the given string.\n\n", "solution_py": "class Solution:\ndef maximumTime(self, time: str) -> str:\n memo = {\"0\":\"9\",\n \"1\":\"9\",\n \"?\":\"3\", \n \"2\":\"3\"}\n \n answer = \"\"\n for idx, val in enumerate(time):\n if val == \"?\":\n if idx == 0:\n if time[idx+1] == \"?\":\n answer += \"2\"\n \n else:\n if int(time[idx+1]) >= 4:\n answer += \"1\"\n \n else: answer += \"2\"\n \n if idx == 1:\n answer += memo[time[idx-1]]\n \n if idx == 3:\n answer += \"5\" \n \n if idx == 4:\n answer += \"9\"\n \n else:\n answer += val\n \n return answer", "solution_js": "var maximumTime = function(time) {\n time = time.split('')\n if (time[0] === \"?\") time[0] = time[1] > 3 ? \"1\" : \"2\"\n if (time[1] === \"?\") time[1] = time[0] > 1 ? \"3\" : \"9\"\n if (time[3] === \"?\") time[3] = \"5\"\n if (time[4] === \"?\") time[4] = \"9\"\n return time.join('')\n};", "solution_java": "class Solution {\n public String maximumTime(String time) {\n char[] times = time.toCharArray();\n //for times[0]\n //if both characters of hour is ?, then hour is 23 then times[0] should be '2'(\"??:3?)\".\n //if 2nd character of hour is <= 3, then hour can be in 20s then times[0] should be '2'.\n //if 2nd character of hour is >3, then hour can only be in 10s then times[0] should be '1'.\n if(times[0]=='?')\n times[0]= (times[1]<='3' || times[1]=='?') ? '2' : '1';\n //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then times[1] should be '9'.\n //if 1st character of hour is 2, then hour can be 23 then times[1] should be '3'.\n if(times[1]=='?')\n times[1]= times[0]=='2' ? '3' : '9';\n //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so times[3] is always '5'.\n if(times[3]=='?')\n times[3]='5';\n //if 2nd character of minute is ?, then times[4] is '9'.\n if(times[4]=='?')\n times[4]='9';\n return new String(times);\n }\n}", "solution_c": "class Solution {\npublic:\n string maximumTime(string time) {\n //for time[0]\n //if both characters of hour is ?, then hour is 23 then time[0] should be '2'(\"??:3?)\".\n //if 2nd character of hour is <= 3, then hour can be in 20s then time[0] should be '2'.\n //if 2nd character of hour is >3, then hour can only be in 10s then time[0] should be '1'.\n if(time[0]=='?')\n time[0]= (time[1]<='3' || time[1]=='?') ? '2' : '1';\n //if 1st character of hour is 0 or 1, then hour can be 09 or 19 then time[1] should be '9'.\n //if 1st character of hour is 2, then hour can be 23 then time[1] should be '3'.\n if(time[1]=='?')\n time[1]= time[0]=='2' ? '3' : '9';\n //if both characters of minute is ? then minute is 59, or only 4th character is ? then 5_ so time[3] is always '5'.\n if(time[3]=='?')\n time[3]='5';\n //if 2nd character of minute is ?, then time[4] is '9'.\n if(time[4]=='?')\n time[4]='9';\n return time;\n }\n};" }, { "title": "Fraction Addition and Subtraction", "algo_input": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.\n\nThe final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.\n\n \nExample 1:\n\nInput: expression = \"-1/2+1/2\"\nOutput: \"0/1\"\n\n\nExample 2:\n\nInput: expression = \"-1/2+1/2+1/3\"\nOutput: \"1/3\"\n\n\nExample 3:\n\nInput: expression = \"1/3-1/2\"\nOutput: \"-1/6\"\n\n\n \nConstraints:\n\n\n\tThe input string only contains '0' to '9', '/', '+' and '-'. So does the output.\n\tEach fraction (input and output) has the format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.\n\tThe input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.\n\tThe number of given fractions will be in the range [1, 10].\n\tThe numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.\n\n", "solution_py": "\"\"\"\napproach:\nfirst replace - with +- in the string so that implementation gets\na little easy\n\"\"\"\nclass Solution:\n def fractionAddition(self, expression: str) -> str:\n expression = expression.replace('-', '+-')\n parts = [item for item in expression.split('+') if item != '']\n numes, denoms, denom_set, lcm = [], [], set(), 1\n def get_lcm(a, b):\n if a == 1:\n return b\n if b == 1:\n return a\n if a < b:\n if b % a == 0:\n return a * get_lcm(1, b/a)\n else:\n return a * get_lcm(1, b)\n else:\n if a % b == 0:\n return b * get_lcm(a/b, 1)\n else:\n return b * get_lcm(a, 1)\n\n for part in parts:\n num, den = part.split('/')\n numes.append(int(num))\n denoms.append(int(den))\n lcm = get_lcm(lcm, int(den))\n\n result = 0\n for num, den in zip(numes, denoms):\n result +=num * int(lcm/den)\n\n def get_gcd(a, b):\n if a == 0:\n return b\n if b == 0:\n return a\n if a == b:\n return a\n elif a < b:\n return get_gcd(a, b-a)\n else:\n return get_gcd(a-b, b)\n\n gcd = get_gcd(abs(result), lcm)\n return str(int(result/gcd)) + '/' + str(int(lcm/gcd))", "solution_js": "var fractionAddition = function(expression) {\n\tconst fractions = expression.split(/[+-]/).filter(Boolean);\n\tconst operator = expression.split(/[0-9/]/).filter(Boolean);\n\texpression[0] !== '-' && operator.unshift('+');\n\n\tconst gcd = (a, b) => b === 0 ? a : gcd(b, a % b);\n\tconst lcm = fractions.reduce((result, fraction) => {\n\t\tconst denominator = fraction.split('/')[1];\n\t\treturn result * denominator / gcd(result, denominator);\n\t}, 1);\n\n\tconst molecularSum = fractions.reduce((total, fraction, index) => {\n\t\tconst [molecular, denominator] = fraction.split('/');\n\t\tconst multiple = lcm / denominator * (operator[index] === '+' ? 1 : -1);\n\t\treturn total + molecular * multiple;\n\t}, 0);\n\n\tconst resultGcd = gcd(Math.abs(molecularSum), lcm);\n\treturn `${molecularSum / resultGcd}/${lcm / resultGcd}`;\n};", "solution_java": "class Solution {\n private int gcd(int x, int y){\n return x!=0?gcd(y%x, x):Math.abs(y);\n }\n\n public String fractionAddition(String exp) {\n Scanner sc = new Scanner(exp).useDelimiter(\"/|(?=[-+])\");\n\n int A=0, B=1;\n while(sc.hasNext()){\n int a = sc.nextInt(), b=sc.nextInt();\n A = A * b + B * a;\n B *= b;\n\n int gcdX = gcd(A, B);\n A/=gcdX;\n B/=gcdX;\n }\n return A+\"/\"+B;\n }\n}", "solution_c": "class Solution {\npublic:\n string fractionAddition(string expression) {\n \n int res_num = 0; //keep track of numerator\n int res_denom = 1; //keep track of denominator\n char sign = '+'; //keep track of sign\n\t\t\n for(int i = 0; i < expression.size(); i++){ //parse the expression string\n int next_num = 0;\n int next_denom = 0;\n if(expression[i] == '+' || expression[i] == '-') //updating\n sign = expression[i];\n else{\n int j = i+1;\n while(j < expression.size() && expression[j] != '/') j++; build next numerator\n next_num = stoi(expression.substr(i, j-i));\n int k = j+1;\n while(k < expression.size() && expression[k] >= '0' && expression[k] <= '9') k++; //build next denominator\n next_denom = stoi(expression.substr(j+1, k-(j+1)));\n if(res_denom != next_denom){ //update result numerator and denominator\n res_num *= next_denom;\n next_num *= res_denom;\n res_denom *= next_denom;\n }\n if(sign == '+') res_num += next_num;\n else res_num -= next_num;\n i = k-1;\n }\n }\n return lowestFraction(res_num, res_denom); //put the fraction into lowest terms and return as string\n }\n \nprivate:\n int findGCD(int a, int b) { //find Greatest Common Denominator\n if(b == 0) return a;\n return findGCD(b, a % b);\n }\n \n string lowestFraction(int num, int denom){ //use GCD to put fraction into lowest terms and return as string\n int gcd;\n gcd = findGCD(num, denom);\n num /= gcd;\n denom /= gcd;\n if(denom < 0){\n denom *= -1;\n num *= -1;\n }\n return to_string(num) + '/' + to_string(denom);\n}\n \n};" }, { "title": "Third Maximum Number", "algo_input": "Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.\n\n \nExample 1:\n\nInput: nums = [3,2,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.\n\n\nExample 2:\n\nInput: nums = [1,2]\nOutput: 2\nExplanation:\nThe first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.\n\n\nExample 3:\n\nInput: nums = [2,2,3,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-231 <= nums[i] <= 231 - 1\n\n\n \nFollow up: Can you find an O(n) solution?", "solution_py": "class Solution:\n def thirdMax(self, nums: List[int]) -> int:\n nums_set = set(nums)\n sorted_set = sorted(nums_set)\n return sorted_set[-3] if len(nums_set) >2 else sorted_set[-1]\n \n \n #use set() to remove dups\n #if len of nums after dups have been removed is at least 2, a third max val must exist\n #if not, just return the max\n \n \n #you can do it in 1 line like this but then you have to call the same functions repeatedly\n #return sorted(set(nums))[-3] if len(set(nums)) > 2 else sorted(set(nums))[-1]\n \n \n ", "solution_js": "var thirdMax = function(nums) {\n nums.sort((a,b) => b-a);\n\t//remove duplicate elements\n for(let i=0; i first){\n third = second;\n second = first;\n first = num;\n continue;\n } \n if(second == null || num > second){\n third = second;\n second = num;\n continue;\n } \n if(third == null || num > third){\n third = num;\n }\n }\n return (third != null) ? third : first;\n }\n}", "solution_c": "class Solution {\npublic:\n int thirdMax(vector& nums) {\n sets;\n for(int i=0;i=3){ // when set size >=3 means 3rd Maximum exist(because set does not contain duplicate element)\n int Third_index_from_last=s.size()-3;\n auto third_maximum=next(s.begin(),Third_index_from_last);\n return *third_maximum;\n }\n return *--s.end(); // return maximum if 3rd maximum not exist\n }\n};" }, { "title": "Get the Maximum Score", "algo_input": "You are given two sorted arrays of distinct integers nums1 and nums2.\n\nA valid path is defined as follows:\n\n\n\tChoose array nums1 or nums2 to traverse (from index-0).\n\tTraverse the current array from left to right.\n\tIf you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).\n\n\nThe score is defined as the sum of uniques values in a valid path.\n\nReturn the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput: 30\nExplanation: Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green [2,4,6,8,10].\n\n\nExample 2:\n\nInput: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput: 109\nExplanation: Maximum sum is obtained with the path [1,3,5,100].\n\n\nExample 3:\n\nInput: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput: 40\nExplanation: There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 105\n\t1 <= nums1[i], nums2[i] <= 107\n\tnums1 and nums2 are strictly increasing.\n\n", "solution_py": "from itertools import accumulate\nclass Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n acc1 = list(accumulate(nums1, initial = 0))\n acc2 = list(accumulate(nums2, initial = 0))\n i, j = len(nums1)-1, len(nums2)-1\n previ, prevj = len(nums1), len(nums2)\n prev_maxscore = 0\n while i >= 0 and j >= 0:\n while i >= 0 and j >= 0 and nums1[i] < nums2[j]:\n j -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n while i >= 0 and j >= 0 and nums2[j] < nums1[i]:\n i -= 1\n if i >= 0 and j >= 0 and nums1[i] == nums2[j]:\n prev_maxscore += max(acc1[previ]-acc1[i], acc2[prevj]-acc2[j])\n previ, prevj = i, j\n i -= 1\n j -= 1\n prev_maxscore += max(acc1[previ]-acc1[0], acc2[prevj]-acc2[0])\n return prev_maxscore % (10**9 + 7)", "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxSum = function(nums1, nums2) {\n let MODULO_AMOUNT = 10 ** 9 + 7;\n let result = 0;\n let ptr1 = 0;\n let ptr2 = 0;\n let n1 = nums1.length;\n let n2 = nums2.length;\n let section_sum1 = 0;\n let section_sum2 = 0;\n while(ptr1 < n1 || ptr2 < n2){\n if(ptr1 < n1 && ptr2 < n2 && nums1[ptr1] == nums2[ptr2]){\n result += Math.max(section_sum1, section_sum2) + nums1[ptr1];\n result %= MODULO_AMOUNT;\n section_sum1 = 0;\n section_sum2 = 0;\n ptr1 += 1;\n ptr2 += 1;\n continue;\n }\n\n if(ptr1 == n1 || (ptr2 != n2 && nums1[ptr1] > nums2[ptr2])){\n section_sum2 += nums2[ptr2];\n ptr2 += 1;\n }else{\n section_sum1 += nums1[ptr1];\n ptr1 += 1;\n }\n }\n result += Math.max(section_sum1, section_sum2);\n return result % MODULO_AMOUNT;\n};", "solution_java": "class Solution {\n public int maxSum(int[] nums1, int[] nums2) {\n long currSum = 0, sum1 = 0, sum2 = 0;\n int i = 0;\n int j = 0;\n while(i < nums1.length && j < nums2.length){\n if(nums1[i] == nums2[j]) {\n currSum += Math.max(sum1, sum2) + nums2[j];\n sum1 = 0;\n sum2 = 0;\n i++;\n j++;\n }\n else if(nums1[i] < nums2[j]){\n sum1 += nums1[i++];\n } else {\n sum2 += nums2[j++];\n }\n }\n \n while(i < nums1.length){\n sum1 += nums1[i++];\n }\n while(j < nums2.length){\n sum2 += nums2[j++];\n }\n return (int)((currSum + Math.max(sum1, sum2)) % 1000000007);\n }\n}", "solution_c": "#define ll long long\nclass Solution {\npublic:\n ll dp1[100005];\n ll dp2[100005];\n \n ll mod=1e9+7;\n \n ll func(vector &nums1 , vector &nums2 , unordered_map< int , int> &mp1,\n unordered_map< int , int> &mp2 , int i1 , int i2 , int n1 , int n2 , bool f1)\n {\n if(i1>=n1 || i2>=n2)\n {\n return 0;\n }\n \n ll sum1=0;\n \n ll sum2=0;\n \n ll ans=0;\n \n if(f1==true)\n {\n if(dp1[i1]!=-1)\n {\n return dp1[i1];\n }\n }\n else\n {\n if(dp2[i2]!=-1)\n {\n return dp2[i2];\n }\n }\n \n if(f1==true)\n {\n sum1=(sum1 + nums1[i1]);\n auto it=mp2.find(nums1[i1]);\n \n sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , i1+1 , i2 , n1 , n2 , true));\n \n if(it!=mp2.end())\n {\n int idx=mp2[nums1[i1]];\n sum2=(sum2 + nums2[idx]);\n \n sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , idx+1 , n1 , n2 , false ));\n \n }\n ans=max(sum1 , sum2);\n \n dp1[i1]=ans;\n }\n else\n {\n sum2=(sum2 + nums2[i2]);\n auto it=mp1.find(nums2[i2]);\n \n sum2=(sum2 + func(nums1 , nums2 , mp1 , mp2 , i1 , i2+1 , n1 , n2 , false));\n \n if(it!=mp1.end())\n {\n int idx=mp1[nums2[i2]];\n sum1= (sum1 + nums1[idx]);\n sum1=(sum1 + func(nums1 , nums2 , mp1 , mp2 , idx+1 , i2 , n1 , n2 , true));\n }\n ans=max(sum1 , sum2);\n dp2[i2]=ans;\n }\n \n \n return ans;\n \n \n }\n \n int maxSum(vector& nums1, vector& nums2) {\n \n // at every equal value we can switch \n \n // the elements from array1 to array2\n \n unordered_map< int , int> mp1 , mp2;\n \n int n1=nums1.size() , n2=nums2.size();\n \n for(int i=0;i bool:\n self.stream.appendleft(letter)\n cur = self.root\n for ch in self.stream:\n if ch not in cur.children:\n return False\n else:\n cur = cur.children[ch]\n if cur.endOfWord:\n return True\n return False", "solution_js": "var StreamChecker = function(words) {\n function Trie() {\n this.suffixLink = null; //this is where it will fallback to when a letter can't be matched\n this.id = -1; //this id will be 0 or greater if it matches a word\n this.next = new Map(); //map of \n }\n this.root = new Trie();\n this.uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system\n\n //standard trie traversal but keeping track of new words via id system\n for (const word of words) {\n let ptr = this.root;\n for (const c of word) {\n if (!ptr.next.has(c)) {\n ptr.next.set(c, new Trie());\n }\n ptr = ptr.next.get(c);\n }\n if (ptr.id === -1) {\n ptr.id = this.uniqueIds++;\n }\n }\n\n //BFS traversal to build the automaton\n const q = [];\n for (const [c, node] of this.root.next) {\n //all first level children should point back to the root when a match to a character fails\n node.suffixLink = this.root;\n q.push(node);\n }\n\n while (q.length) {\n const curr = q.shift();\n for (const [c, node] of curr.next) {\n\n let ptr = curr.suffixLink;\n while (ptr !== this.root && !ptr.next.has(c)) {\n ptr = ptr.suffixLink;\n }\n //find the next suffixLink if it matches the current character or fallback to the root\n node.suffixLink = ptr.next.get(c) ?? this.root;\n\n //if the current suffixLink happens to also be a word we should store its id to make it quick to find\n if (node.suffixLink.id !== -1) {\n node.id = node.suffixLink.id;\n }\n q.push(node);\n }\n }\n //the query ptr will now track every new streamed character and use it to match\n this.queryPtr = this.root;\n};\n\nStreamChecker.prototype.query = function(letter) {\n //the query ptr will now track every new streamed character and can be used to quickly find words\n while (this.queryPtr !== this.root && !this.queryPtr.next.has(letter)) {\n this.queryPtr = this.queryPtr.suffixLink;\n }\n this.queryPtr = this.queryPtr.next.get(letter) ?? this.root;\n //if any word is found it will have an id that isn't -1\n return this.queryPtr.id !== -1;\n};", "solution_java": "class StreamChecker {\n \n class TrieNode {\n boolean isWord;\n TrieNode[] next = new TrieNode[26];\n }\n \n TrieNode root = new TrieNode();\n StringBuilder sb = new StringBuilder();\n \n public StreamChecker(String[] words) {\n createTrie(words);\n }\n \n public boolean query(char letter){\n sb.append(letter);\n TrieNode node = root;\n for(int i=sb.length()-1; i>=0 && node!=null; i--){\n char ch = sb.charAt(i);\n node = node.next[ch - 'a'];\n if(node != null && node.isWord){\n return true;\n }\n }\n return false;\n }\n \n private void createTrie(String words[]){\n for(String s : words){\n TrieNode node = root;\n int len = s.length();\n for(int i = len-1; i>=0; i--){\n char ch = s.charAt(i);\n if(node.next[ch-'a'] == null){\n node.next[ch - 'a'] = new TrieNode();\n }\n node = node.next[ch - 'a'];\n }\n node.isWord = true;\n }\n }\n}", "solution_c": "class StreamChecker {\n struct Trie {\n Trie* suffixLink; //this is where it will fallback to when a letter can't be matched\n int id = -1; //this id will be 0 or greater if it matches a word\n map next;\n };\npublic:\n Trie* root;\n Trie* queryPtr;\n int uniqueIds = 0; //used to count all the unique words discovered and as part of the Trie id system\n \n StreamChecker(vector& words) {\n root = new Trie();\n \n\t\t//standard trie traversal but keeping track of new words via id system\n for (string& word: words) {\n Trie* p = root;\n for (char c: word) {\n if (p->next.find(c) == p->next.end()) {\n p->next.insert({ c, new Trie() });\n }\n p = p->next.at(c);\n }\n if (p->id == -1) {\n p->id = uniqueIds++;\n }\n }\n \n queue q;\n for (pair itr: root->next) {\n q.push(itr.second);\n itr.second->suffixLink = root;\n }\n \n\t\t//BFS traversal to build the automaton\n while (q.size()) {\n Trie* curr = q.front();\n q.pop();\n for (pair e: curr->next) {\n char c = e.first;\n Trie* node = e.second;\n\t\t\t\t\n Trie* ptr = curr->suffixLink;\n while (ptr != root && ptr->next.find(c) == ptr->next.end()) {\n ptr = ptr->suffixLink;\n }\n\t\t\t\t//find the next suffixLink if it matches the current character or fallback to the root\n node->suffixLink = ptr->next.find(c) != ptr->next.end() ? ptr->next.at(c) : root;\n\t\t\t\t\n\t\t\t\t//if the current suffixLink happens to also be a word we should store its id to make it quick to find\n if (node->suffixLink->id != -1) {\n node->id = node->suffixLink->id;\n }\n q.push(node);\n }\n }\n\t\t//the query ptr will now track every new streamed character and can be used to quickly find words\n queryPtr = root;\n }\n \n bool query(char letter) {\n\t\t//if the next letter can't be found and we're not at the root, we'll trace back until we find the longest suffix that matches\n while (queryPtr != root && queryPtr->next.find(letter) == queryPtr->next.end()) {\n queryPtr = queryPtr->suffixLink;\n }\n queryPtr = queryPtr->next.find(letter) != queryPtr->next.end() ? queryPtr->next.at(letter) : root;\n\t\t//if any word is found it will have an id that isn't -1\n return queryPtr->id != -1;\n }\n};" }, { "title": "Number of Students Unable to Eat Lunch", "algo_input": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.\n\nThe number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:\n\n\n\tIf the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.\n\tOtherwise, they will leave it and go to the queue's end.\n\n\nThis continues until none of the queue students want to take the top sandwich and are thus unable to eat.\n\nYou are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i​​​​​​th sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j​​​​​​th student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.\n\n \nExample 1:\n\nInput: students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput: 0 \nExplanation:\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.\n\n\nExample 2:\n\nInput: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= students.length, sandwiches.length <= 100\n\tstudents.length == sandwiches.length\n\tsandwiches[i] is 0 or 1.\n\tstudents[i] is 0 or 1.\n\n", "solution_py": "class Solution(object):\n def countStudents(self, students, sandwiches):\n \"\"\"\n :type students: List[int]\n :type sandwiches: List[int]\n :rtype: int\n \"\"\"\n while sandwiches:\n if sandwiches[0] in students:\n students.remove(sandwiches[0])\n sandwiches.pop(0)\n else:\n break\n return len(sandwiches)\n ", "solution_js": "var countStudents = function(students, sandwiches) {\nwhile (students.length>0 && students.indexOf(sandwiches[0])!=-1) {\n if (students[0] == sandwiches[0]) {\n students.shift();\n sandwiches.shift();\n }\n else students.push(students.shift());\n}\nreturn students.length\n};", "solution_java": "class Solution {\n public int countStudents(int[] students, int[] sandwiches) {\n int ones = 0; //count of students who prefer type1\n int zeros = 0; //count of students who prefer type0\n\n for(int stud : students){\n if(stud == 0) zeros++;\n else ones++;\n }\n\n // for each sandwich in sandwiches\n for(int sandwich : sandwiches){\n if(sandwich == 0){ // if sandwich is of type0\n if(zeros == 0){ // if no student want a type0 sandwich\n return ones;\n }\n zeros--;\n }\n else{ // if sandwich is of type1\n if(ones == 0){ // if no student want a type1 sandwich\n return zeros;\n }\n ones--;\n }\n }\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n int countStudents(vector& students, vector& sandwiches) {\n int size = students.size();\n queue student_choice;\n for(int i = 0 ; i < size ; ++i){\n student_choice.push(students[i]);\n }\n int rotations = 0 , i = 0;\n while(student_choice.size() && rotations < student_choice.size()){\n if(student_choice.front() == sandwiches[i]){\n student_choice.pop();\n i++;\n rotations = 0;\n } else {\n int choice = student_choice.front();\n student_choice.pop();\n student_choice.push(choice);\n rotations++;\n }\n }\n return student_choice.size();\n }\n};" }, { "title": "Print Words Vertically", "algo_input": "Given a string s. Return all the words vertically in the same order in which they appear in s.\nWords are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).\nEach word would be put on only one column and that in one column there will be only one word.\n\n \nExample 1:\n\nInput: s = \"HOW ARE YOU\"\nOutput: [\"HAY\",\"ORO\",\"WEU\"]\nExplanation: Each word is printed vertically. \n \"HAY\"\n \"ORO\"\n \"WEU\"\n\n\nExample 2:\n\nInput: s = \"TO BE OR NOT TO BE\"\nOutput: [\"TBONTB\",\"OEROOE\",\" T\"]\nExplanation: Trailing spaces is not allowed. \n\"TBONTB\"\n\"OEROOE\"\n\" T\"\n\n\nExample 3:\n\nInput: s = \"CONTEST IS COMING\"\nOutput: [\"CIC\",\"OSO\",\"N M\",\"T I\",\"E N\",\"S G\",\"T\"]\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 200\n\ts contains only upper case English letters.\n\tIt's guaranteed that there is only one space between 2 words.\n", "solution_py": "class Solution:\n def getMaxLen(self, words):\n max_len = 0\n for word in words:\n max_len = max(max_len, len(word))\n return max_len\n \n def printVertically(self, s: str) -> List[str]:\n words = s.split()\n max_len = self.getMaxLen(words)\n \n res = list()\n for i in range(max_len):\n s = \"\"\n for word in words:\n if i < len(word):\n s += word[i]\n else:\n s += \" \"\n s = s.rstrip()\n res.append(s)\n return res\n \n \n \n\t\t", "solution_js": "/**\n * @param {string} s\n * @return {string[]}\n */\n\n var printVertically = function(s)\n{\n let arr = s.split(' '),\n max = arr.reduce((last, curr) => Math.max(last, curr.length), 0),\n ans = [];\n\n arr = arr.map(el => el + ' '.repeat(max - el.length));\n\n for (let i = 0; i < max; i++)\n {\n let word = '';\n\n for (let j = 0; j < arr.length; j++)\n word += arr[j][i];\n\n ans.push(word.replace(new RegExp('\\\\s+$'), ''));\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public List printVertically(String s) {\n s = s.replace(\" \",\",\");\n String str=\"\";\n List a=new ArrayList<>();\n\n int max=0;\n for(int i =0;i();\n for(int i=0;i printVertically(string s) {\n\n int row = 0, col = 0;\n\n stringstream sso(s);\n string buffer;\n\n while (sso >> buffer)\n {\n row++;\n col = max((int)buffer.size(),col);\n }\n\n vector> matrix(row, vector(col,' '));\n\n sso = stringstream(s);\n\n int i = 0;\n while (sso >> buffer)\n {\n for (int j = 0; j < buffer.size(); j++)\n matrix[i][j] = buffer[j];\n i++;\n }\n\n vector res;\n for (int j = 0; j < col; j++)\n {\n string item;\n for (int i = 0; i < row; i++)\n item.push_back(matrix[i][j]);\n\n for (int i = item.size()-1; i >= 0; i--)\n {\n if (item[i] != ' ')\n {\n item.erase(item.begin()+i+1,item.end());\n break;\n }\n }\n res.push_back(item);\n }\n\n return res;\n }\n};" }, { "title": "Max Dot Product of Two Subsequences", "algo_input": "Given two arrays nums1 and nums2.\n\nReturn the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\n\nA subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).\n\n \nExample 1:\n\nInput: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput: 18\nExplanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.\n\nExample 2:\n\nInput: nums1 = [3,-2], nums2 = [2,-6,7]\nOutput: 21\nExplanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.\n\nExample 3:\n\nInput: nums1 = [-1,-1], nums2 = [1,1]\nOutput: -1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 500\n\t-1000 <= nums1[i], nums2[i] <= 1000\n\n", "solution_py": "class Solution:\n def maxDotProduct(self, A, B):\n dp = [float('-inf')] * (len(B)+1)\n for i in range(len(A)):\n prev = float('-inf')\n for j in range(len(B)):\n product = A[i] * B[j]\n prev, dp[j+1] = dp[j+1], max(dp[j+1], dp[j], product, prev + product)\n return dp[-1]", "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxDotProduct = function(nums1, nums2) {\n var m = nums1.length;\n var n = nums2.length;\n if (!m || !n) return 0;\n var dp = [[nums1[0] * nums2[0]]];\n for (var i = 1; i < m; i++) {\n dp[i] = [];\n dp[i][0] = Math.max(nums1[i] * nums2[0], dp[i-1][0]);\n }\n for (var i = 1; i < n; i++) dp[0][i] = Math.max(nums1[0] * nums2[i], dp[0][i-1]);\n for (var i = 1; i < m; i++) {\n for (var j = 1; j < n; j++) {\n var val = nums1[i] * nums2[j];\n dp[i][j] = Math.max(val, val + dp[i-1][j-1], dp[i][j-1], dp[i-1][j]);\n }\n }\n return dp[m - 1][n - 1];\n};", "solution_java": "class Solution {\n public int maxDotProduct(int[] nums1, int[] nums2) {\n int N = nums1.length, M = nums2.length;\n int[][] dp = new int[N][M];\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < M; j++) {\n dp[i][j] = nums1[i] * nums2[j];\n if (i > 0 && j > 0 && dp[i - 1][j - 1] > 0) {\n dp[i][j] += dp[i - 1][j - 1];\n }\n if (i > 0 && dp[i - 1][j] > dp[i][j]) {\n dp[i][j] = dp[i - 1][j];\n }\n if (j > 0 && dp[i][j - 1] > dp[i][j]) {\n dp[i][j] = dp[i][j - 1];\n }\n }\n }\n return dp[N - 1][M - 1];\n }\n}", "solution_c": "class Solution\n{\n public:\n\n const int NEG_INF = -10e8;\n int maxDotProduct(vector& nums1, vector& nums2) {\n\n int n = nums1.size();\n int m = nums2.size();\n\n // NOTE : we can't initialize with INT_MIN because adding any val with it will give overflow\n // that is why we prefer 10^7 or 10^8\n\n vector> dp(n+1, vector(m+1, NEG_INF));\n\n for (int i=1; i<=n; i++) {\n for (int j=1; j<=m; j++) {\n\n int temp_p = nums1[i-1]*nums2[j-1];\n\n // Although it is a variation of LCS but here we need to check for all answers we already know in dp\n // Why only temp_p ? -> suppose in dp[i-1][j-1] is -10^7 + temp_p is 2 == gives nearly -10^7(which is wrong ans)\n // For Remaining comparisons we already know why !\n\n dp[i][j] = max({ dp[i-1][j-1] + temp_p,\n temp_p,\n dp[i-1][j],\n dp[i][j-1]\n });\n }\n }\n\n return dp[n][m];\n }\n};" }, { "title": "Longest Substring Of All Vowels in Order", "algo_input": "A string is considered beautiful if it satisfies the following conditions:\n\n\n\tEach of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.\n\tThe letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).\n\n\nFor example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", and \"aaaeeeooo\" are not beautiful.\n\nGiven a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.\n\nA substring is a contiguous sequence of characters in a string.\n\n \nExample 1:\n\nInput: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput: 13\nExplanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\n\nExample 2:\n\nInput: word = \"aeeeiiiioooauuuaeiou\"\nOutput: 5\nExplanation: The longest beautiful substring in word is \"aeiou\" of length 5.\n\n\nExample 3:\n\nInput: word = \"a\"\nOutput: 0\nExplanation: There is no beautiful substring, so return 0.\n\n\n \nConstraints:\n\n\n\t1 <= word.length <= 5 * 105\n\tword consists of characters 'a', 'e', 'i', 'o', and 'u'.\n\n", "solution_py": "class Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n g = ''\n count = m = 0\n for x in word:\n if g and x < g[-1]:\n count = 0\n g = ''\n if not g or x > g[-1]:\n g += x\n count += 1\n if g == 'aeiou':\n m = max(m, count)\n return m", "solution_js": "/**\n * @param {string} word\n * @return {number}\n */\nvar longestBeautifulSubstring = function(word) {\n \n let obj = { 'a': 1, 'e': 2, 'i': 3, 'o': 4, 'u': 5 }\n let seq = 0\n let maxstrcount = 0, strcount = \"\"\n for (let i = 0; i <= word.length; i++) {\n if (seq <= obj[word[i]]) {\n strcount += word[i]\n seq = obj[word[i]]\n } else {\n let set = new Set()\n for (let i = 0; i < strcount.length; i++) {\n set.add(strcount[i])\n }\n if (set.size == 5) {\n maxstrcount = Math.max(strcount.length, maxstrcount)\n }\n if (i < word.length - 1)\n i--\n strcount = \"\"\n seq = 0\n }\n }\n return maxstrcount\n};", "solution_java": "class Solution {\n public int longestBeautifulSubstring(String word) {\n int max = 0;\n for(int i = 1;i verify = new HashSet<>();\n verify.add(word.charAt(i-1));\n while(i < word.length() && word.charAt(i) >= word.charAt(i-1)){\n temp++;\n verify.add(word.charAt(i));\n i++;\n }\n max = verify.size() == 5 ? Math.max(max,temp) : max ;\n }\n\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestBeautifulSubstring(string word) {\n const auto n = word.size();\n\n int cnt = 1;\n int len = 1;\n int max_len = 0;\n for (int i = 1; i != n; ++i) {\n if (word[i - 1] == word[i]) {\n ++len;\n } else if (word[i - 1] < word[i]) {\n ++len;\n ++cnt;\n } else {\n cnt = 1;\n len = 1;\n }\n\n if (cnt == 5) {\n max_len = max(max_len, len);\n }\n }\n return max_len;\n }\n};" }, { "title": "Count the Number of Ideal Arrays", "algo_input": "You are given two integers n and maxValue, which are used to describe an ideal array.\n\nA 0-indexed integer array arr of length n is considered ideal if the following conditions hold:\n\n\n\tEvery arr[i] is a value from 1 to maxValue, for 0 <= i < n.\n\tEvery arr[i] is divisible by arr[i - 1], for 0 < i < n.\n\n\nReturn the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 2, maxValue = 5\nOutput: 10\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.\n\n\nExample 2:\n\nInput: n = 5, maxValue = 3\nOutput: 11\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 104\n\t1 <= maxValue <= 104\n\n", "solution_py": "from math import sqrt\n\nclass Solution:\n def primesUpTo(self, n):\n primes = set(range(2, n + 1))\n for i in range(2, n):\n if i in primes:\n it = i * 2\n while it <= n:\n if it in primes:\n primes.remove(it)\n it += i\n\n return primes\n\n def getPrimeFactors(self, n, primes):\n ret = {}\n sq = int(math.sqrt(n))\n\n for p in primes:\n if n in primes:\n ret[n] = 1\n break\n\n while n % p == 0:\n ret[p] = ret.get(p, 0) + 1\n n //= p\n\n if n <= 1:\n break\n\n return ret\n \n def idealArrays(self, n: int, maxValue: int) -> int:\n mod = 10**9 + 7\n ret = 0\n primes = self.primesUpTo(maxValue)\n \n for num in range(1, maxValue + 1):\n # find number of arrays that can end with num\n # for each prime factor, we can add it at any index i that we want\n pf = self.getPrimeFactors(num, primes)\n cur = 1\n for d in pf:\n ct = pf[d]\n v = n\n # there are (n + 1) choose k ways to add k prime factors\n for add in range(1, ct):\n v *= (n + add)\n v //= (add + 1)\n \n cur = (cur * v) % mod\n \n ret = (ret + cur) % mod\n \n return ret", "solution_js": "/**\n * @param {number} n\n * @param {number} maxValue\n * @return {number}\n */\nvar idealArrays = function(n, maxValue) {\n const mod = 1e9 + 7;\n let cur = 0;\n let arr = Array(2).fill().map(() => Array(maxValue).fill(1));\n for (let l = 2; l <= n; l++) {\n const prev = arr[cur];\n const next = arr[1-cur];\n for (let s = 1; s <= maxValue; s++) {\n let res = 0;\n for (let m = 1; m * s <= maxValue; m++) {\n res = (res + prev[m * s - 1]) % mod;\n }\n next[s-1] = res;\n }\n cur = 1 - cur;\n }\n const res = arr[cur].reduce((a, b) => (a + b) % mod, 0);\n return res;\n};", "solution_java": "class Solution {\n int M =(int)1e9+7;\n public int idealArrays(int n, int maxValue) {\n long ans = 0;\n int N = n+maxValue;\n long[] inv = new long[N];\n long[] fact = new long[N];\n long[] factinv = new long[N];\n inv[1]=fact[0]=fact[1]=factinv[0]=factinv[1]=1;\n for (int i = 2; i < N; i++){ // mod inverse\n inv[i]=M-M/i*inv[M%i]%M;\n fact[i]=fact[i-1]*i%M;\n factinv[i]=factinv[i-1]*inv[i]%M;\n }\n for (int i = 1; i <= maxValue; i++){\n int tmp = i;\n Map map = new HashMap<>();\n for (int j = 2; j*j<= tmp; j++){\n while(tmp%j==0){ // prime factorization.\n tmp/=j;\n map.merge(j, 1, Integer::sum);\n }\n }\n if (tmp>1){\n map.merge(tmp, 1, Integer::sum);\n }\n long gain=1;\n for (int val : map.values()){ // arranges all the primes.\n gain *= comb(n+val-1, val, fact, factinv);\n gain %= M;\n }\n ans += gain;\n ans %= M;\n }\n\n return (int)ans;\n }\n\n private long comb(int a, int b, long[] fact, long[] factinv){\n return fact[a]*factinv[b]%M*factinv[a-b]%M;\n }\n}", "solution_c": "int comb[10001][14] = { 1 }, cnt[10001][14] = {}, mod = 1000000007;\nclass Solution {\npublic: \nint idealArrays(int n, int maxValue) {\n if (comb[1][1] == 0) { // one-time computation.\n for (int s = 1; s <= 10000; ++s) // nCr (comb)\n for (int r = 0; r < 14; ++r)\n comb[s][r] = r == 0 ? 1 : (comb[s - 1][r - 1] + comb[s - 1][r]) % mod;\n for (int div = 1; div <= 10000; ++div) { // Sieve of Eratosthenes\n ++cnt[div][0];\n for (int i = 2 * div; i <= 10000; i += div)\n for (int bars = 0; cnt[div][bars]; ++bars)\n cnt[i][bars + 1] += cnt[div][bars];\n }\n }\n int res = 0;\n for (int i = 1; i <= maxValue; ++i)\n for (int bars = 0; bars < min(14, n) && cnt[i][bars]; ++bars)\n res = (1LL * cnt[i][bars] * comb[n - 1][bars] + res) % mod;\n return res;\n}\n};" }, { "title": "Maximum Number of Coins You Can Get", "algo_input": "There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:\n\n\n\tIn each step, you will choose any 3 piles of coins (not necessarily consecutive).\n\tOf your choice, Alice will pick the pile with the maximum number of coins.\n\tYou will pick the next pile with the maximum number of coins.\n\tYour friend Bob will pick the last pile.\n\tRepeat until there are no more piles of coins.\n\n\nGiven an array of integers piles where piles[i] is the number of coins in the ith pile.\n\nReturn the maximum number of coins that you can have.\n\n \nExample 1:\n\nInput: piles = [2,4,1,2,7,8]\nOutput: 9\nExplanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.\n\n\nExample 2:\n\nInput: piles = [2,4,5]\nOutput: 4\n\n\nExample 3:\n\nInput: piles = [9,8,7,6,5,1,2,3,4]\nOutput: 18\n\n\n \nConstraints:\n\n\n\t3 <= piles.length <= 105\n\tpiles.length % 3 == 0\n\t1 <= piles[i] <= 104\n\n", "solution_py": "class Solution:\n def maxCoins(self, piles: List[int]) -> int:\n piles.sort()\n n = len(piles)\n k = n // 3\n i, j = 0, 2\n ans = 0\n while i < k:\n ans += piles[n-j]\n j += 2\n i +=1\n return ans", "solution_js": "var maxCoins = function(piles) {\n let count = 0, i = 0, j = piles.length - 1;\n piles.sort((a, b) => b - a);\n\n while(i < j) {\n count += piles[i + 1];\n i += 2;\n j--;\n }\n\n return count;\n};", "solution_java": "class Solution {\n public int maxCoins(int[] piles) {\n Arrays.sort(piles);\n int s=0,n=piles.length;\n for(int i=n/3;i& piles) {\n sort(piles.begin(),piles.end(),greater());\n int myPilesCount=0;\n int myPilesSum=0;\n int PilesSize=piles.size();\n int i=1;\n while(myPilesCount<(PilesSize/3))\n {\n\n myPilesSum+=piles[i];\n myPilesCount++;\n i+=2;\n }\n return myPilesSum;\n }\n};" }, { "title": "Truncate Sentence", "algo_input": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).\n\n\n\tFor example, \"Hello World\", \"HELLO\", and \"hello world hello world\" are all sentences.\n\n\nYou are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.\n\n \nExample 1:\n\nInput: s = \"Hello how are you Contestant\", k = 4\nOutput: \"Hello how are you\"\nExplanation:\nThe words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".\n\n\nExample 2:\n\nInput: s = \"What is the solution to this problem\", k = 4\nOutput: \"What is the solution\"\nExplanation:\nThe words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".\n\nExample 3:\n\nInput: s = \"chopper is not a tanuki\", k = 5\nOutput: \"chopper is not a tanuki\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 500\n\tk is in the range [1, the number of words in s].\n\ts consist of only lowercase and uppercase English letters and spaces.\n\tThe words in s are separated by a single space.\n\tThere are no leading or trailing spaces.\n\n", "solution_py": "class Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n words = s.split(\" \")\n return \" \".join(words[0:k])", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar truncateSentence = function(s, k) {\n return s.split(\" \").slice(0,k).join(\" \")\n};", "solution_java": "class Solution {\n public String truncateSentence(String s, int k) {\n int n = s.length();\n int count = 0;\n int i = 0;\n while(i target) {\n high = mid - 1;\n }\n }\n return -1;\n}\n\nvar searchMatrix = function(matrix, target) {\n for (let i = 0; i < matrix.length; i++) {\n let check = binarySearch(matrix[i], target);\n\n if (check != -1) { return true }\n }\n return false\n};", "solution_java": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n int lo = 0, hi = rows;\n while(lo + 1 < hi) {\n int mid = lo + (hi - lo) / 2;\n if (matrix[mid][0] <= target) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n int[] prospect;\n for (int i = 0; i <= lo; i++) {\n prospect = matrix[i];\n int l = 0;\n int h = cols;\n while (l + 1 < h) {\n int mid = l + (h - l) / 2;\n if (prospect[mid] <= target) {\n l = mid;\n } else {\n h = mid;\n }\n }\n if (prospect[l] == target) {\n return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool searchMatrix(vector>& matrix, int target) {\n for(int i=0;itarget)\n {\n e=mid-1;\n }\n else if(matrix[i][mid] bool:\n return set(word1) == set(word2) and Counter(Counter(word1).values()) == Counter(Counter(word2).values())", "solution_js": "var closeStrings = function(word1, word2) {\n if (word1.length != word2.length) return false;\n let map1 = new Map(), map2 = new Map(),freq1=new Set(),freq2=new Set();\n for (let i = 0; i < word1.length; i++) map1.set(word1[i],map1.get(word1[i])+1||1),map2.set(word2[i],map2.get(word2[i])+1||1);\n if (map1.size != map2.size) return false;\n for (const [key,value] of map1) {\n if (!map2.has(key)) return false\n freq1.add(value);\n freq2.add(map2.get(key));\n }\n if (freq1.size != freq2.size) return false;\n for (const freq of freq1) if (!freq2.has(freq)) return false\n return true; \n};", "solution_java": "class Solution {\n private int N = 26;\n public boolean closeStrings(String word1, String word2) {\n // count the English letters\n int[] arr1 = new int[N], arr2 = new int[N];\n for (char ch : word1.toCharArray())\n arr1[ch - 'a']++;\n for (char ch : word2.toCharArray())\n arr2[ch - 'a']++;\n\n // if one has a letter which another one doesn't have, dont exist\n for (int i = 0; i < N; i++) {\n if (arr1[i] == arr2[i]) {\n continue;\n }\n if (arr1[i] == 0 || arr2[i] == 0) {\n return false;\n }\n }\n Arrays.sort(arr1);\n Arrays.sort(arr2);\n for (int i = 0; i < N; i++) {\n if (arr1[i] != arr2[i]) {\n return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool closeStrings(string word1, string word2) {\n set w1_letters, w2_letters, w1_freq, w2_freq;\n unordered_map w1_m, w2_m;\n \n for (auto a : word1) {\n w1_letters.insert(a);\n w1_m[a]++;\n }\n \n for (auto a : word2) {\n w2_letters.insert(a);\n w2_m[a]++;\n }\n \n for (auto [k, v] : w1_m) w1_freq.insert(v);\n \n for (auto [k, v] : w2_m) w2_freq.insert(v);\n\n return w1_letters == w2_letters && w1_freq == w2_freq;\n }\n};" }, { "title": "Average of Levels in Binary Tree", "algo_input": "Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.\n \nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\n\n\nExample 2:\n\nInput: root = [3,9,20,15,7]\nOutput: [3.00000,14.50000,11.00000]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 <= Node.val <= 231 - 1\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# O(n) || O(h) where h is the height of the tree\n def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n\n queue = deque([root])\n result = []\n\n while queue:\n runningSum = 0\n newLevelSize = 0\n for i in range(len(queue)):\n currNode = queue.popleft()\n\n runningSum += currNode.val\n newLevelSize += 1\n\n if currNode.left:\n queue.append(currNode.left)\n if currNode.right:\n queue.append(currNode.right)\n\n secretFormula = (runningSum/newLevelSize)\n\n result.append(secretFormula)\n\n return result", "solution_js": "var averageOfLevels = function(root) {\nlet avg = [root.val];\nlet level = [];\nlet queue = [root];\nwhile(queue.length>0){\n let curr = queue.shift();\n if(curr.left){\n level.push(curr.left)\n }\n if(curr.right){\n level.push(curr.right);\n }\n if(queue.length===0){\n queue.push(...level);\n avg.push(level.reduce((a,b) => a+b.val,0)/level.length);\n level = [];\n }\n}\navg.pop()\nreturn avg;\n};", "solution_java": "class Solution {\n public List averageOfLevels(TreeNode root) {\n Queue q = new LinkedList<>(List.of(root));\n List ans = new ArrayList<>();\n while (q.size() > 0) {\n double qlen = q.size(), row = 0;\n for (int i = 0; i < qlen; i++) {\n TreeNode curr = q.poll();\n row += curr.val;\n if (curr.left != null) q.offer(curr.left);\n if (curr.right != null) q.offer(curr.right);\n }\n ans.add(row/qlen);\n }\n return ans;\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 // Pre-Requisite for this solution: Level order traversal of a BT Line by Line\n \n vector averageOfLevels(TreeNode* root) {\n // vector to store the result\n vector avgVal;\n avgVal.push_back(root->val);\n \n // Queue for level order traversal Line by Line\n queue q;\n q.push(root);\n q.push(NULL);\n \n // To store values for levels\n double levelSum = 0;\n double levelCount = 0;\n \n // Standard Level order traversal Line by Line code\n while(q.empty() == false){\n TreeNode* curr = q.front(); q.pop();\n \n if(curr == NULL){\n if(q.empty()==true){\n break;\n }\n else{ // Here we know that we are at the end of a line\n \n // So we push the result into the vector\n avgVal.push_back(levelSum/levelCount);\n \n // Reset the counters and push End of Level into the queue.\n levelSum = 0;\n levelCount = 0;\n q.push(NULL);\n continue;\n }\n }\n \n // Note that when we are traversing one level\n // we are getting sum and count of the next level\n // Hence, we are moving one level ahead\n if(curr->left){\n q.push(curr->left);\n levelSum += curr->left->val;\n levelCount++;\n }\n if(curr->right){\n q.push(curr->right);\n levelSum += curr->right->val;\n levelCount++;\n }\n }\n return avgVal;\n }\n};" }, { "title": "Regular Expression Matching", "algo_input": "Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:\n\n\n\t'.' Matches any single character.​​​​\n\t'*' Matches zero or more of the preceding element.\n\n\nThe matching should cover the entire input string (not partial).\n\n \nExample 1:\n\nInput: s = \"aa\", p = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\n\n\nExample 2:\n\nInput: s = \"aa\", p = \"a*\"\nOutput: true\nExplanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n\n\nExample 3:\n\nInput: s = \"ab\", p = \".*\"\nOutput: true\nExplanation: \".*\" means \"zero or more (*) of any character (.)\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 20\n\t1 <= p.length <= 30\n\ts contains only lowercase English letters.\n\tp contains only lowercase English letters, '.', and '*'.\n\tIt is guaranteed for each appearance of the character '*', there will be a previous valid character to match.\n\n", "solution_py": "class Solution:\n def isMatch(self, s, p):\n n = len(s)\n m = len(p)\n dp = [[False for _ in range (m+1)] for _ in range (n+1)]\n dp[0][0] = True\n for c in range(1,m+1):\n if p[c-1] == '*' and c > 1:\n dp[0][c] = dp[0][c-2]\n for r in range(1,n+1):\n for c in range(1,m+1):\n if p[c-1] == s[r-1] or p[c-1] == '.':\n dp[r][c] = dp[r-1][c-1]\n elif c > 1 and p[c-1] == '*':\n if p[c-2] =='.' or s[r-1]==p[c-2]:\n dp[r][c] =dp[r][c-2] or dp[r-1][c]\n else:\n dp[r][c] = dp[r][c-2]\n return dp[n][m]", "solution_js": "/**\n * @param {string} s\n * @param {string} p\n * @return {boolean}\n */\n\nvar isMatch = function(s, p) {\n const pattern = new RegExp('^'+p+'$'); // ^ means start of string, $ means end of the string, these are to prevent certain pattern that match a part of the string to be returned as true.\n return pattern.test(s);\n};", "solution_java": "class Solution {\n public boolean isMatch(String s, String p) {\n if (p == null || p.length() == 0) return (s == null || s.length() == 0);\n\n boolean dp[][] = new boolean[s.length()+1][p.length()+1];\n dp[0][0] = true;\n for (int j=2; j<=p.length(); j++) {\n dp[0][j] = p.charAt(j-1) == '*' && dp[0][j-2];\n }\n\n for (int j=1; j<=p.length(); j++) {\n for (int i=1; i<=s.length(); i++) {\n if (p.charAt(j-1) == s.charAt(i-1) || p.charAt(j-1) == '.')\n dp[i][j] = dp[i-1][j-1];\n else if(p.charAt(j-1) == '*')\n dp[i][j] = dp[i][j-2] || ((s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == '.') && dp[i-1][j]);\n }\n }\n return dp[s.length()][p.length()];\n }\n}", "solution_c": "class Solution {\npublic:\n bool isMatch(string s, string p) {\n return helper(s,p,0,0);\n }\n \n bool helper(string s, string p, int i, int j)\n {\n if(j==p.length())\n return i==s.length();\n bool first_match=(i 0) {\n const [row, col, dist] = queue.shift();\n\n if (visited[row][col]) continue;\n\n visited[row][col] = true;\n\n const price = grid[row][col];\n\n if (withinRange(price, low, high)) {\n items.push({ dist, price, row, col });\n }\n\n for (let i = 0; i < dirs.length - 1; ++i) {\n const neiRow = row + dirs[i];\n const neiCol = col + dirs[i + 1];\n\n if (withinBound(neiRow, neiCol) && !visited[neiRow][neiCol] && grid[neiRow][neiCol] != 0) {\n queue.push([neiRow, neiCol, dist + 1]);\n }\n }\n }\n\n items.sort(compareFunc);\n\n const res = [];\n\n for (let i = 0; i < Math.min(k, items.length); ++i) {\n const { dist, price, row, col } = items[i];\n\n res.push([row, col]);\n }\n\n return res;\n\n function withinRange(price, low, high) {\n return low <= price && price <= high;\n }\n\n function withinBound(row, col) {\n return row >= 0 && col >= 0 && row < m && col < n;\n }\n\n function compareFunc(a, b) {\n return a.dist - b.dist || a.price - b.price || a.row - b.row || a.col - b.col;\n }\n};", "solution_java": "class Solution {\n static class Quad\n {\n int x,y,price,dist;\n Quad(int x,int y,int price,int dist)\n {\n this.x=x;\n this.y=y;\n this.price=price;\n this.dist=dist;\n }\n }\n public List> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {\n List> ans=new LinkedList<>();\n PriorityQueue pq=new PriorityQueue<>((a,b)->{\n if(a.dist!=b.dist)\n return a.dist-b.dist;\n if(a.price!=b.price)\n return a.price-b.price;\n if(a.x!=b.x)\n return a.x-b.x;\n return a.y-b.y;\n });\n bfs(grid,start[0],start[1],pricing[0],pricing[1],pq);\n while(!pq.isEmpty()&&k-->0)\n {\n Quad quad=pq.poll();\n List temp=new LinkedList<>();\n temp.add(quad.x);\n temp.add(quad.y);\n ans.add(temp);\n }\n return ans;\n }\n void bfs(int[][] grid,int i,int j,int low,int high,PriorityQueue pq)\n {\n Queue queue=new LinkedList<>();\n int m=grid.length,n=grid[0].length;\n if(grid[i][j]>=low&&grid[i][j]<=high)\n pq.add(new Quad(i,j,grid[i][j],0));\n grid[i][j]=0;\n queue.add(new int[]{i,j});\n int dist=0;\n int dirs[][]={{1,0},{-1,0},{0,1},{0,-1}};\n while(!queue.isEmpty())\n {\n ++dist;\n int size=queue.size();\n while(size-->0)\n {\n int[] p=queue.poll();\n for(int[] dir:dirs)\n {\n int newX=dir[0]+p[0];\n int newY=dir[1]+p[1];\n if(newX>=0&&newY>=0&&newX=low&&grid[newX][newY]<=high)\n pq.add(new Quad(newX,newY,grid[newX][newY],dist));\n queue.add(new int[]{newX,newY});\n grid[newX][newY]=0;\n }\n }\n }\n \n }\n }\n \n\n}", "solution_c": "class Solution {\npublic:\n struct cell\n {\n int dist;\n int cost;\n int row;\n int col;\n };\n struct compare\n {\n bool operator()(const cell &a, const cell &b)\n {\n if(a.dist != b.dist)\n return a.dist < b.dist;\n else if(a.cost != b.cost)\n return a.cost < b.cost;\n else if(a.row != b.row)\n return a.row < b.row;\n else\n return a.col < b.col;\n }\n };\n\n vector> highestRankedKItems(vector>& grid, vector& pricing, vector& start, int k) {\n int m=grid.size();\n int n=grid[0].size();\n\n queue>q;\n q.push({start[0],start[1]});\n\n vector> vis(m,vector(n,false));\n vis[start[0]][start[1]]=true;\n\n int dx[4]={-1,0,1,0};\n int dy[4]={0,-1,0,1};\n int dist=0;\n\n priority_queue,compare> pq;\n while(!q.empty())\n {\n int size=q.size();\n while(size--)\n {\n pair p=q.front(); q.pop();\n if(grid[p.first][p.second]!=1 && grid[p.first][p.second]>=pricing[0] && grid[p.first][p.second]<=pricing[1])\n {\n pq.push({dist,grid[p.first][p.second],p.first,p.second});\n\n if(pq.size()>k)\n pq.pop();\n }\n for(int k=0;k<4;k++)\n {\n int x=p.first+dx[k];\n int y=p.second+dy[k];\n\n if(x>=0 && x=0 && y> ans;\n while(!pq.empty())\n {\n ans.push_back({pq.top().row,pq.top().col});\n pq.pop();\n }\n\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};" }, { "title": "Longest String Chain", "algo_input": "You are given an array of words where each word consists of lowercase English letters.\n\nwordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.\n\n\n\tFor example, \"abc\" is a predecessor of \"abac\", while \"cba\" is not a predecessor of \"bcad\".\n\n\nA word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.\n\nReturn the length of the longest possible word chain with words chosen from the given list of words.\n\n \nExample 1:\n\nInput: words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput: 4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].\n\n\nExample 2:\n\nInput: words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput: 5\nExplanation: All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].\n\n\nExample 3:\n\nInput: words = [\"abcd\",\"dbqca\"]\nOutput: 1\nExplanation: The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 1000\n\t1 <= words[i].length <= 16\n\twords[i] only consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \n words.sort(key=len)\n dic = {}\n \n for i in words:\n dic[ i ] = 1\n \n for j in range(len(i)):\n \n # creating words by deleting a letter\n successor = i[:j] + i[j+1:]\n if successor in dic:\n dic[ i ] = max (dic[i], 1 + dic[successor])\n \n res = max(dic.values())\n return res", "solution_js": "/**\n * @param {string[]} words\n * @return {number}\n */\nvar longestStrChain = function(words) \n{\n let tiers = new Array(16);\n for(let i=0; i0; i--)\n {\n for(let w2=0; w2= tiers[i][w2].len+1)\n continue;\n if(isPredecessor(tiers[i-1][w1].word, tiers[i][w2].word))\n tiers[i-1][w1].len = tiers[i][w2].len+1;\n }\n }\n }\n \n let max = 0;\n for(let i=0; i a.length()-b.length()); //as Sequence/Subset are not ordered\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j] + 1;\n maxi = Math.max(maxi,dp[i]);\n }\n }\n }//for neds\n return maxi;\n }\n}", "solution_c": "class Solution {\n int dfs(unordered_map& m, unordered_set& setWords, \n const string& w) {\n if (m.count(w)) return m[w];\n int maxLen = 1;\n \n for(int i=0;i& words) {\n \n unordered_map m;\n unordered_set setWords(words.begin(), words.end());\n int res = 0;\n\t\t\n for(auto& w:words) {\n res = max(res, dfs(m, setWords, w));\n }\n return res;\n }\n};" }, { "title": "Possible Bipartition", "algo_input": "We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.\n\nGiven the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.\n\n \nExample 1:\n\nInput: n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput: true\nExplanation: group1 [1,4] and group2 [2,3].\n\n\nExample 2:\n\nInput: n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput: false\n\n\nExample 3:\n\nInput: n = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2000\n\t0 <= dislikes.length <= 104\n\tdislikes[i].length == 2\n\t1 <= dislikes[i][j] <= n\n\tai < bi\n\tAll the pairs of dislikes are unique.\n\n", "solution_py": "class Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n def dfs(i, c):\n if color[i] != 0:\n if color[i] != c:\n return False\n return True\n\n color[i] = c\n for u in e[i]:\n if not dfs(u, 3 - c):\n return False\n return True\n\n e = [[] for _ in range(n)]\n for u, v in dislikes:\n u -= 1\n v -= 1\n e[u].append(v)\n e[v].append(u)\n color = [0] * n\n for i in range(n):\n if color[i] == 0:\n if not dfs(i, 1):\n return False\n return True", "solution_js": "var possibleBipartition = function(n, dislikes) {\n const g = new Map();\n dislikes.forEach(([a, b]) => {\n const aDis = g.get(a) || [];\n const bDis = g.get(b) || [];\n g.set(a, aDis.concat(b));\n g.set(b, bDis.concat(a));\n });\n \n const vis = new Array(n+1).fill(false);\n const col = new Array(n+1).fill(-1);\n \n const dfs = (n, c = 0) => {\n if(vis[n]) return true;\n \n col[n] = c;\n vis[n] = true;\n \n const nodes = g.get(n) || [];\n for(let node of nodes) {\n if(!vis[node]) {\n if(!dfs(node, 1 - c)) return false;\n }\n \n if(node != n && col[node] == c) return false;\n }\n \n return true;\n };\n \n let canBi = true;\n for(let i = 1; i <= n; i++) {\n canBi &= dfs(i);\n }\n return canBi;\n};", "solution_java": "class Solution {\n int[] rank;\n int[] parent;\n int[] rival;\n public boolean possibleBipartition(int n, int[][] dislikes) {\n rank = new int[n+1];\n rival = new int[n+1];\n parent = new int[n+1];\n for(int i = 1;i <= n;i++){\n rank[i] = 1;\n parent[i] = i;\n }\n for(int[] dis : dislikes){\n int x = dis[0], y = dis[1];\n if(find(x) == find(y))\n return false;\n if(rival[x] != 0)\n union(rival[x], y);\n else\n rival[x] = y;\n if(rival[y] != 0)\n union(rival[y], x);\n else\n rival[y] = x;\n }\n return true;\n }\n public int find(int x){\n if(parent[x] == x)\n return x;\n return parent[x] = find(parent[x]);\n }\n public void union(int x, int y){\n int x_set = find(x);\n int y_set = find(y);\n if(x_set == y_set)\n return;\n if(rank[x_set] < rank[y_set])\n parent[x_set] = y_set;\n else if(rank[y_set] < rank[x_set])\n parent[y_set] = x_set;\n else{\n parent[x_set] = y_set;\n rank[y_set]++;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n \n bool dfs(vectoradj[], vector& color, int node){\n for(auto it: adj[node]){ //dfs over adjacent nodes\n if(color[it]==-1){ //not visited yet\n color[it]=1-color[node]; //set different color of adjacent nodes \n if(!dfs(adj,color,it)) return false;\n }\n else if(color[it]!=1-color[node]) return false; //if adjacent nodes have same color\n }\n return true;\n }\n \n \n bool possibleBipartition(int n, vector>& dislikes) {\n vectoradj[n+1];\n for(int i=0;icolor(n+1,-1); //-1 i.e. not visited yet\n for(int i=1;i<=n;i++){\n if(color[i]==-1){\n color[i]=0;\n if(!dfs(adj,color,i)) return false;\n }\n }\n return true;\n }\n};" }, { "title": "Odd Even Jump", "algo_input": "You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\n\nYou may jump forward from index i to index j (with i < j) in the following way:\n\n\n\tDuring odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n\tDuring even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n\tIt may be the case that for some index i, there are no legal jumps.\n\n\nA starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).\n\nReturn the number of good starting indices.\n\n \nExample 1:\n\nInput: arr = [10,13,12,14,15]\nOutput: 2\nExplanation: \nFrom starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.\n\n\nExample 2:\n\nInput: arr = [2,3,1,1,4]\nOutput: 3\nExplanation: \nFrom starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.\n\n\nExample 3:\n\nInput: arr = [5,1,3,4,2]\nOutput: 3\nExplanation: We can reach the end from starting indices 1, 2, and 4.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 2 * 104\n\t0 <= arr[i] < 105\n\n", "solution_py": "class Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n \n l = len(arr)\n res = [False]*l\n res[-1] = True\n \n # for odd jump: for i, get next larger one \n odd_next = [i for i in range(l)]\n stack = [] # mono inc for ind\n for n, i in sorted([(arr[i], i) for i in range(l)]):\n while stack and stack[-1] new Array(len).fill(false))\n \n // Build a BST to maintain logN search/Insert\n function treeNode(value) {\n this.val = value;\n this.left = null;\n this.right = null;\n }\n \n const root = new TreeNode(arr[len - 1])\n \n function InsertToBST(val) {\n function dfs(node){\n if(node.val < val) {\n if(!node.right) node.right = new TreeNode(val);\n else dfs(node.right);\n }\n if(node.val > val) {\n if(!node.left) node.left = new TreeNode(val);\n else dfs(node.left);\n }\n }\n \n dfs(root);\n }\n \n \n \n \n memo[0][len - 1] = memo[1][len - 1] = true;\n map[arr[len - 1]] = len - 1;\n \n //memo[0] odd jumps\n //memo[1] even jumps\n \n function getNextBig(base) { // odd jump\n if(map[base] !== undefined) {\n return base\n }\n let result = Infinity\n function dfs(node) {\n if(!node) return;\n \n if(node.val > base && node.val < result) {\n result = node.val;\n dfs(node.left)\n }\n \n if(node.val < base) {\n dfs(node.right);\n }\n }\n \n dfs(root)\n \n return result === Infinity ? false : result;\n }\n \n function getNextSmall(base) { //even jump\n if(map[base] !== undefined) {\n return base\n }\n let result = -Infinity\n function dfs(node) {\n if(!node) return;\n \n if(node.val < base && node.val > result) {\n result = node.val;\n dfs(node.right)\n }\n \n if(node.val > base) {\n dfs(node.left);\n }\n }\n \n dfs(root)\n \n return result === -Infinity ? false : result;\n }\n \n for(let i = len - 2; i >= 0; i--) {\n let nextBig = getNextBig(arr[i])\n let nextSmall = getNextSmall(arr[i])\n \n memo[0][i] = nextBig ? memo[1][map[nextBig]] : nextBig;\n memo[1][i] = nextSmall ? memo[0][map[nextSmall]] : nextSmall;\n map[arr[i]] = i;\n InsertToBST(arr[i])\n }\n\n return memo[0].filter(boo => boo).length\n \n};", "solution_java": "class Solution {\n public int oddEvenJumps(int[] arr) {\n\n int len = arr.length;\n int minjmp[] = new int[len];\n int maxjmp[] = new int[len];\n\n TreeMap map = new TreeMap<>();\n int evjmp, oddjmp;\n for(int i = len-1; i>=0; i--)\n {\n Integer minpos = map.floorKey(arr[i]);\n evjmp = (minpos != null)?map.get(minpos):len; //default len, to show not possible\n\n if(evjmp != len && (evjmp == len-1 || maxjmp[evjmp] == len-1))\n evjmp = len-1; //check the last pos reachability\n\n Integer maxpos = map.ceilingKey(arr[i]);\n oddjmp = (maxpos != null) ? map.get(maxpos):len;\n\n if(oddjmp != len && (oddjmp == len-1 || minjmp[oddjmp] == len-1))\n oddjmp = len-1;//check the last pos reachability\n\n minjmp[i] = evjmp; //specify possible jump path, if not possible assign len\n maxjmp[i] = oddjmp;//specify possible jump path, if not possible assign len\n\n map.put(arr[i],i); //put the current index\n }\n\n int res = 0;\n\n for(int i = 0; i< len-1; i++) {\n\n if(maxjmp[i] == len-1)\n res++;\n }\n\n return res+1; //since last position will always be the answer\n }\n\n}", "solution_c": "class Solution {\nprivate:\n void tryOddJump(const int idx,\n const int val,\n std::map& visitedNode,\n vector& oddJumpsDP,\n vector& evenJumpsDP) {\n // looking for equal or bigger element and it's going to be smallest posible\n auto jumpPoint = visitedNode.lower_bound(val);\n // If from jumpPoint exists even jump further, then odd jump will have some value\n if(jumpPoint != visitedNode.end()) oddJumpsDP[idx] = evenJumpsDP[jumpPoint->second];\n }\n \n void tryEvenJump(const int idx,\n const int val,\n std::map& visitedNode,\n vector& oddJumpsDP,\n vector& evenJumpsDP) {\n //looking for strictly bigger element because then I can be sure that previous will be equal or less that val for sure\n auto jumpPoint = visitedNode.upper_bound(val);\n // if it's first element, then there is no equal or less option, so no even jump possible\n if(jumpPoint != visitedNode.begin()) \n evenJumpsDP[idx] = oddJumpsDP[std::prev(jumpPoint)->second]; // (jumpPoint-1) check if further odd jump is possible from largest element that is <= val \n }\npublic:\n int oddEvenJumps(vector& arr) {\n const size_t n = arr.size();\n vector oddJumpsDP(n, 0);\n vector evenJumpsDP(n, 0);\n oddJumpsDP[n-1] = 1;\n evenJumpsDP[n-1] = 1;\n std::map visitedNode;\n visitedNode[arr[n-1]] = n-1;\n \n /*\n Idea is to move backward and keep track of posibility of odd and even jumps from each cell.\n This way at any jump we could check if further jumps is possible.\n Example 1:\n v\n arr = [10,13,12,14,15]\n odd = [ -, -, 0, 1, 1]\n even= [ -, -, -, 0, 1]\n \n Let's say we curently have answers for 14 and 15 and trying to work on 12:\n tryOddJump() -> will give us 14 as only possible odd jump(arr[i] <= arr[j] and arr[j] is the smallest possible value), \n\t\t\t\tbut there is no EVEN jump from 14 further, \n\t\t\t\tso we cache odd jump for 12 as 0 as well. \n\t\t\t\tThat's why I called thouse variables as oddJumpsDP/evenJumpsDP,\n\t\t\t\tthey are caches for subproblems that helps in later computations.\n\t\t\t\tWithout them we would need to check entire further path starting from each cell and it's not efficient.\n */\n int res = 1;\n for(int i=n-2; i>=0; --i) {\n tryOddJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);\n tryEvenJump(i, arr[i], visitedNode, oddJumpsDP, evenJumpsDP);\n // we alwayse start from 1st jump that is odd jump, so we can add index to the result if odd jump from it is possible\n if(oddJumpsDP[i] == 1) ++res;\n visitedNode[arr[i]] = i;\n }\n \n return res;\n }\n};" }, { "title": "Minimum Insertions to Balance a Parentheses String", "algo_input": "Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:\n\n\n\tAny left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.\n\tLeft parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.\n\n\nIn other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.\n\n\n\tFor example, \"())\", \"())(())))\" and \"(())())))\" are balanced, \")()\", \"()))\" and \"(()))\" are not balanced.\n\n\nYou can insert the characters '(' and ')' at any position of the string to balance it if needed.\n\nReturn the minimum number of insertions needed to make s balanced.\n\n \nExample 1:\n\nInput: s = \"(()))\"\nOutput: 1\nExplanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.\n\n\nExample 2:\n\nInput: s = \"())\"\nOutput: 0\nExplanation: The string is already balanced.\n\n\nExample 3:\n\nInput: s = \"))())(\"\nOutput: 3\nExplanation: Add '(' to match the first '))', Add '))' to match the last '('.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of '(' and ')' only.\n\n", "solution_py": "class Solution:\n def minInsertions(self, s: str) -> int:\n leftbrackets = insertions = 0\n i, n = 0, len(s)\n\n while i < n:\n if s[i] == '(':\n leftbrackets += 1\n elif s[i] == ')':\n if i == n-1 or s[i+1] != ')': insertions += 1\n else: i += 1\n \n if not leftbrackets: insertions += 1\n else: leftbrackets -= 1\n \n i += 1\n \n return leftbrackets * 2 + insertions", "solution_js": "var minInsertions = function(s) {\n let rightNeeded = 0;\n let leftNeeded = 0;\n for (const char of s) {\n if (char === \"(\") {\n if (rightNeeded % 2 === 0) {\n rightNeeded += 2; \n } else { \n rightNeeded++;\n leftNeeded++;\n }\n } else {\n rightNeeded--;\n if (rightNeeded === -1 ){\n leftNeeded++;\n rightNeeded = 1;\n }\n }\n }\n return leftNeeded + rightNeeded;\n};", "solution_java": "class Solution {\n public int minInsertions(String s) {\n int open=0;\n int ans=0;\n\n for(int i=0;i0){\n open--;\n }\n else{\n ans++;\n }\n }\n else{\n if(open>0){\n open--;\n ans++;\n }\n else{\n ans+=2;\n }\n }\n }\n }\n ans+=2*open;\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minInsertions(string s) {\n stack st;\n int n = s.size();\n int insert = 0;\n for(int i = 0; i < n; i++)\n {\n if(s[i] == '(')\n {\n if(st.empty())\n {\n st.push(2);\n }\n else\n {\n if(st.top() != 2)\n {\n st.pop();\n insert++;\n }\n st.push(2);\n }\n }\n else\n {\n if(st.empty())\n {\n insert++;\n st.push(1);\n }\n else\n {\n int dummy = st.top();\n st.pop();\n dummy--;\n if(dummy)\n st.push(dummy);\n }\n }\n }\n while(!st.empty())\n {\n insert += st.top();\n st.pop();\n }\n return insert;\n }\n};" }, { "title": "A Number After a Double Reversal", "algo_input": "Reversing an integer means to reverse all its digits.\n\n\n\tFor example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.\n\n\nGiven an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.\n\n \nExample 1:\n\nInput: num = 526\nOutput: true\nExplanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.\n\n\nExample 2:\n\nInput: num = 1800\nOutput: false\nExplanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.\n\n\nExample 3:\n\nInput: num = 0\nOutput: true\nExplanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.\n\n\n \nConstraints:\n\n\n\t0 <= num <= 106\n\n", "solution_py": "class Solution(object):\n def isSameAfterReversals(self, num):\n\t\t# All you have to do is check the Trailing zeros\n return num == 0 or num % 10 # num % 10 means num % 10 != 0", "solution_js": "/**\n * @param {number} num\n * @return {boolean}\n */\nvar isSameAfterReversals = function(num) {\n if(num == 0) return true;\n if(num % 10 == 0) return false;\n return true;\n};", "solution_java": "class Solution {\n public boolean isSameAfterReversals(int num) {\n return (num%10!=0||num<10);\n }\n}", "solution_c": "class Solution {\npublic:\n bool isSameAfterReversals(int num) {\n return num == 0 || num % 10 > 0; // All you have to do is check the Trailing zeros\n }\n};" }, { "title": "Make The String Great", "algo_input": "Given a string s of lower and upper case English letters.\n\nA good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:\n\n\n\t0 <= i <= s.length - 2\n\ts[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.\n\n\nTo make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.\n\nReturn the string after making it good. The answer is guaranteed to be unique under the given constraints.\n\nNotice that an empty string is also good.\n\n \nExample 1:\n\nInput: s = \"leEeetcode\"\nOutput: \"leetcode\"\nExplanation: In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\n\n\nExample 2:\n\nInput: s = \"abBAcC\"\nOutput: \"\"\nExplanation: We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"\n\n\nExample 3:\n\nInput: s = \"s\"\nOutput: \"s\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts contains only lower and upper case English letters.\n\n", "solution_py": "class Solution:\n def makeGood(self, s: str) -> str:\n while True:\n for i in range(len(s)-1):\n if s[i].lower() == s[i+1].lower() and (s[i].islower() and s[i+1].isupper() or s[i].isupper() and s[i+1].islower()):\n s = s[:i]+s[i+2:]\n break\n else:\n break\n return s", "solution_js": "var makeGood = function(s) {\n const sArr = []\n for(let i = 0; i < s.length; i++) {\n sArr.push(s[i])\n }\n const popper = function() {\n let counter = 0\n for(let i = 0; i < sArr.length; i++) {\n if(sArr[i] !== sArr[i + 1]) {\n if(sArr[i].toUpperCase() === sArr[i + 1] || sArr[i].toLowerCase() === sArr[i + 1]) {\n sArr.splice(i,2)\n counter++\n }\n }\n }\n if(counter > 0) {\n popper()\n }\n }\n popper()\n \n return sArr.join('');\n};\n\nconvert string to array to allow access to splice method. iterate over array checking for eqality between i and i +1 in the array. if equal, do nothing. if not equal convert to lower/uppercase and again check for equality. if equal splice those two from the array. counter checks if anything has been removed, if it has it iterates over the array again", "solution_java": "class Solution {\npublic String makeGood(String s) {\n char[] res = s.toCharArray();\n int i = 0;\n for( char n: s.toCharArray())\n {\n res[i] = n;\n \n if(i>0 && Math.abs((int) res[i-1]- (int) res[i])==32)\n {\n i-=2;\n }\n i++;\n }\n return new String(res, 0, i);\n}\n}", "solution_c": "class Solution {\npublic:\n string makeGood(string s) {\n \tstackst;\n\tst.push(s[0]);\n\tstring ans=\"\";\n\n\tfor(int i=1;i int:\n \n # previous continuous occurrence, current continuous occurrence\n pre_cont_occ, cur_cont_occ = 0, 1\n \n # counter for binary substrings with equal 0s and 1s\n counter = 0\n \n\t\t# scan each character pair in s\n for idx in range(1, len(s)):\n \n if s[idx] == s[idx-1]:\n \n # update current continuous occurrence\n cur_cont_occ += 1\n \n else:\n # update counter of binary substrings between prevous character group and current character group\n counter += min(pre_cont_occ, cur_cont_occ)\n\n # update previous as current's continuous occurrence\n pre_cont_occ = cur_cont_occ\n \n # reset current continuous occurrence to 1\n cur_cont_occ = 1\n \n # update for last time\n counter += min(pre_cont_occ, cur_cont_occ)\n \n return counter", "solution_js": "/**\n * find all bit switches '01' and '10'. \n * From each one expand sideways: i goes left, j goes right\n * Until:\n * if '01' -> i,j != 0,1\n * if '10' -> i,j != 1,0\n * and within input boundaries\n */\nvar countBinarySubstrings = function(s) {\n let i = 0;\n const n = s.length;\n let count = 0;\n while (i < n-1) {\n if (s[i] != s[i+1]) {\n if (s[i] === '0') {\n count += countZeroOnes(s, i, true);\n } else {\n count += countZeroOnes(s, i, false);\n }\n \n }\n i++;\n }\n return count;\n \n // count the number of valid substrings substrings\n function countZeroOnes(s, start, startsWithZero) {\n let count = 0;\n let i = start;\n let j = start+1;\n const n = s.length;\n if (startsWithZero) {\n while(i >= 0 && j < n && s[i] === '0' && s[j] === '1') {\n count++;\n i--;\n j++;\n }\n } else {\n while(i >= 0 && j < n && s[i] === '1' && s[j] === '0') {\n count++;\n i--;\n j++;\n }\n }\n return count;\n }\n}", "solution_java": "class Solution\n{\n public int countBinarySubstrings(String s)\n {\n int i , prevRunLength = 0 , curRunLength = 1 , count = 0 ;\n for ( i = 1 ; i < s.length() ; i++ )\n {\n if( s.charAt(i) == s.charAt( i - 1 ) )\n {\n curRunLength++;\n }\n else\n {\n prevRunLength = curRunLength;\n curRunLength = 1;\n }\n if(prevRunLength >= curRunLength)\n {\n count++ ;\n }\n }\n return count ;\n }\n}", "solution_c": "class Solution {\npublic:\n int countBinarySubstrings(string s) {\n int prev=0;\n int curr=1;\n int sum=0;\n\n for(int i=1;i List[str]:\n \n def is_within_1hr(t1, t2):\n h1, m1 = t1.split(\":\")\n h2, m2 = t2.split(\":\")\n if int(h1) + 1 < int(h2): return False\n if h1 == h2: return True\n return m1 >= m2\n \n records = collections.defaultdict(list)\n for name, time in zip(keyName, keyTime):\n records[name].append(time)\n \n rv = []\n for person, record in records.items():\n record.sort()\n\t\t\t# Loop through 2 values at a time and check if they are within 1 hour.\n if any(is_within_1hr(t1, t2) for t1, t2 in zip(record, record[2:])):\n rv.append(person)\n return sorted(rv)\n ", "solution_js": "/**\n * @param {string[]} keyName\n * @param {string[]} keyTime\n * @return {string[]}\n */\nvar alertNames = function(keyName, keyTime) {\n // so we don't keep duplicates\n const abusers = new Set();\n // map: name->times[] (sorted)\n const times = {};\n for (let i=0; i 2) {\n times[name].sort();\n const len = times[name].length;\n // we check all triples for a time difference below 1 hour.\n // as times are sorted, we need to check all i and i+2\n for (let i=0; i parseInt(num));\n const [h2, m2] = t2.split(':').map(num => parseInt(num));\n if (h1 === h2) return true;\n if (h2-h1 > 1) return false;\n if (m2 <= m1) return true;\n }\n};", "solution_java": "class Solution {\n public List alertNames(String[] keyName, String[] keyTime) {\n Map> map = new HashMap<>();\n\t\t// for every entry in keyName and keyTime, add that time to a priorityqueue for that name\n for(int i=0;i pq = map.getOrDefault(keyName[i], new PriorityQueue());\n\t\t\t//convert the time to an integer (0- 2359 inclusive) for easy comparisons\n pq.add(Integer.parseInt(keyTime[i].substring(0,2))*100+Integer.parseInt(keyTime[i].substring(3)));\n map.put(keyName[i],pq);\n }\n \n\t\t// Generate the \"answer\" list\n List ans = new ArrayList<>();\n for(String s: map.keySet()){\n\t\t\t// For each name in the map, determine if that name used the keycard within 1 hour\n PriorityQueue pq = map.get(s);\n if(active(pq)){\n ans.add(s);\n }\n }\n \n\t\t// Sort the names alphabetically\n Collections.sort(ans);\n return ans;\n }\n \n\t// Greedy function to determine if there were 3 uses within an hour\n private boolean active(PriorityQueue pq){\n\t\t// If there are two or less entries, the user could not have entered 3 times, return false\n if(pq.size()<3) return false;\n\t\t\n\t\t// Create rolling data\n\t\t// Using PriorityQueues, the lowest number is removed first by default\n int a = pq.poll();\n int b = pq.poll();\n int c = pq.poll();\n \n\t\t// Test if two entrances are within 1 hour (100 in integer)\n if(c-a <=100) return true;\n while(pq.size()>0){\n a = b;\n b = c;\n c = pq.poll();\n if(c-a <=100) return true;\n }\n\t\t\n\t\t// If the full Queue has been checked, return false\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool timeDiff(vector timestamp, int index){\n int time1 = ((timestamp[index][0]-'0') * 10 + (timestamp[index][1]-'0')) * 60 + ((timestamp[index][3]-'0') * 10 + (timestamp[index][4]-'0'));\n int time2 = ((timestamp[index+2][0]-'0') * 10 + (timestamp[index+2][1]-'0')) * 60 + ((timestamp[index+2][3]-'0') * 10 + (timestamp[index+2][4]-'0'));\n \n if(abs(time2-time1)<=60) return true;\n return false;\n }\n \n vector alertNames(vector& keyName, vector& keyTime) {\n unordered_map> ht;\n \n for(int i=0; i result;\n for(auto time : ht){\n sort(time.second.begin(), time.second.end());\n for(int i=0; i+2 List[int]:\n gray_code = [x ^ (x >> 1) for x in range(2 ** n)]\n start_i = gray_code.index(start)\n return gray_code[start_i:] + gray_code[:start_i]", "solution_js": "var circularPermutation = function(n, start) {\n const grayCodes = [];\n\n let startIdx = -1;\n\n for (let i = 0; i <= 2**n - 1; i++) {\n grayCodes[i] = i ^ (i >> 1);\n\n if (grayCodes[i] == start) startIdx = i;\n }\n\n const res = [];\n\n for (let i = 0; i <= 2**n - 1; i++) {\n res[i] = grayCodes[startIdx];\n\n startIdx++;\n\n if (startIdx == grayCodes.length) startIdx = 0;\n }\n\n return res;\n};", "solution_java": "class Solution {\n public List circularPermutation(int n, int start) {\n List l = new ArrayList();\n int i=0;\n int len = (int)Math.pow(2,n);\n int[] arr = new int[len];\n while(i get_val(int n)\n {\n if(n==1)return {\"0\",\"1\"};\n vector v = get_val(n-1);\n vector ans;\n for(int i = 0;i=0;i--)\n {\n ans.push_back(\"1\" + v[i]);\n }\n return ans;\n }\n\n vector solve(int n)\n {\n vector v = get_val(n);\n vector ans;\n for(int i = 0;i circularPermutation(int n, int start) {\n\n vector v = solve(n);\n int ind;\n for(int i = 0;i ans;\n for(int i = ind;i int:\n @cache\n def dp(a,b,c):\n if a==n: return c==k\n return (b*dp(a+1,b,c) if b>=1 else 0) + sum(dp(a+1,i,c+1) for i in range(b+1,m+1))\n return dp(0,0,0)%(10**9+7)", "solution_js": "var numOfArrays = function(n, m, k){ \n let mod=1e9+7,\n // dp[i][c][j] the number of arrays of length i that cost c and their max element is j \n dp=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0))),\n // prefix[i][k][j] holds the prefix sum of dp[i][k][:j] \n prefix=[...Array(n+1)].map(d=>[...Array(k+1)].map(d=>[...Array(m+1)].map(d=>0)))\n //basecases\n dp[0][0][0] = 1\n prefix[0][0].fill(1)\n for(var i = 1; i <= n; i++) //length of array\n for(var x = 1; x <= k; x++) //curcost\n for(var j = 1; j <= m; j++) //curmax\n // the previous max can be anything (a+c)%mod)\n};", "solution_java": "class Solution {\n public int numOfArrays(int n, int m, int k) {\n int M = (int)1e9+7, ans = 0;\n int[][] dp = new int[m+1][k+1]; // maximum value, num of elements seen from left side\n for (int i = 1; i <= m; i++){\n dp[i][1]=1; // base case \n }\n for (int i = 2; i <= n; i++){\n int[][] next = new int[m+1][k+1];\n for (int j = 1; j <= m; j++){ // for the current max value\n for (int p = 1; p <= m; p++){ // previous max value\n for (int w = 1; w <= k; w++){ // for all possible k\n if (j>p){ // if current max is larger, update next[j][w] from dp[p][w-1]\n next[j][w]+=dp[p][w-1];\n next[j][w]%=M;\n }else{ // otherwise, update next[p][w] from dp[p][w]\n next[p][w]+=dp[p][w];\n next[p][w]%=M;\n }\n }\n }\n }\n dp=next;\n }\n for (int i = 1; i <= m; i++){ // loop through max that has k and sum them up.\n ans += dp[i][k];\n ans %= M;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numOfArrays(int n, int m, int k) {\n if(m int:\n Arr = [0] * n # i-th city has Arr[i] roads\n for A,B in roads:\n Arr[A] += 1 # Each road increase the road count\n Arr[B] += 1\n Arr.sort() # Cities with most road should receive the most score\n summ = 0\n for i in range(len(Arr)):\n summ += Arr[i] * (i+1) # Multiply city roads with corresponding score\n \n return summ", "solution_js": "var maximumImportance = function(n, roads) {\n const connectionCount = Array(n).fill(0)\n\n // Count the connections from each city\n // e.g. the 0th city's count will be stored at index zero in the array\n for (let [cityTo, cityFrom] of roads) {\n connectionCount[cityTo]++\n connectionCount[cityFrom]++\n }\n\n let cityToConnectionCount = []\n for (let city = 0; city < n; city++) {\n cityToConnectionCount.push([city, connectionCount[city]])// Store the [city, numberOfConnections]\n }\n\n // Created new array(sortedCities) for readability\n const sortedCities = cityToConnectionCount.sort((a,b) => b[1] - a[1])// sort by number of connections, the city with the greatest number of connections should be\n // the city with the greatest importance\n\n const values = Array(n).fill(0)\n let importance = n\n for (let i = 0; i < sortedCities.length; i++) {\n const [city, connectionCount] = cityToConnectionCount[i]\n values[city] = importance// City at the 0th position array is should be the city with the greatest importance\n importance--\n }\n\n // Sum the importance of each city, toCity => fromCity\n let res = 0\n for (let [to, from] of roads) {\n res += values[to] + values[from]\n }\n\n return res\n};```", "solution_java": "class Solution {\n public long maximumImportance(int n, int[][] roads) {\n long ans = 0, x = 1;\n long degree[] = new long[n];\n for(int road[] : roads){\n degree[road[0]]++;\n degree[road[1]]++;\n }\n Arrays.sort(degree);\n for(long i : degree) ans += i * (x++) ;\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n long long maximumImportance(int n, vector>& roads) {\n vectorind(n,0);\n \n for(auto it:roads)\n {\n ind[it[0]]++;\n ind[it[1]]++;\n }\n \n priority_queue pq;\n long long val = n,ans=0;\n \n for(int i=0;i int:\n beg = 1\n end = m * n\n while beg < end:\n mid = (beg + end) // 2\n curr = self.numSmaller(mid, m, n)\n if curr < k:\n beg = mid + 1\n else:\n end = mid\n return beg", "solution_js": "/**\n * @param {number} m\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar findKthNumber = function(m, n, k) {\n // lo always points to a value which is\n // not going to be our answer\n let lo = 0;\n let hi = m * n;\n\n // the loop stops when lo and hi point to two adjascent numbers\n // because lo is always incorrect, hi will contain our final answer\n while (lo + 1 < hi) {\n\n // As a general practice don't do a (lo + hi) / 2 because that\n // might cause integer overflow\n const mid = lo + Math.floor((hi - lo) / 2);\n const count = countLessThanEqual(mid, m, n);\n\n // Find the minimum mid, such that count >= k\n if (count >= k) {\n hi = mid;\n } else {\n lo = mid;\n }\n }\n return hi;\n};\n\nfunction countLessThanEqual(target, rows, cols) {\n let count = 0;\n // we move row by row in the multiplication table\n // Each row contains at max (target / rowIndex) elements less than\n // or equal to target. The number of cols would limit it though.\n for (let i = 1; i <= rows; i++) {\n count += Math.min(Math.floor(target / i), cols);\n }\n return count;\n}", "solution_java": "class Solution {\n public int findKthNumber(int m, int n, int k) {\n int lo = 1;\n int hi = m * n;\n \n while(lo < hi){\n int mid = lo + (hi - lo) / 2;\n \n if(count(mid, m, n) < k){\n lo = mid + 1;\n } else if(count(mid, m, n) >= k){\n hi = mid;\n }\n }\n return lo;\n }\n private int count(int mid, int m, int n){\n int ans = 0;\n for(int i = 1; i <= m; i++){\n int res = Math.min(mid / i, n);\n ans += res;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int findKthNumber(int m, int n, int k) {\n int high=m*n ,low=1;\n\n int mid=0, ans=1e9;\n while(low<=high)\n {\n mid=low+(high-low)/2;\n int temp=0;\n\n // for each i find the max value ,less than or equal to n , such that\n // i*j<=mid\n // add j to answer\n for(int i=1;i<=m;i++)\n temp+=min(mid/i,n);\n\n if(temp>=k)\n {\n ans=min(ans,mid);\n high=mid-1;\n }\n else\n low=mid+1;\n\n }\n return ans;\n }\n};" }, { "title": "Best Time to Buy and Sell Stock with Cooldown", "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 as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:\n\n\n\tAfter you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).\n\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 = [1,2,3,0,2]\nOutput: 3\nExplanation: transactions = [buy, sell, cooldown, buy, sell]\n\n\nExample 2:\n\nInput: prices = [1]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= prices.length <= 5000\n\t0 <= prices[i] <= 1000\n\n", "solution_py": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n \n cache = {}\n def dfs(i, buying):\n \n if i >= len(prices):\n return 0\n \n if (i, buying) in cache:\n return cache[(i, buying)]\n \n if buying:\n # if have sell the share in previous step\n # then currently we have two options\n # either buy or not buy(cooldown)\n \n # we have bought so, increment the index and set buying flag to not buying\n # and don't forget that we bought so, we have to reduce that share amount from profit\n buy = dfs(i+1, not buying) - prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( buy, cooldown )\n cache[(i, buying)] = profit\n \n else:\n # we have sell the share so, \n # we cannot buy next share we have to skip the next price(cooldown for one day)\n # set (not buying) flag to buying\n # we also have to add that share price to profit\n sell = dfs(i+2, not buying) + prices[i] \n \n cooldown = dfs(i+1, buying)\n \n profit = max( sell, cooldown )\n cache[(i, buying)] = profit\n \n return cache[(i, buying)]\n \n return dfs(0, True)", "solution_js": "/**\n * @param {number[]} prices\n * @return {number}\n */\nvar maxProfit = function(prices) {\n let dp = {};\n let recursiveProfit = (index,buy) =>{\n if(index>=prices.length){\n return 0;\n }\n if(dp[index+'_'+buy]) return dp[index+'_'+buy]\n if(buy){\n dp[index+'_'+buy] = Math.max(-prices[index]+recursiveProfit(index+1,0), 0+recursiveProfit(index+1,1))\n return dp[index+'_'+buy];\n }\n else{\n dp[index+'_'+buy]= Math.max(prices[index]+recursiveProfit(index+2,1),0+recursiveProfit(index+1,0))\n return dp[index+'_'+buy];\n }\n }\n return recursiveProfit(0,1);\n};", "solution_java": "class Solution {\n public int maxProfit(int[] prices) {\n\n int n = prices.length;\n\n int[][] dp = new int[n+2][2];\n\n for(int index = n-1; index>=0; index--){\n for(int buy = 0; buy<=1; buy++){\n\n int profit = 0;\n\n if(buy == 0){ // buy stocks\n profit = Math.max(-prices[index] + dp[index+1][1], 0 + dp[index+1][0]);\n }\n if(buy == 1){ // we can sell stocks\n profit = Math.max(prices[index] + dp[index+2][0], 0 + dp[index+1][1]);\n }\n dp[index][buy] = profit;\n }\n }\n return dp[0][0];\n }\n}", "solution_c": "class Solution {\n public:\n int maxProfit(vector& prices) {\n int n = prices.size();\n int ans = 0;\n vector dp(n, 0);\n for (int i = 1; i < n; ++i) {\n int max_dp = 0;\n for (int j = 0; j < i; ++j) {\n dp[i] = max(dp[i], prices[i] - prices[j] + max_dp);\n max_dp = max(max_dp, j > 0 ? dp[j - 1] : 0);\n }\n ans = max(ans, dp[i]);\n }\n return ans;\n }\n};" }, { "title": "Implement Stack using Queues", "algo_input": "Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).\n\nImplement the MyStack class:\n\n\n\tvoid push(int x) Pushes element x to the top of the stack.\n\tint pop() Removes the element on the top of the stack and returns it.\n\tint top() Returns the element on the top of the stack.\n\tboolean empty() Returns true if the stack is empty, false otherwise.\n\n\nNotes:\n\n\n\tYou must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.\n\tDepending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.\n\n\n \nExample 1:\n\nInput\n[\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 2, 2, false]\n\nExplanation\nMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False\n\n\n \nConstraints:\n\n\n\t1 <= x <= 9\n\tAt most 100 calls will be made to push, pop, top, and empty.\n\tAll the calls to pop and top are valid.\n\n\n \nFollow-up: Can you implement the stack using only one queue?\n", "solution_py": "class MyStack:\n\n def __init__(self):\n self.q1 = deque()\n self.q2 = deque()\n\n def push(self, x: int) -> None:\n self.q1.append(x)\n\n def pop(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n popped_element = self.q1.popleft()\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return popped_element\n\n def top(self) -> int:\n while len(self.q1) > 1:\n self.q2.append(self.q1.popleft())\n \n top_element = self.q1[0]\n \n self.q2.append(self.q1.popleft())\n \n # Swap q1 and q2\n self.q1, self.q2 = self.q2, self.q1\n \n return top_element\n\n def empty(self) -> bool:\n return len(self.q1) == 0", "solution_js": "var MyStack = function() {\n this.stack = [];\n};\n\n/** \n * @param {number} x\n * @return {void}\n */\nMyStack.prototype.push = function(x) {\n this.stack.push(x);\n};\n\n/**\n * @return {number}\n */\nMyStack.prototype.pop = function() {\n return this.stack.splice([this.stack.length-1], 1)\n};\n\n/**\n * @return {number}\n */\nMyStack.prototype.top = function() {\n return this.stack[this.stack.length-1]\n};\n\n/**\n * @return {boolean}\n */\nMyStack.prototype.empty = function() {\n return this.stack.length === 0 ? true : false;\n};\n\n/** \n * Your MyStack object will be instantiated and called as such:\n * var obj = new MyStack()\n * obj.push(x)\n * var param_2 = obj.pop()\n * var param_3 = obj.top()\n * var param_4 = obj.empty()\n */", "solution_java": "class MyStack {\n\n Queue queue = null;\n\n public MyStack() {\n queue = new LinkedList<>();\n }\n\n public void push(int x) {\n\n Queue tempQueue = new LinkedList<>();\n tempQueue.add(x);\n\n while(!queue.isEmpty()){\n tempQueue.add(queue.remove());\n }\n\n queue = tempQueue;\n\n }\n\n public int pop() {\n return queue.remove();\n }\n\n public int top() {\n return queue.peek();\n }\n\n public boolean empty() {\n return queue.isEmpty();\n }\n}", "solution_c": "class MyStack {\npublic:\n queue q1;\n queue q2;\n MyStack() {\n\n }\n\n void push(int x) {\n q1.push(x);\n }\n\n int pop() {\n\n while(q1.size() !=1){\n int temp = q1.front();\n q1.pop();\n q2.push(temp);\n }\n int temp = q1.front();\n q1.pop();\n while(!q2.empty()){\n int tp = q2.front();\n q2.pop();\n q1.push(tp);\n }\n return temp;\n }\n\n int top() {\n while(q1.size() !=1){\n int temp = q1.front();\n q1.pop();\n q2.push(temp);\n }\n int temp = q1.front();\n q1.pop();\n q2.push(temp);\n while(!q2.empty()){\n int tp = q2.front();\n q2.pop();\n q1.push(tp);\n }\n return temp;\n }\n\n bool empty() {\n if(q1.empty()){\n return true;\n }\n return false;\n }\n};\n\n/**\n * Your MyStack object will be instantiated and called as such:\n * MyStack* obj = new MyStack();\n * obj->push(x);\n * int param_2 = obj->pop();\n * int param_3 = obj->top();\n * bool param_4 = obj->empty();\n */" }, { "title": "Find Bottom Left Tree Value", "algo_input": "Given the root of a binary tree, return the leftmost value in the last row of the tree.\n\n \nExample 1:\n\nInput: root = [2,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,2,3,4,null,5,6,null,null,7]\nOutput: 7\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 <= Node.val <= 231 - 1\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 findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n \n res = root.val\n stack = [(0, root)]\n prev_d = 0\n \n while stack:\n \n curr_d, curr_v = stack.pop(0)\n \n if curr_v.left:\n stack.append((curr_d+1, curr_v.left))\n if prev_d != curr_d + 1:\n res = curr_v.left.val\n prev_d = curr_d+1\n \n if curr_v.right:\n stack.append((curr_d+1, curr_v.right))\n if prev_d != curr_d + 1:\n res = curr_v.right.val\n prev_d = curr_d+1\n \n return res\n\t\t\n\t\t# An Upvote will be encouraging", "solution_js": "var findBottomLeftValue = function(root) {\n let arr=[];\n let q=[root];\n while(q.length!==0){\n let current=q.shift();\n arr.push(current.val)\n if(current.right){\n q.push(current.right)\n }\n if(current.left){\n q.push(current.left);\n }\n }\n return arr[arr.length-1]\n};", "solution_java": "class Solution {\n int max = Integer.MIN_VALUE;\n int res = -1;\n public int findBottomLeftValue(TreeNode root) {\n check(root,0);\n return res;\n }\n void check(TreeNode root, int h){\n if(root==null)\n return;\n if(h>max){\n max=h;\n res = root.val;\n }\n check(root.left,h+1);\n check(root.right,h+1);\n }\n}", "solution_c": "class Solution {\npublic:\n int findBottomLeftValue(TreeNode* root) {\n queue q;\n q.push(root);\n int ans=root->val;\n \n while(!q.empty()){\n int n=q.size();\n for(int i=0;ival;\n \n if(curr->left) q.push(curr->left);\n if(curr->right) q.push(curr->right);\n }\n }\n return ans;\n }\n};" }, { "title": "Bitwise AND of Numbers Range", "algo_input": "Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.\n\n \nExample 1:\n\nInput: left = 5, right = 7\nOutput: 4\n\n\nExample 2:\n\nInput: left = 0, right = 0\nOutput: 0\n\n\nExample 3:\n\nInput: left = 1, right = 2147483647\nOutput: 0\n\n\n \nConstraints:\n\n\n\t0 <= left <= right <= 231 - 1\n\n", "solution_py": "class Solution:\n def rangeBitwiseAnd(self, left: int, right: int) -> int:\n if not left: return 0\n i = 0\n cur = left\n while cur + (cur & -cur) <= right:\n cur += cur & -cur\n left &= cur\n return left", "solution_js": "var rangeBitwiseAnd = function(left, right) {\n const a = left.toString(2);\n const b = right.toString(2);\n\n if (a.length !== b.length) {\n return 0;\n }\n\n let match = 0;\n\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n break;\n }\n\n match++;\n }\n\n return parseInt(b.substring(0, match).padEnd(b.length, '0'), 2);\n};", "solution_java": "class Solution {\npublic int rangeBitwiseAnd(int left, int right) {\n int count=0;\n while(left!=right){\n left>>=1;\n right>>=1;\n count++;\n }\n return right<<=count;\n}", "solution_c": "class Solution {\npublic:\n int rangeBitwiseAnd(int left, int right) {\n int t=0;\n while(left!=right){\n left= left>>1;\n right= right>>1;\n t++;\n }\n int ans= left;\n while(t--){\n ans= ans<<1;\n }\n return ans;\n }\n};" }, { "title": "Minimum Depth of Binary Tree", "algo_input": "Given a binary tree, find its minimum depth.\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\n\nNote: A leaf is a node with no children.\n\n \nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 2\n\n\nExample 2:\n\nInput: root = [2,null,3,null,4,null,5,null,6]\nOutput: 5\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 105].\n\t-1000 <= Node.val <= 1000\n\n", "solution_py": "class Solution(object):\n def minDepth(self, root):\n # Base case...\n # If the subtree is empty i.e. root is NULL, return depth as 0...\n if root is None: return 0\n # Initialize the depth of two subtrees...\n leftDepth = self.minDepth(root.left)\n rightDepth = self.minDepth(root.right)\n # If the both subtrees are empty...\n if root.left is None and root.right is None:\n return 1\n # If the left subtree is empty, return the depth of right subtree after adding 1 to it...\n if root.left is None:\n return 1 + rightDepth\n # If the right subtree is empty, return the depth of left subtree after adding 1 to it...\n if root.right is None:\n return 1 + leftDepth\n # When the two child function return its depth...\n # Pick the minimum out of these two subtrees and return this value after adding 1 to it...\n return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees...", "solution_js": "var minDepth = function(root) {\n if (!root){\n return 0\n }\n if(root.left && root.right){\n return Math.min(minDepth(root.left), minDepth(root.right)) + 1\n }\n if(root.right){\n return minDepth(root.right) + 1\n }\n if(root.left){\n return minDepth(root.left) + 1\n }\n return 1\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 int minDepth(TreeNode root) {\n if(root == null)\n return 0;\n \n int left = minDepth(root.left);\n int right = minDepth(root.right);\n if(root.left == null)\n return right+1;\n if(root.right == null)\n return left+1;\n return Math.min(left, right)+1;\n }\n}", "solution_c": "class Solution {\npublic:\n void maxlevel(TreeNode* root,int level,int &ans){\n if(!root)\n return ;\n\n if(!root->left && !root->right){\n ans=min(level,ans);\n return ;\n }\n\n maxlevel(root->left,level+1,ans);\n maxlevel(root->right,level+1,ans);\n }\n int minDepth(TreeNode* root) {\n if(!root)\n return 0;\n\n int ans=INT_MAX;\n maxlevel(root,0,ans);\n return ans+1;\n }\n};" }, { "title": "Lexicographical Numbers", "algo_input": "Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.\n\nYou must write an algorithm that runs in O(n) time and uses O(1) extra space. \n\n \nExample 1:\nInput: n = 13\nOutput: [1,10,11,12,13,2,3,4,5,6,7,8,9]\nExample 2:\nInput: n = 2\nOutput: [1,2]\n\n \nConstraints:\n\n\n\t1 <= n <= 5 * 104\n\n", "solution_py": "class Solution:\n def lexicalOrder(self, n: int) -> List[int]:\n result = []\n orderDic = {}\n for i in range(1, n + 1):\n strI = str(i)\n level = orderDic\n for char in strI:\n if char not in level:\n level[char] = {}\n level = level[char]\n self.traverse(orderDic, \"\", result)\n return result\n \n def traverse(self, dic, temp, result):\n for key in dic:\n result.append(int(temp + key))\n self.traverse(dic[key], temp + key, result)", "solution_js": "/**\n * @param {number} n\n * @return {number[]}\n */\nvar lexicalOrder = function(n) {\n const arr = [];\n \n function dfs(baseIndex) {\n if (baseIndex * 10 > n) {\n return;\n }\n \n for(let i = baseIndex * 10; i < baseIndex * 10 + 10 && i <= n; i++) {\n arr.push(i);\n dfs(i);\n }\n }\n \n let stack = [];\n \n for(let i = 1; i <= 9 && i <= n; i++) {\n arr.push(i); \n dfs(i);\n }\n \n return arr;\n};", "solution_java": "class Solution {\n\n private final TrieNode trie = new TrieNode(' ');\n\n class TrieNode{\n\n private Character digit;\n private String value;\n private boolean isWord;\n private Map children;\n\n TrieNode(Character c){\n this.digit = c;\n this.isWord = false;\n this.children = new HashMap<>();\n }\n\n void insert(String s){\n TrieNode current = this;\n for(Character c : s.toCharArray()){\n current = current.children.computeIfAbsent(c, k -> new TrieNode(c));\n }\n current.value = s;\n current.isWord = true;\n }\n\n List getWordsPreOrder(){\n return getWordsPreOrder(this);\n }\n\n private List getWordsPreOrder(TrieNode root){\n List result = new ArrayList<>();\n if(root == null){\n return result;\n }\n\n if(root.isWord){\n result.add(Integer.parseInt(root.value));\n }\n for(TrieNode node : root.children.values()){\n result.addAll(getWordsPreOrder(node));\n }\n return result;\n }\n }\n\n public List lexicalOrder(int n) {\n for(int i = 1 ; i<=n;i++){\n trie.insert(String.valueOf(i));\n }\n return trie.getWordsPreOrder();\n }\n}", "solution_c": "class Solution {\nprivate:\n void dfs(int i, int n, vector &ans){\n if(i > n) return;\n ans.push_back(i);\n for(int j = 0; j< 10; ++j) dfs(i * 10 + j, n, ans);\n }\npublic:\n vector lexicalOrder(int n) {\n vector ans;\n for(int i =1; i<10; ++i) dfs(i, n, ans);\n return ans;\n }\n};" }, { "title": "Longest Increasing Subsequence", "algo_input": "Given an integer array nums, return the length of the longest strictly increasing subsequence.\n\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\n \nExample 1:\n\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nExplanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n\n\nExample 2:\n\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\n\n\nExample 3:\n\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2500\n\t-104 <= nums[i] <= 104\n\n\n \nFollow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?\n", "solution_py": "class Solution:\n def lengthOfLIS(self, nums: list[int]) -> int:\n\n # Initialize the result\n res = []\n\n # Binary search to find the index of the smallest number in result that is greater than or equal to the target\n def binarySearch(l, r, target):\n\n nonlocal res\n\n # If the left and right pointers meet, we have found the smallest number that is greater than the target\n if l == r:\n return l\n\n # Find the mid pointer\n m = (r - l) // 2 + l\n\n # If the number at the mid pointer is equal to the target, we have found a number that is equal to the target\n if res[m] == target:\n return m\n\n # Else if the number at the mid poitner is less than the target, we search the right side\n elif res[m] < target:\n return binarySearch(m + 1, r, target)\n\n # Else, we search the left side including the number at mid pointer because it is one of the possible solution since it is greater than the target\n else:\n return binarySearch(l, m, target)\n\n # Iterate through all numbers\n for n in nums:\n\n # If the last number in the result is less than the current number\n if not res or res[-1] < n:\n\n # Append the current number to the result\n res.append(n)\n\n continue\n\n # Else, find the index of the smallest number in the result that is greater than or equal to the current number\n i = binarySearch(0, len(res) - 1, n)\n\n # Replace the current number at such index\n res[i] = n\n\n return len(res)", "solution_js": "var lengthOfLIS = function(nums) {\n let len = nums.length;\n let dp = Array.from({length: len}, v => 1);\n \n for (let i = 1 ; i < len; i++) {\n for (let j = 0; j < i; j++) {\n if (nums[i] > nums[j] && dp[i] <= dp[j]) {\n dp[i] = dp[j] + 1;\n }\n }\n }\n \n return Math.max(...dp);\n};", "solution_java": "class Solution {\n public int lengthOfLIS(int[] nums) {\n\n ArrayList lis = new ArrayList<>();\n\n for(int num:nums){\n\n int size = lis.size();\n\n if(size==0 ||size>0 && num>lis.get(size-1)){\n lis.add(num);\n }else{\n int insertIndex = bs(lis,num);\n lis.set(insertIndex,num);\n }\n }\n\n return lis.size();\n }\n\n int bs(List list, int target){\n int lo = 0;\n int hi = list.size()-1;\n\n while(lo& nums) {\n int n = nums.size();\n vectordp(n,1);\n for(int i=n-2;i>=0;i--){\n for(int j=i+1;jnums[i])dp[i]=max(dp[i],1+dp[j]);\n }\n }\n int mx=0;\n for(int i=0;i int:\n if k==0 or k==1:\n return 0\n p=1\n ini=0\n fin=0\n n=len(nums)\n c=0\n while fin=k :\n p=p//nums[ini]\n ini+=1\n\n n1=fin-ini+1\n c+=n1\n fin+=1\n return c", "solution_js": "var numSubarrayProductLessThanK = function(nums, k) {\n var used = new Array(nums.length).fill(0);\n var l, r, runsum=1;\n let ans=0;\n \n l = 0;\n r = 0;\n while( r < nums.length ) {\n if( r < nums.length && runsum * nums[r] >= k ) {\n if( r != l )\n runsum /= nums[l];\n else\n r++;\n l++;\n } else if( l <= r ) {\n runsum *= nums[r];\n r++;\n ans += (r-l);\n } else break;\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int numSubarrayProductLessThanK(int[] nums, int k) {\n\t\t//if k=0 then ans will always be zero as we have positive integers array only.\n if(k==0)\n return 0;\n \n int length = 0;\n long product = 1;\n int i = 0;\n int j = 0;\n int n = nums.length;\n int ans = 0;\n \n while(j=k){\n product/=nums[i];\n i++;\n }\n\t\t\t\t//As we have added only 1 element to the window and this element can make subarray to j-i element along with itself.\n ans+=(j-i)+1;\n\t\t\t\t//Update the current subarray length.\n length=j-i+1;\n }\n j++;\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numSubarrayProductLessThanK(vector& nums, int k) {\n int start = 0;\n long prod = 1;\n int count =0; // count of subarray prod less than k\n for(int end =0; end< nums.size(); end++){\n prod *= nums[end];\n \n while(prod >= k && start < nums.size()){\n prod = prod/nums[start];// divide product by nums at start pointer t reduce the prod\n start++;//move start pointer because no longer nums at start can give us prod < k\n }\n if(prod < k)\n count += end - start +1;\n }\n return count;\n }\n};" }, { "title": "Count Odd Numbers in an Interval Range", "algo_input": "Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\n\n \nExample 1:\n\nInput: low = 3, high = 7\nOutput: 3\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\n\nExample 2:\n\nInput: low = 8, high = 10\nOutput: 1\nExplanation: The odd numbers between 8 and 10 are [9].\n\n \nConstraints:\n\n\n\t0 <= low <= high <= 10^9\n", "solution_py": "class Solution:\n def countOdds(self, low: int, high: int) -> int: \n total_nums = high - low\n \n answer = total_nums // 2\n \n if low % 2 == 1 and high % 2 == 1:\n return answer + 1\n \n if low % 2 == 1:\n answer = answer + 1\n \n if high % 2 == 1:\n answer = answer + 1\n \n return answer", "solution_js": "var countOdds = function(low, high) {\n let total = 0;\n for (let i = low; i <= high; i++) {\n if (i % 2 !== 0) {\n total++;\n }\n }\n return total;\n};", "solution_java": "class Solution {\n public int countOdds(int low, int high) {\n if(low%2==0 && high%2==0){\n return (high-low)/2;\n }\n return (high-low)/2+1;\n }\n}", "solution_c": "class Solution {\npublic:\n int countOdds(int low, int high) {\n if (low%2 == 0 && high%2 == 0 ){\n return (high - low)/2;\n }\n else{\n return (high - low)/2 + 1;\n }\n\n }\n};" }, { "title": "2 Keys Keyboard", "algo_input": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:\n\n\n\tCopy All: You can copy all the characters present on the screen (a partial copy is not allowed).\n\tPaste: You can paste the characters which are copied last time.\n\n\nGiven an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 3\nExplanation: Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\n", "solution_py": "class Solution:\n def minSteps(self, n: int) -> int: \n # at every step we can copy or paste\n # paste -> we need to know the current clipboard content (count)\n # copy -> set clipboard count to current screen count (we should consider it, if the last operation was paste)\n \n memo = {}\n \n def dfs(clipboard_count, screen_count):\n if (clipboard_count, screen_count) in memo: \n return memo[(clipboard_count, screen_count)]\n \n # we reached n, this is a valid option\n if screen_count == n: return 0\n \n # we passed n, not a valid option\n if screen_count > n: return float('inf') \n \n # paste or copy\n copy_opt = paste_opt = float('inf')\n \n # we should only paste if clipboard is not empty\n if clipboard_count > 0:\n paste_opt = dfs(clipboard_count, screen_count + clipboard_count) \n \n # we should consider copy only if the last operation was paste\n if screen_count > clipboard_count:\n copy_opt = dfs(screen_count, screen_count) \n \n # save to memo\n memo[(clipboard_count, screen_count)] = 1 + min(paste_opt, copy_opt) \n return memo[(clipboard_count, screen_count)]\n \n return dfs(0, 1)\n ", "solution_js": "var minSteps = function(n) {\n\tlet result = 0;\n\n\tfor (let index = 2; index <= n; index++) {\n\t\twhile (n % index === 0) {\n\t\t\tresult += index;\n\t\t\tn /= index;\n\t\t}\n\t}\n\treturn result;\n};", "solution_java": "class Solution {\n public int minSteps(int n) {\n int rem = n-1, copied = 0, ans = 0, onScreen = 1;\n \n while(rem>0){\n if(rem % onScreen == 0){\n ans++; // copy operation\n copied = onScreen; \n }\n rem-=copied;\n ans++; // paste operation\n onScreen = n-rem; // no. of characters on screen currently that can be copied in next copy operation\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n//See the solution for this explanation \n int byPrimeFactorization(int n) {\n if(n == 1)\n return 0;\n if(n == 2)\n return 2;\n int factor = 2, ans = 0;\n while(n > 1) {\n while(n % factor == 0) {\n ans += factor;\n n /= factor;\n }\n factor++;\n }\n return ans;\n }\n \n int byDp(int n) {\n vector dp(1001, INT_MAX);\n dp[0] = dp[1] = 0;\n dp[2] = 2, dp[3] = 3;\n for(int i = 4; i <= n; i++) {\n dp[i] = i; //maximum number of operations required will be i\n for(int j = 2; j <= i / 2; j++) { //we copy and paste j A's till we have i A's\n int x = i - j; //we already have j A's in our stream, so remaining = i - j\n if(x % j == 0) { //if remaining number of A's is a multiple of J\n dp[i] = min(dp[i], dp[j] + 1 + (x / j)); //1 operation to copy, x / j to paste, dp[j] for getting j A's\n }\n }\n }\n return dp[n];\n }\n \n int minSteps(int n) {\n return byPrimeFactorization(n);\n }\n};" }, { "title": "Find Largest Value in Each Tree Row", "algo_input": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).\n\n \nExample 1:\n\nInput: root = [1,3,2,5,3,null,9]\nOutput: [1,3,9]\n\n\nExample 2:\n\nInput: root = [1,2,3]\nOutput: [1,3]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [0, 104].\n\t-231 <= Node.val <= 231 - 1\n\n", "solution_py": "class Solution(object):\n def largestValues(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n ans=[]\n q=[]\n q.append(root)\n while q:\n s=len(q)\n t=[]\n for i in range(s):\n n=q.pop(0)\n t.append(n.val)\n if n.left:\n q.append(n.left)\n if n.right:\n q.append(n.right)\n ans.append(max(t))\n return ans", "solution_js": "var largestValues = function(root) {\n if(!root) return [];\n \n const op = [];\n const Q = [[root, 1]];\n while(Q.length) {\n const [r, l] = Q.shift();\n \n if(op.length < l) op.push(-Infinity);\n op[l-1] = Math.max(op[l-1], r.val);\n \n if(r.left) Q.push([r.left, l + 1]);\n if(r.right) Q.push([r.right, l + 1]);\n }\n return op;\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 private List li=new ArrayList<>();\n\n public List largestValues(TreeNode root) {\n\n if(root==null) return li; //if root is NULL\n\n //using bfs(level-order)\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty()){\n int size=q.size();\n int res=Integer.MIN_VALUE;\n while(size-->0){\n TreeNode temp=q.poll();\n if(temp.left!=null) q.add(temp.left);\n if(temp.right!=null) q.add(temp.right);\n res =Math.max(res,temp.val); //comparing every node in each level to get max\n }\n li.add(res); //adding each level Max value to the list\n }\n return li;\n }\n}", "solution_c": "class Solution {\npublic:\n vectorres;\n vector largestValues(TreeNode* root) {\n if(!root) return {};\n if(!root->left && !root->right) return {root->val};\n TreeNode*temp;\n int mx = INT_MIN;\n queueq;\n q.push(root);\n\n while(!q.empty()){\n int sz = q.size();\n while(sz--){\n temp = q.front();\n if(temp->val > mx) mx = temp->val;\n q.pop();\n if(temp->left) q.push(temp->left);\n if(temp->right) q.push(temp->right);\n }\n res.push_back(mx);\n mx = INT_MIN;\n }\n return res;\n }\n};" }, { "title": "Finding MK Average", "algo_input": "You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\n\nThe MKAverage can be calculated using these steps:\n\n\n\tIf the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.\n\tRemove the smallest k elements and the largest k elements from the container.\n\tCalculate the average value for the rest of the elements rounded down to the nearest integer.\n\n\nImplement the MKAverage class:\n\n\n\tMKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.\n\tvoid addElement(int num) Inserts a new element num into the stream.\n\tint calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n\n\n \nExample 1:\n\nInput\n[\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\nOutput\n[null, null, null, -1, null, 3, null, null, null, 5]\n\nExplanation\nMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be [3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be [5].\n // The average of [5] equals 5/1 = 5, return 5\n\n\n \nConstraints:\n\n\n\t3 <= m <= 105\n\t1 <= k*2 < m\n\t1 <= num <= 105\n\tAt most 105 calls will be made to addElement and calculateMKAverage.\n\n", "solution_py": "from sortedcontainers import SortedList\n\nclass MKAverage:\n\n MAX_NUM = 10 ** 5\n def __init__(self, m: int, k: int):\n \n self.m = m\n self.k = k\n \n # sorted list\n self.sl = SortedList([0] * m)\n\t\t# sum of k smallest elements\n self.sum_k = 0\n\t\t# sum of m - k smallest elements\n self.sum_m_k = 0\n \n # queue for the last M elements if the stream\n self.q = deque([0] * m)\n \n def addElement(self, num: int) -> None:\n # Time: O(logm)\n\t\t\n m, k, q, sl = self.m, self.k, self.q, self.sl \n \n # update q\n q.append(num)\n old = q.popleft()\n \n # remove the old num\n r = sl.bisect_right(old)\n\t\t# maintain sum_k\n if r <= k:\n self.sum_k -= old\n self.sum_k += sl[k]\n\t\t# maintain sum_m_k\n if r <= m - k:\n self.sum_m_k -= old\n self.sum_m_k += sl[m-k]\n # remove the old num\n sl.remove(old)\n \n # add the new num\n r = sl.bisect_right(num)\n if r < k:\n self.sum_k -= sl[k-1]\n self.sum_k += num\n if r < m - k:\n self.sum_m_k -= sl[m - k - 1]\n self.sum_m_k += num\n \n sl.add(num)\n \n return\n\n def calculateMKAverage(self) -> int:\n\t\t# Time: O(1)\n if self.sl[0] == 0:\n return -1\n return (self.sum_m_k - self.sum_k) // (self.m - self.k * 2)", "solution_js": "class ArraySegTree{\n // Array to perfrom operations on, range query operation, PointUpdate operation\n constructor(A,op=(a,b)=>a+b,upOp=(a,b)=>a+b,opSentinel=0){\n this.n=A.length,this.t=[...Array(4*this.n+1)],this.op=op,this.upOp=upOp,this.opSentinel=opSentinel\n //root's idx =1\n this.build(A,1,0,this.n-1)\n }\n left=x=>this.t[2*x];right=x=>this.t[2*x+1]\n build(A,idx,left,right){\n if(left==right)\n return this.t[idx]=A[left]\n let mid=(left+right)>>1\n this.build(A,2*idx,left,mid) //go left\n this.build(A,2*idx+1,mid+1,right) //go right\n this.t[idx]=this.op(this.left(idx),this.right(idx)) //merge\n }\n //just specify l,r on actual queries\n //Here queries use the actul indices of the starting array A, so rangeQuery(0,n-1) returns the whole array\n rangeQuery=(l,r,tl=0,tr=this.n-1,idx=1)=>{\n if(l>r)\n return this.opSentinel\n if(l===tl&&r===tr)\n return this.t[idx]\n let mid=(tl+tr)>>1\n return this.op(\n this.rangeQuery(l,Math.min(r,mid),tl,mid,idx*2),\n this.rangeQuery(Math.max(l,mid+1),r,mid+1,tr,idx*2+1)\n )\n }\n //just specify arrIdx,newVal on actual pointUpdates\n pointUpdate=(arrIdx,newVal,tl=0,tr=this.n-1,idx=1)=>{\n if(tl==tr)\n return this.t[idx]=this.upOp(this.t[idx],newVal)\n let mid=(tl+tr)>>1\n if(arrIdx<=mid)\n this.pointUpdate(arrIdx,newVal,tl,mid,2*idx)\n else\n this.pointUpdate(arrIdx,newVal,mid+1,tr,2*idx+1)\n this.t[idx]=this.op(this.left(idx),this.right(idx))\n }\n seachPrefixIndex=(x,start=0,end=this.n-1)=>{\n let s=this.rangeQuery(start,end)\n if(s>1,left=this.rangeQuery(start,mid)\n if( left>=x)\n return this.seachPrefixIndex(x,start,mid)\n else\n return this.seachPrefixIndex(x-left,mid+1,end)\n }\n}\n\nvar MKAverage = function(m, k) {\n this.A=[],this.m=m,this.k=k,this.div=m-2*k\n this.S1=new ArraySegTree([...Array(1e5+2)].map(d=>0))//indices\n this.S2=new ArraySegTree([...Array(1e5+2)].map(d=>0))//sums\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nMKAverage.prototype.addElement = function(num) {\n this.A.push(num)\n this.S1.pointUpdate(num,1)\n this.S2.pointUpdate(num,num)\n if(this.A.length>this.m){\n let z=this.A.shift()\n this.S1.pointUpdate(z,-1)\n this.S2.pointUpdate(z,-z)\n }\n};\n\n/**\n * @return {number}\n */\nMKAverage.prototype.calculateMKAverage = function() {\n if(this.A.length>0\n};", "solution_java": "class MKAverage {\n class Node implements Comparable {\n int val;\n int time;\n \n Node(int val, int time) {\n this.val = val;\n this.time = time;\n }\n \n @Override\n public int compareTo(Node other) {\n return (this.val != other.val ? this.val - other.val \n : this.time - other.time);\n }\n }\n \n private TreeSet set = new TreeSet<>(); // natural order\n private Deque queue = new LinkedList<>();\n private Node kLeft;\n private Node kRight;\n \n private int m, k;\n \n private int time = 0;\n private int sum = 0;\n\n public MKAverage(int m, int k) {\n this.m = m;\n this.k = k;\n }\n \n public void addElement(int num) {\n Node node = new Node(num, time++);\n\n addNode(node);\n removeNode();\n \n if (time == m) init();\n }\n \n private void init() {\n int i = 0;\n for (Node node : set) {\n if (i < k-1);\n else if (i == k-1) kLeft = node;\n else if (i < m-k) sum += node.val;\n else if (i == m-k) {\n kRight = node;\n return;\n }\n \n i++;\n }\n return;\n }\n \n private void addNode(Node node) {\n queue.offerLast(node);\n set.add(node);\n \n if (queue.size() <= m) return;\n \n if (node.compareTo(kLeft) < 0) {\n sum += kLeft.val;\n kLeft = set.lower(kLeft);\n } else if (node.compareTo(kRight) > 0) {\n sum += kRight.val;\n kRight = set.higher(kRight);\n } else {\n sum += node.val;\n } \n }\n \n private void removeNode() {\n if (queue.size() <= m) return;\n \n Node node = queue.pollFirst();\n \n if (node.compareTo(kLeft) <= 0) {\n kLeft = set.higher(kLeft);\n sum -= kLeft.val;\n } else if (node.compareTo(kRight) >= 0) {\n kRight = set.lower(kRight);\n sum -= kRight.val;\n } else {\n sum -= node.val;\n }\n \n set.remove(node);\n }\n \n public int calculateMKAverage() {\n return (queue.size() < m ? -1 : sum / (m - 2 * k));\n }\n}", "solution_c": "/* \n Time: addElement: O(logm) | calculateMKAverage: O(1)\n Space: O(m)\n Tag: TreeMap, Sorting, Queue\n Difficulty: H\n*/\n\nclass MKAverage {\n map left, middle, right;\n queue q;\n int sizeofLeft, sizeofMiddle, sizeofRight;\n int k;\n long long mkSum;\n int m;\n\n void addToSet1(int num) {\n left[num]++;\n sizeofLeft++;\n }\n\n void deleteFromSet1(int num) {\n left[num]--;\n if (left[num] == 0) left.erase(num);\n sizeofLeft--;\n }\n\n void addToSet2(int num) {\n middle[num]++;\n sizeofMiddle++;\n mkSum += num;\n }\n\n void deleteFromSet2(int num) {\n middle[num]--;\n if (middle[num] == 0) middle.erase(num);\n sizeofMiddle--;\n mkSum -= num;\n }\n\n void addToSet3(int num) {\n right[num]++;\n sizeofRight++;\n }\n\n void deleteFromSet3(int num) {\n right[num]--;\n if (right[num] == 0) right.erase(num);\n sizeofRight--;\n }\n\npublic:\n MKAverage(int m, int k) {\n sizeofLeft = 0, sizeofMiddle = 0, sizeofRight = 0;\n mkSum = 0;\n this->k = k;\n this->m = m;\n }\n\n void addElement(int num) {\n if (sizeofLeft < k) {\n addToSet1(num);\n q.push(num);\n } else if (sizeofMiddle < (m - (2 * k))) {\n int lastEle = prev(left.end())->first;\n if (num >= lastEle) {\n addToSet2(num);\n } else {\n deleteFromSet1(lastEle);\n addToSet1(num);\n addToSet2(lastEle);\n }\n q.push(num);\n } else if (sizeofRight < k) {\n int last1 = prev(left.end())->first;\n int last2 = prev(middle.end())->first;\n if (num >= last1 && num >= last2) {\n addToSet3(num);\n } else if (num >= last1 && num < last2) {\n deleteFromSet2(last2);\n addToSet2(num);\n addToSet3(last2);\n } else {\n deleteFromSet2(last2);\n addToSet3(last2);\n deleteFromSet1(last1);\n addToSet2(last1);\n addToSet1(num);\n }\n q.push(num);\n } else {\n int toErase = q.front();\n q.pop();\n int first3 = right.begin()->first;\n int first2 = middle.begin()->first;\n int first1 = left.begin()->first;\n\n if (toErase >= first3) {\n deleteFromSet3(toErase);\n } else if (toErase >= first2) {\n deleteFromSet3(first3);\n deleteFromSet2(toErase);\n addToSet2(first3);\n } else {\n deleteFromSet3(first3);\n deleteFromSet2(first2);\n deleteFromSet1(toErase);\n addToSet1(first2);\n addToSet2(first3);\n }\n addElement(num);\n }\n }\n\n int calculateMKAverage() {\n if (q.size() < m) return -1;\n return mkSum / (m - (2 * k));\n }\n};" }, { "title": "Rotate Image", "algo_input": "You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n\nYou have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.\n\n \nExample 1:\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[7,4,1],[8,5,2],[9,6,3]]\n\n\nExample 2:\n\nInput: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n\n\n \nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t1 <= n <= 20\n\t-1000 <= matrix[i][j] <= 1000\n\n", "solution_py": "class Solution:\n \n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n # transpose \n size = len(matrix)\n for i in range(size):\n for j in range(i+1, size):\n matrix[j][i],matrix[i][j] = matrix[i][j],matrix[j][i]\n \n print(matrix)\n \n # reverse row\n for row in range(len(matrix)):\n matrix[row] = matrix[row][::-1]\n \n print(matrix)", "solution_js": "/**\n * @param {number[][]} matrix\n * @return {void} Do not return anything, modify matrix in-place instead.\n */\nvar rotate = function(matrix) {\n let m = matrix.length;\n let n = matrix[0].length;\n \n for (let i = m - 1; i >= 0; i--) {\n for (let j = 0; j < m; j++) {\n matrix[j].push(matrix[i].shift());\n }\n }\n};", "solution_java": "class Solution {\n public void swap(int[][] matrix, int n1, int m1, int n2, int m2) {\n int a = matrix[n1][m1];\n int temp = matrix[n2][m2];\n matrix[n2][m2] = a;\n matrix[n1][m1] = temp;\n }\n public void rotate(int[][] matrix) {\n int n = matrix.length;\n for (int i = 0; i < n/2; i++) {\n for (int j = 0; j < n; j++) {\n swap(matrix, i,j, n-i-1, j);\n }\n }\n for (int i = n-1; i >= 0; i--) {\n for (int j = 0; j < i; j++) {\n swap(matrix, i,j, j, i);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void rotate(vector>& matrix) {\n int row = matrix.size();\n for(int i=0;i 1000):\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n continue\n while left <= len(indexes)-2 and transactions[indexes[left]].time < t.time - 60: # O(60) time\n left += 1\n while right <= len(indexes)-2 and transactions[indexes[right+1]].time <= t.time + 60: # O(60) time\n right += 1\n for i in range(left,right+1): # O(120) time\n if transactions[indexes[i]].city != t.city:\n res.append(\"{},{},{},{}\".format(t.name, t.time, t.amount, t.city))\n break\n\n return res", "solution_js": "var invalidTransactions = function(transactions) {\n const invalid = new Uint8Array(transactions.length).fill(false);\n\n for(let i = 0; i < transactions.length; i++){\n const [name, time, amount, city] = transactions[i].split(',');\n\n if(+amount > 1000) invalid[i] = true;\n\n for(let j = i + 1; j < transactions.length; j++){\n const [name1, time1, amount1, city1] = transactions[j].split(',');\n\n if(Math.abs(+time - +time1) <= 60 && name === name1 && city !== city1){\n invalid[i] = true;\n invalid[j] = true;\n }\n }\n }\n\n return invalid.reduce((acc, val, index) => {\n if(val) acc.push(transactions[index])\n return acc;\n }, [])\n};", "solution_java": "class Solution {\n public List invalidTransactions(String[] transactions) {\n Map> nameToTransaction = new HashMap<>();\n for (int i = 0; i < transactions.length; i++) {\n Transaction t = new Transaction(transactions[i], i);\n nameToTransaction.putIfAbsent(t.name, new ArrayList<>());\n nameToTransaction.get(t.name).add(t);\n }\n List invalid = new ArrayList<>();\n for (List list : nameToTransaction.values()) {\n for (Transaction t : list) {\n if (t.isInvalidAmount()) invalid.add(transactions[t.id]);\n else {\n for (Transaction otherT : list) {\n if (t.isInvalidCity(otherT)) {\n invalid.add(transactions[t.id]);\n break;\n }\n }\n }\n }\n }\n return invalid;\n }\n}\n\nclass Transaction {\n String name, city;\n int time, amount, id;\n\n Transaction(String s, int id) {\n this.id = id;\n String[] split = s.split(\",\");\n name = split[0];\n time = Integer.parseInt(split[1]);\n amount = Integer.parseInt(split[2]);\n city = split[3];\n }\n\n boolean isInvalidAmount() {\n return this.amount > 1000;\n }\n\n boolean isInvalidCity(Transaction t) {\n return !city.equals(t.city) && Math.abs(t.time - time) <= 60;\n }\n}", "solution_c": "class Solution {\npublic:\n /*\n this question is absolutely frustrating 🙂\n */\n \n /*\n method to split string\n */\n vector split(string s){\n string t=\"\";\n vector v;\n for(int i=0;i>mp){\n for(auto x:mp[s]){\n vectorout=split(x);\n int val1=stoi(out[1]);\n int val2=stoi(time);\n if(out[3]!=city and abs(val2-val1)<=60){\n return true;\n }\n }\n return false;\n }\n \n \n vector invalidTransactions(vector& transactions) {\n vector res;/* stores the result */\n \n map>mp;/* to search for only that person*/\n \n int n=transactions.size();\n \n vector>v(n,vector(4));/*ith v stores info about ith transaction*/\n int c=0;\n \n for(auto x:transactions){\n vector out=split(x);\n v[c]=out;\n mp[out[0]].emplace_back(x);\n c+=1;\n }\n \n for(int i=0;i1000){\n /*\n check for first condition\n */\n res.emplace_back(transactions[i]);\n }else{\n /*\n checks for second condition.\n */\n if(check(v[i][0],v[i][1],v[i][3],mp)){\n res.emplace_back(transactions[i]);\n }\n }\n \n }\n \n return res;\n }\n};" }, { "title": "Count Nodes Equal to Average of Subtree", "algo_input": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.\n\nNote:\n\n\n\tThe average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\n\tA subtree of root is a tree consisting of root and all of its descendants.\n\n\n \nExample 1:\n\nInput: root = [4,8,5,0,1,null,6]\nOutput: 5\nExplanation: \nFor the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.\n\n\nExample 2:\n\nInput: root = [1]\nOutput: 1\nExplanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 <= Node.val <= 1000\n\n", "solution_py": "class Solution:\n def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n \n \n def calculate_average(root):\n if root:\n self.summ+=root.val\n self.nodecount+=1\n calculate_average(root.left)\n calculate_average(root.right)\n \n \n def calculate_for_each_node(root):\n if root:\n self.summ = 0\n self.nodecount = 0\n calculate_average(root)\n if ((self.summ)//(self.nodecount)) == root.val:\n self.count+=1 \n calculate_for_each_node(root.left)\n calculate_for_each_node(root.right)\n \n \n self.count = 0\n calculate_for_each_node(root) \n return self.count", "solution_js": "var averageOfSubtree = function(root) {\n let result = 0;\n \n const traverse = node => {\n if (!node) return [0, 0];\n \n const [leftSum, leftCount] = traverse(node.left);\n const [rightSum, rightCount] = traverse(node.right);\n \n const currSum = node.val + leftSum + rightSum;\n const currCount = 1 + leftCount + rightCount;\n \n if (Math.floor(currSum / currCount) === node.val) result++;\n \n return [currSum, currCount];\n };\n \n traverse(root);\n return result;\n};", "solution_java": "class Solution {\n int res = 0;\n public int averageOfSubtree(TreeNode root) {\n dfs(root);\n return res;\n }\n \n private int[] dfs(TreeNode node) {\n if(node == null) {\n return new int[] {0,0};\n }\n \n int[] left = dfs(node.left);\n int[] right = dfs(node.right);\n \n int currSum = left[0] + right[0] + node.val;\n int currCount = left[1] + right[1] + 1;\n \n if(currSum / currCount == node.val) {\n res++;\n }\n \n return new int[] {currSum, currCount};\n }\n}", "solution_c": "class Solution {\npublic:\n pair func(TreeNode* root,int &ans){\n if(!root)return {0,0};\n auto p1=func(root->left,ans);\n auto p2=func(root->right,ans);\n int avg=(root->val+p1.first+p2.first)/(p1.second+p2.second+1);\n if(avg==root->val)ans++;\n return {root->val+p1.first+p2.first,p1.second+p2.second+1};\n }\n int averageOfSubtree(TreeNode* root) {\n int ans=0;\n func(root,ans);\n return ans;\n }\n};" }, { "title": "Insertion Sort List", "algo_input": "Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.\n\nThe steps of the insertion sort algorithm:\n\n\n\tInsertion sort iterates, consuming one input element each repetition and growing a sorted output list.\n\tAt each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.\n\tIt repeats until no input elements remain.\n\n\nThe following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.\n\n \nExample 1:\n\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\n\n\nExample 2:\n\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 5000].\n\t-5000 <= Node.val <= 5000\n\n", "solution_py": "/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction insertionSortList(head: ListNode | null): ListNode | null {\n if (!head) return null\n if (!head.next) return head\n\n let output = head\n let curr = head.next\n\n head.next = null\n\n while (curr) {\n const next = curr.next\n const insertion = curr\n\n output = insert(output, insertion)\n curr = next as ListNode\n }\n\n return output\n}\n\nfunction insert(head: ListNode, other: ListNode) {\n let curr = head\n const val = other.val\n\n if (val <= head.val) {\n other.next = head\n return other\n }\n\n while (curr) {\n if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) {\n other.next = curr.next\n curr.next = other\n\n return head\n }\n\n curr = curr.next as ListNode\n }\n\n return head\n}", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar insertionSortList = function(head) {\n let ptr = head;\n \n while(ptr.next !== null){\n if(ptr.val <= ptr.next.val)\n ptr = ptr.next;\n else{\n let temp = ptr.next;\n ptr.next = ptr.next.next;\n \n \n if(temp.val < head.val)\n {\n temp.next = head;\n head = temp;\n }\n \n else{\n let ptr2 = head;\n while(ptr2.next != null && temp.val >= ptr2.next.val){\n ptr2 = ptr2.next;\n }\n temp.next = ptr2.next;\n ptr2.next = temp;\n }\n }\n }\n return head;\n};", "solution_java": "class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode cur = head;\n ListNode temp = new ListNode(-5001);\n ListNode prev = temp;\n while(cur != null){\n ListNode nxt = cur.next;\n if(prev.val >= cur.val)\n prev = temp;\n while(prev.next != null && prev.next.val < cur.val)\n prev = prev.next;\n cur.next = prev.next;\n prev.next = cur;\n cur = nxt;\n }\n return temp.next;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n ListNode *prev=head,*cur=head->next;\n while(cur){\n ListNode *tmp=head,*pt=NULL;\n while(tmp!=cur and tmp->val < cur->val){\n pt=tmp;\n tmp=tmp->next;\n }\n if(tmp==cur){\n prev=prev->next;\n cur=cur->next;\n continue;\n }\n prev->next=cur->next;\n if(!pt){\n cur->next=head;\n head=cur;\n }\n else{\n pt->next=cur;\n cur->next=tmp;\n }\n cur=prev->next;\n }\n return head;\n }\n};" }, { "title": "Find All Anagrams in a String", "algo_input": "Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\n \nExample 1:\n\nInput: s = \"cbaebabacd\", p = \"abc\"\nOutput: [0,6]\nExplanation:\nThe substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n\n\nExample 2:\n\nInput: s = \"abab\", p = \"ab\"\nOutput: [0,1,2]\nExplanation:\nThe substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length, p.length <= 3 * 104\n\ts and p consist of lowercase English letters.\n\n", "solution_py": "from collections import Counter\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n l='abcdefghijklmnopqrstuvwxyz'\n if len(p)>len(s):\n return []\n d={}\n for x in l:\n d[x]=0\n d1=dict(d)\n d2=dict(d)\n for x in range(len(p)):\n d1[s[x]]+=1\n d2[p[x]]+=1\n l1=[]\n if d1==d2:\n l1=[0]\n #print(d1)\n for x in range(len(p),len(s)):\n d1[s[x]]+=1\n d1[s[x-len(p)]]-=1\n if d1==d2:\n l1.append(x-len(p)+1)\n return l1", "solution_js": "var findAnagrams = function(s, p) {\n\n function compareMaps(map1, map2) {\n var testVal;\n if (map1.size !== map2.size) {\n return false;\n }\n for (var [key, val] of map1) {\n testVal = map2.get(key);\n // in cases of an undefined value, make sure the key\n // actually exists on the object so there are no false positives\n if (testVal !== val || (testVal === undefined && !map2.has(key))) {\n return false;\n }\n }\n return true;\n }\n\n let p_map=new Map()\n let s_map=new Map()\n let res=[]\n let pn=p.length\n let sn=s.length\n for(let i in p){\n p_map.set(p[i],p_map.get(p[i])?p_map.get(p[i])+1:1)\n s_map.set(s[i],s_map.get(s[i])?s_map.get(s[i])+1:1)\n }\n let l=0\n if(compareMaps(s_map,p_map)) res.push(l)\n for(let r=pn;r findAnagrams(String s, String p) {\n int fullMatchCount = p.length();\n Map anagramMap = new HashMap<>();\n \n for (Character c : p.toCharArray())\n anagramMap.put(c, anagramMap.getOrDefault(c, 0) + 1);\n \n List result = new ArrayList<>();\n int left = 0, right = 0, currentMatchCount = 0;\n Map currentAnagramMap = new HashMap<>();\n while (right < s.length()) {\n char c = s.charAt(right);\n if (anagramMap.get(c) == null) {\n currentAnagramMap = new HashMap<>();\n right++;\n left = right;\n currentMatchCount = 0;\n continue;\n }\n currentAnagramMap.put(c, currentAnagramMap.getOrDefault(c, 0) + 1);\n currentMatchCount++;\n \n if (currentAnagramMap.get(c) > anagramMap.get(c)) {\n char leftC = s.charAt(left);\n while (leftC != c) {\n currentAnagramMap.put(leftC, currentAnagramMap.get(leftC) - 1);\n left++;\n leftC = s.charAt(left);\n currentMatchCount--;\n }\n left++;\n currentAnagramMap.put(c, currentAnagramMap.get(c) - 1);\n currentMatchCount--;\n }\n \n if (currentMatchCount == fullMatchCount)\n result.add(left);\n \n right++;\n }\n return result;\n }\n}", "solution_c": "//easy to understand\nclass Solution {\npublic:\n bool allZeros(vector &count) {\n for (int i = 0; i < 26; i++) {\n if (count[i] != 0) \n return false;\n }\n return true;\n }\n vector findAnagrams(string s, string p) {\n string s1 = p, s2 = s;\n int n = s1.length(); \n int m = s2.length();\n if (n > m) \n return {};\n\n vector ans;\n vector count(26, 0);\n\n for (int i = 0; i < n; i++) {\n count[s1[i] - 'a']++;\n count[s2[i] - 'a']--;\n }\n //it will check for s1 = abcd, s2 = cdab\n if (allZeros(count)) {\n ans.push_back(0);\n }\n\n for (int i = n; i < m; i++) {\n count[s2[i] - 'a']--;\n count[s2[i - n] - 'a']++;\n if (allZeros(count)) \n ans.push_back(i-n+1);\n }\n\n return ans;\n }\n};" }, { "title": "Search a 2D Matrix", "algo_input": "Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:\n\n\n\tIntegers in each row are sorted from left to right.\n\tThe first integer of each row is greater than the last integer of the previous row.\n\n\n \nExample 1:\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput: true\n\n\nExample 2:\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput: false\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 100\n\t-104 <= matrix[i][j], target <= 104\n\n", "solution_py": "class Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n left=0\n right=len(matrix)-1\n while left <= right:\n mid=(left+right)//2\n if matrix[mid][0] < target:\n left = mid+1\n elif matrix[mid][0] >target:\n right= mid-1\n else:\n return True\n left1=0\n right1=len(matrix[right])-1\n while left1 <= right1:\n mid=(left1+right1)//2\n if matrix[right][mid] < target:\n left1 = mid+1\n elif matrix[right][mid] >target:\n right1= mid-1\n else:\n return True\n return False", "solution_js": "var searchMatrix = function(matrix, target) {\n let matCopy = [...matrix];\n let leftIndex = 0;\n let rightIndex = matrix.length - 1;\n\n let mid = Math.ceil((matrix.length - 1) / 2);\n\n let eachMatrixLength = matrix[0].length;\n \n if (matrix[mid].includes(target) === true) {\n return true;\n } else if (matrix.length == 1) {\n return false;\n }\n\n if (matrix[mid][eachMatrixLength - 1] > target) {\n rightIndex = mid - 1;\n matCopy.splice(-mid);\n } else {\n leftIndex = mid + 1;\n matCopy.splice(0, mid);\n }\n\n return searchMatrix(matCopy, target);\n \n};", "solution_java": "class Solution {\n public boolean searchMatrix(int[][] matrix, int target) {\n if (target < matrix[0][0]) {\n return false;\n }\n for (int i = 0; i < matrix.length; i++) {\n if (matrix[i][0] > target | i == matrix.length - 1) {\n if (matrix[i][0] > target) {\n i--;\n }\n for (int j = 0; j < matrix[i].length; j++) {\n if (matrix[i][j] == target) {\n return true;\n }\n }\n return false;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool searchMatrix(vector>& matrix, int target) {\n for(int i = 0; i < matrix.size(); i ++) {\n if(matrix[i][0] > target) return false;\n for(int j = 0; j < matrix[i].size(); j ++) {\n if(matrix[i][j] == target) return true;\n else if(matrix[i][j] > target) break;\n }\n }\n return false;\n }\n};" }, { "title": "Throne Inheritance", "algo_input": "A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.\n\nThe kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.\n\nSuccessor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder\n\n\nFor example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.\n\n\n\tIn the beginning, curOrder will be [\"king\"].\n\tCalling Successor(king, curOrder) will return Alice, so we append to curOrder to get [\"king\", \"Alice\"].\n\tCalling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\"].\n\tCalling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n\tCalling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n\n\nUsing the above function, we can always obtain a unique order of inheritance.\n\nImplement the ThroneInheritance class:\n\n\n\tThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.\n\tvoid birth(string parentName, string childName) Indicates that parentName gave birth to childName.\n\tvoid death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.\n\tstring[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.\n\n\n \nExample 1:\n\nInput\n[\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n[[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]\nOutput\n[null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]\n\nExplanation\nThroneInheritance t= new ThroneInheritance(\"king\"); // order: king\nt.birth(\"king\", \"andy\"); // order: king > andy\nt.birth(\"king\", \"bob\"); // order: king > andy > bob\nt.birth(\"king\", \"catherine\"); // order: king > andy > bob > catherine\nt.birth(\"andy\", \"matthew\"); // order: king > andy > matthew > bob > catherine\nt.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob > alex > catherine\nt.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\nt.death(\"bob\"); // order: king > andy > matthew > bob > alex > asha > catherine\nt.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]\n\n\n \nConstraints:\n\n\n\t1 <= kingName.length, parentName.length, childName.length, name.length <= 15\n\tkingName, parentName, childName, and name consist of lowercase English letters only.\n\tAll arguments childName and kingName are distinct.\n\tAll name arguments of death will be passed to either the constructor or as childName to birth first.\n\tFor each call to birth(parentName, childName), it is guaranteed that parentName is alive.\n\tAt most 105 calls will be made to birth and death.\n\tAt most 10 calls will be made to getInheritanceOrder.\n\n", "solution_py": "class ThroneInheritance:\n\n def __init__(self, kingName: str):\n # Taking kingName as root\n self.root = kingName\n\n # notDead will hold all the people who are alive and their level number\n self.alive = {}\n self.alive[kingName] = 0\n\n # hold edges existing in our graph\n self.edges = {self.root:[]}\n\n def birth(self, parentName: str, childName: str) -> None:\n # birth --> new child so update alive\n self.alive[childName] = self.alive[parentName]+1\n\n # add parent to child edges in the edges dictionary\n if parentName in self.edges:\n self.edges[parentName].append(childName)\n if childName not in self.edges:\n self.edges[childName] = []\n else:\n if childName not in self.edges:\n self.edges[childName] = []\n self.edges[parentName] = [childName]\n\n def death(self, name: str) -> None:\n # removing the dead people from alive map\n del self.alive[name]\n\n def getInheritanceOrder(self) -> List[str]:\n\n hierarchy = []\n def dfs(cur,parent=-1):\n nonlocal hierarchy\n\n # current person available in alive then only add in hierarchy\n if cur in self.alive:\n hierarchy.append(cur)\n\n # traverse all the children of current node\n for i in self.edges[cur]:\n if i!=parent:\n dfs(i,cur)\n dfs(self.root)\n return hierarchy", "solution_js": "var bloodList = function(name, parent = null) {\n return {\n name,\n children: []\n };\n}\n\nvar ThroneInheritance = function(kingName) {\n this.nameMap = new Map();\n this.nameMap.set(kingName, bloodList(kingName));\n this.king = kingName;\n this.deadList = new Set();\n};\n\n/**\n * @param {string} parentName\n * @param {string} childName\n * @return {void}\n */\nThroneInheritance.prototype.birth = function(parentName, childName) {\n const parent = this.nameMap.get(parentName);\n const childId = bloodList(childName, parent);\n this.nameMap.set(childName, childId);\n parent.children.push(childId);\n};\n\n/**\n * @param {string} name\n * @return {void}\n */\nThroneInheritance.prototype.death = function(name) {\n this.deadList.add(name);\n};\n\n/**\n * @return {string[]}\n */\nfunction updateList(list, nameId, deadList) {\n if (!deadList.has(nameId.name))\n list.push(nameId.name);\n\n for (let child of nameId.children) {\n updateList(list, child, deadList);\n }\n}\n\nThroneInheritance.prototype.getInheritanceOrder = function() {\n let list = [];\n updateList(list, this.nameMap.get(this.king), this.deadList);\n return list;\n};", "solution_java": "class Tree{\n Listchild;\n String name;\n public Tree(String name,Listchild){\n this.name=name;\n this.child=child;\n }\n}\nclass ThroneInheritance {\n private Setdeath;\n private Tree tree;\n private MapaddtoTree;\n public ThroneInheritance(String kingName) {\n death=new HashSet<>(); \n tree=new Tree(kingName,new ArrayList());\n addtoTree=new HashMap();\n addtoTree.put(kingName,tree); \n }\n \n public void birth(String parentName, String childName) {\n Tree tmp =addtoTree.get(parentName);\n Tree childtree=new Tree(childName,new ArrayList());\n tmp.child.add(childtree);\n addtoTree.put( childName,childtree); \n }\n \n public void death(String name) {\n death.add(name);\n }\n \n public List getInheritanceOrder() {\n Listans=new ArrayList<>();\n preOreder(tree,ans,death);\n return ans;\n }\n \n void preOreder(Tree n,Listans,Setdeath){\n if(n==null)return;\n if(!death.contains(n.name))ans.add(n.name);\n for(Tree name:n.child){\n preOreder(name,ans,death);\n }\n }\n}", "solution_c": "class ThroneInheritance {\npublic:\n ThroneInheritance(string kingName) {\n curr_king = kingName;\n }\n \n void birth(string parentName, string childName) {\n children[parentName].push_back(childName);\n }\n \n void death(string name) {\n dead.insert(name);\n }\n \n void rec(string parent) {\n if (!dead.count(parent)) inheritance.push_back(parent);\n for (auto child : children[parent])\n rec(child);\n }\n \n vector getInheritanceOrder() {\n inheritance = {};\n rec(curr_king);\n return inheritance;\n }\n \nprivate:\n unordered_map> children;\n vector inheritance;\n unordered_set dead;\n string curr_king;\n};" }, { "title": "Previous Permutation With One Swap", "algo_input": "Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.\n\n \nExample 1:\n\nInput: arr = [3,2,1]\nOutput: [3,1,2]\nExplanation: Swapping 2 and 1.\n\n\nExample 2:\n\nInput: arr = [1,1,5]\nOutput: [1,1,5]\nExplanation: This is already the smallest permutation.\n\n\nExample 3:\n\nInput: arr = [1,9,4,6,7]\nOutput: [1,7,4,6,9]\nExplanation: Swapping 9 and 7.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 104\n\t1 <= arr[i] <= 104\n\n", "solution_py": "class Solution:\n\n def find_max(self, i, a, n):\n maxs = i+1\n for j in range(n-1, i, -1):\n # if only j is greater than max and smaller than first descending element\n if(a[maxs] <= a[j] and a[j] < a[i]):\n maxs = j\n # Swap\n a[i], a[maxs] = a[maxs], a[i]\n return a\n\n def prevPermOpt1(self, arr):\n n = len(arr)\n for i in range(n-1, 0, -1):\n if(arr[i] < arr[i-1]):\n # sending the first descending element from right to max_function\n arr = self.find_max(i-1, arr, n)\n break\n return arr", "solution_js": "var prevPermOpt1 = function(arr) {\n const n = arr.length;\n let i = n - 1;\n \n while (i > 0 && arr[i] >= arr[i - 1]) i--;\n \n if (i === 0) return arr;\n\n const swapIndex = i - 1;\n const swapDigit = arr[swapIndex];\n \n let maxIndex = i;\n i = n - 1;\n \n while (swapIndex < i) {\n const currDigit = arr[i];\n \n if (currDigit < swapDigit && currDigit >= arr[maxIndex]) maxIndex = i;\n i--;\n }\n\n [arr[maxIndex], arr[swapIndex]] = [arr[swapIndex], arr[maxIndex]];\n \n return arr; \n}; ", "solution_java": "class Solution {\n public int[] prevPermOpt1(int[] arr) {\n int n=arr.length;\n int small=arr[n-1];\n int prev=arr[n-1];\n for(int i=n-2;i>=0;i--){\n if(arr[i]<=prev){\n prev=arr[i];\n }\n else{\n int indte=i;\n int te=0;\n for(int j=i+1;jte){\n te=arr[j];\n indte=j;\n }\n }\n int tem=arr[indte];\n arr[indte]=arr[i];\n arr[i]=tem;\n return arr;\n }\n }\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector prevPermOpt1(vector& arr) {\n int i, p, mn = -1;\n for(i=arr.size() - 2; i>=0; i--) {\n if(arr[i] > arr[i + 1]) break;\n }\n if(i == -1) return arr;\n\n for(int j=i + 1; j mn && arr[j] < arr[i]) mn = arr[j], p = j;\n \n }\n swap(arr[i], arr[p]);\n return arr;\n }\n};" }, { "title": "Word Ladder II", "algo_input": "A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:\n\n\n\tEvery adjacent pair of words differs by a single letter.\n\tEvery si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.\n\tsk == endWord\n\n\nGiven two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].\n\n \nExample 1:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\nExplanation: There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"\n\n\nExample 2:\n\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput: []\nExplanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n\n\n \nConstraints:\n\n\n\t1 <= beginWord.length <= 5\n\tendWord.length == beginWord.length\n\t1 <= wordList.length <= 500\n\twordList[i].length == beginWord.length\n\tbeginWord, endWord, and wordList[i] consist of lowercase English letters.\n\tbeginWord != endWord\n\tAll the words in wordList are unique.\n\n", "solution_py": "class Solution:\n\n WILDCARD = \".\"\n\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \"\"\"\n Given a wordlist, we perform BFS traversal to generate a word tree where\n every node points to its parent node.\n\n Then we perform a DFS traversal on this tree starting at the endWord.\n \"\"\"\n if endWord not in wordList:\n # end word is unreachable\n return []\n\n # first generate a word tree from the wordlist\n word_tree = self.getWordTree(beginWord, endWord, wordList)\n\n # then generate a word ladder from the word tree\n return self.getLadders(beginWord, endWord, word_tree)\n\n def getWordTree(self,\n beginWord: str,\n endWord: str,\n wordList: List[str]) -> Dict[str, List[str]]:\n \"\"\"\n BFS traversal from begin word until end word is encountered.\n\n This functions constructs a tree in reverse, starting at the endWord.\n \"\"\"\n # Build an adjacency list using patterns as keys\n # For example: \".it\" -> (\"hit\"), \"h.t\" -> (\"hit\"), \"hi.\" -> (\"hit\")\n adjacency_list = defaultdict(list)\n for word in wordList:\n for i in range(len(word)):\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n adjacency_list[pattern].append(word)\n\n # Holds the tree of words in reverse order\n # The key is an encountered word.\n # The value is a list of preceding words.\n # For example, we got to beginWord from no other nodes.\n # {a: [b,c]} means we got to \"a\" from \"b\" and \"c\"\n visited_tree = {beginWord: []}\n\n # start off the traversal without finding the word\n found = False\n\n q = deque([beginWord])\n while q and not found:\n n = len(q)\n\n # keep track of words visited at this level of BFS\n visited_this_level = {}\n\n for i in range(n):\n word = q.popleft()\n\n for i in range(len(word)):\n # for each pattern of the current word\n pattern = word[:i] + Solution.WILDCARD + word[i+1:]\n\n for next_word in adjacency_list[pattern]:\n if next_word == endWord:\n # we don't return immediately because other\n # sequences might reach the endWord in the same\n # BFS level\n found = True\n if next_word not in visited_tree:\n if next_word not in visited_this_level:\n visited_this_level[next_word] = [word]\n # queue up next word iff we haven't visited it yet\n # or already are planning to visit it\n q.append(next_word)\n else:\n visited_this_level[next_word].append(word)\n\n # add all seen words at this level to the global visited tree\n visited_tree.update(visited_this_level)\n\n return visited_tree\n\n def getLadders(self,\n beginWord: str,\n endWord: str,\n wordTree: Dict[str, List[str]]) -> List[List[str]]:\n \"\"\"\n DFS traversal from endWord to beginWord in a given tree.\n \"\"\"\n def dfs(node: str) -> List[List[str]]:\n if node == beginWord:\n return [[beginWord]]\n if node not in wordTree:\n return []\n\n res = []\n parents = wordTree[node]\n for parent in parents:\n res += dfs(parent)\n for r in res:\n r.append(node)\n return res\n\n return dfs(endWord)", "solution_js": "const isMatch = (currWord, nextWord) => {\n let mismatch = 0;\n for(let i = 0; i < nextWord.length; i += 1) {\n if(nextWord[i] !== currWord[i]) {\n mismatch += 1;\n }\n }\n\n return mismatch === 1;\n}\n\nconst getNextWords = (lastRung, dictionary) => {\n const nextWords = [];\n for(const word of dictionary) {\n if(isMatch(word, lastRung)) {\n nextWords.push(word);\n }\n }\n\n return nextWords;\n}\n\nconst updateLadders = (ladders, dictionary) => {\n const updatedLadders = [];\n const nextRung = new Set();\n\n for(const ladder of ladders) {\n const nextWords = getNextWords(ladder[ladder.length - 1], dictionary);\n for(const nextWord of nextWords) {\n updatedLadders.push([...ladder, nextWord]);\n nextRung.add(nextWord);\n }\n }\n\n return [updatedLadders, nextRung];\n}\n\nconst updateDictionary = (dictionary, nextRung) => {\n return dictionary.filter((word) => !nextRung.has(word));\n}\n\n// BFS traversal from endWord to beginWord\n// This limits the paths that we'll need to consider during our traversal from beingWord to endWord\nconst getDictionary = (wordList, endWord, beginWord) => {\n const dictionary = new Set();\n\n let currRung = [endWord];\n while(currRung.length > 0) {\n const nextRung = new Set();\n if(!wordList.includes(beginWord)) break;\n\n while(currRung.length > 0) {\n const currWord = currRung.pop();\n dictionary.add(currWord);\n\n for(const nextWord of wordList) {\n if(isMatch(currWord, nextWord)) {\n nextRung.add(nextWord);\n }\n }\n }\n\n currRung = [...nextRung];\n wordList = wordList.filter((word) => !nextRung.has(word));\n }\n\n return [...dictionary];\n}\n\nvar findLadders = function(beginWord, endWord, wordList) {\n if(!wordList.includes(endWord)) return [];\n if(!wordList.includes(beginWord)) wordList.push(beginWord);\n\n const result = [];\n const saveResult = (ladders) => {\n for(const ladder of ladders) {\n if(ladder[ladder.length - 1] === endWord) {\n result.push(ladder);\n }\n }\n }\n\n let ladders = [[beginWord]];\n let dictionary = getDictionary(wordList, endWord, beginWord);\n while(ladders.length > 0) {\n if(!dictionary.includes(endWord)) {\n saveResult(ladders);\n break;\n }\n\n const [updatedLadders, nextRung] = updateLadders(ladders, dictionary);\n ladders = updatedLadders;\n dictionary = updateDictionary(dictionary, nextRung);\n }\n\n return result;\n};", "solution_java": "class Solution {\n public List> findLadders(String beginWord, String endWord, List wordList) {\n Set dict = new HashSet(wordList);\n if( !dict.contains(endWord) )\n return new ArrayList();\n \n // adjacent words for each word\n Map> adjacency = new HashMap();\n Queue queue = new LinkedList();\n // does path exist?\n boolean found = false;\n \n // BFS for shortest path, keep removing visited words\n queue.offer(beginWord);\n dict.remove(beginWord);\n \n while( !found && !queue.isEmpty() ) {\n int size = queue.size();\n // adjacent words in current level\n HashSet explored = new HashSet();\n\n while( size-- > 0 ) {\n String word = queue.poll();\n \n if( adjacency.containsKey(word) )\n continue;\n \n // remove current word from dict, and search for adjacent words\n dict.remove(word);\n List adjacents = getAdjacents(word, dict);\n adjacency.put(word, adjacents);\n\n for(String adj : adjacents) {\n if( !found && adj.equals(endWord) ) \n found = true;\n \n explored.add(adj);\n queue.offer(adj);\n }\n }\n // remove words explored in current level from dict\n for(String word : explored)\n dict.remove(word);\n }\n\n // if a path exist, dfs to find all the paths\n if( found ) \n return dfs(beginWord, endWord, adjacency, new HashMap());\n else\n return new ArrayList();\n }\n \n private List getAdjacents(String word, Set dict) {\n List adjs = new ArrayList();\n char[] wordChars = word.toCharArray();\n \n for(int i=0; i> dfs(String src, String dest, \n Map> adjacency, \n Map>> memo) {\n if( memo.containsKey(src) )\n return memo.get(src);\n \n List> paths = new ArrayList();\n \n\t\t// reached dest? return list with dest word\n if( src.equals( dest ) ) {\n paths.add( new ArrayList(){{ add(dest); }} );\n return paths;\n }\n\n\t\t// no adjacent for curr word? return empty list\n List adjacents = adjacency.get(src);\n if( adjacents == null || adjacents.isEmpty() )\n return paths;\n\n for(String adj : adjacents) {\n List> adjPaths = dfs(adj, dest, adjacency, memo);\n \n for(List path : adjPaths) {\n if( path.isEmpty() ) continue;\n \n List newPath = new ArrayList(){{ add(src); }};\n newPath.addAll(path);\n \n paths.add(newPath);\n }\n } \n memo.put(src, paths);\n return paths;\n }\n}", "solution_c": "// BFS gives TLE if we store path while traversing because whenever we find a better visit time for a word, we have to clear/make a new path vector everytime. \n// The idea is to first use BFS to search from beginWord to endWord and generate the word-to-children mapping at the same time. \n// Then, use DFS (backtracking) to generate the transformation sequences according to the mapping. \n// The reverse DFS allows us to only make the shortest paths, never having to clear a whole sequence when we encounter better result in BFS\n// No string operations are done, by dealing with indices instead.\n\n\n\nclass Solution {\npublic:\nbool able(string s,string t){\n int c=0;\n for(int i=0;i> &g,vector parent[],int n,int start,int end){\n vector dist(n,1005);\n queue q;\n q.push(start);\n parent[start]={-1};\n dist[start]=0;\n while(!q.empty()){\n int x=q.front();\n q.pop();\n for(int u:g[x]){\n if(dist[u]>dist[x]+1){\n dist[u]=dist[x]+1;\n q.push(u);\n parent[u].clear();\n parent[u].push_back(x);\n }\n else if(dist[u]==dist[x]+1)\n parent[u].push_back(x);\n }\n }\n}\nvoid shortestPaths(vector> &Paths, vector &path, vector parent[],int node){\n if(node==-1){\n // as parent of start was -1, we've completed the backtrack\n Paths.push_back(path);\n return ;\n }\n for(auto u:parent[node]){\n path.push_back(u);\n shortestPaths(Paths,path,parent,u);\n path.pop_back();\n }\n}\nvector> findLadders(string beginWord, string endWord, vector& wordList) {\n // start and end are indices of beginWord and endWord\n int n=wordList.size(),start=-1,end=-1;\n vector> ANS;\n for(int i=0;i> g(n,vector()),Paths;\n \n // storing possible parents for each word (to backtrack later), path is the current sequence (while backtracking)\n vector parent[n],path;\n \n // creating adjency list for each pair of words in the wordList (including beginword)\n for(int i=0;i now;\n for(int i=0;i bool:\n if head.next == None: return True #if only 1 element, it's always a palindrome\n forward = head\n first_half = []\n fast = head\n\n while (fast != None and fast.next != None):\n first_half.append(forward.val)\n forward = forward.next\n fast = fast.next.next\n\n # forward should now be through half the list\n if fast != None : forward = forward.next # if length isn't even, skip the middle number\n \n reverse = len(first_half)-1\n while forward != None:\n if forward.val != first_half[reverse]: return False\n forward = forward.next\n reverse -= 1\n\n return True", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nvar isPalindrome = function(head) {\n let slow = head;\n let fast = head;\n // Moving slow one step at a time while fast, two steps\n while (fast && fast.next) {\n slow = slow.next;\n fast = fast.next.next;\n }\n // This way, slow will end up right after the middle node\n // Reverse the list from that node\n slow = reverse(slow);\n fast = head;\n // Now check for equality first half and second half of the list\n while (slow) {\n if (slow.val !== fast.val) {\n return false;\n }\n slow = slow.next;\n fast = fast.next;\n }\n return true;\n};\n\n// Function to reverse a LinkedList\nfunction reverse(head) {\n let prev = null;\n while (head) {\n let nextNode = head.next;\n head.next = prev;\n prev = head;\n head = nextNode;\n }\n return prev;\n}", "solution_java": "class Solution {\n public boolean isPalindrome(ListNode head) {\n \n ListNode mid = getMiddle(head);\n ListNode headSecond = reverse(mid);\n ListNode reverseHead = headSecond;\n \n while(head != null && headSecond != null){\n if(head.val != headSecond.val){\n break;\n }\n head = head.next;\n headSecond = headSecond.next;\n }\n reverse(reverseHead);\n \n return head==null || headSecond == null;\n }\n \n public ListNode reverse(ListNode head){\n if(head==null) return head;\n ListNode prev = null;\n ListNode present = head;\n ListNode next = head.next;\n while(present != null){\n present.next = prev;\n prev = present;\n present = next;\n if(next!=null)\n next = next.next;\n }\n return prev;\n }\n \n public ListNode getMiddle(ListNode head){\n ListNode temp = head;\n int count = 0;\n while(temp!=null){\n temp = temp.next;\n count++;\n }\n int mid = count/2;\n temp = head;\n for(int i=0; inext;\n head->next=prev;\n prev=head;\n head=current;\n }\n return prev;\n }\n bool isPalindrome(ListNode* head) {\n if(!head || !head->next) return true;\n ListNode* tort=head;\n ListNode* hare=head;\n while(hare->next && hare->next->next)\n {\n tort=tort->next;\n hare=hare->next->next;\n }\n tort->next=reverse(tort->next);\n tort=tort->next;\n ListNode* dummy=head;\n while(tort)\n {\n if(tort->val!=dummy->val)\n return false;\n tort=tort->next;\n dummy=dummy->next;\n }\n return true;\n }\n};\n\nTime Complexity: O(n/2)+O(n/2)+O(n/2)\nSpace Complexity: O(1)" }, { "title": "Available Captures for Rook", "algo_input": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.\n\nWhen the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.\n\nReturn the number of available captures for the white rook.\n\n \nExample 1:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: In this example, the rook is attacking all the pawns.\n\n\nExample 2:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 0\nExplanation: The bishops are blocking the rook from attacking any of the pawns.\n\n\nExample 3:\n\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: The rook is attacking the pawns at positions b5, d6, and f5.\n\n\n \nConstraints:\n\n\n\tboard.length == 8\n\tboard[i].length == 8\n\tboard[i][j] is either 'R', '.', 'B', or 'p'\n\tThere is exactly one cell with board[i][j] == 'R'\n\n", "solution_py": "class Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n\t\t# Checking for possible case to the right of Rook\n def right_position(n,i):\n List = i[0:n][::-1] # taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List: # Checking if 'p' in list \n pIndex = List.index('p')\n if 'B' in List: # Checking if 'B' in list\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1: # if list does not have 'B' and have 'p'\n return True\n if pIndex == -1: # if list does not have 'p'\n return False\n return bIndex>pIndex \n def left_position(n,i):\n List = i[n+1:]# taking list to the right of rook\n pIndex,bIndex = -1,-1\n if 'p' in List:\n pIndex = List.index('p')\n if 'B' in List:\n bIndex = List.index('B')\n print(bIndex,pIndex,List)\n if bIndex == -1 and pIndex >-1:\n return True\n if pIndex == -1:\n return False\n return bIndex>pIndex\n Count = 0\n\t\t# Checking for possibilites in row\n for i in board:\n if 'R' in i:\n print(i)\n n = i.index('R')\n if left_position(n,i):\n Count += 1\n if right_position(n,i):\n Count += 1\n Col = []\n\t\t# checking for possibilites in col\n for i in range(0,len(board)):\n Col.append(board[i][n]) # taking the elements from the same col of Rook\n n = Col.index('R')\n if left_position(n,Col):\n Count += 1\n if right_position(n,Col):\n Count += 1\n return Count", "solution_js": "var numRookCaptures = function(board) {\n const r=board.length;\n const c=board[0].length;\n\n let res=0\n const dir=[[0,1],[0,-1],[1,0],[-1,0]]; // all the 4 possible directions\n let rook=[];\n\n // finding the rook's position\n for(let i=0;i=0&&newY>=0){\n if(board[newX][newY]==='p'){\n attack++\n break; // break because Rook can't attack more than one pawn in same direction\n }else if(board[newX][newY]==='B'){\n break\n }\n // keep moving towards the same direction\n newX+=x\n newY+=y\n }\n return attack\n }\n};", "solution_java": "class Solution {\n public int numRookCaptures(char[][] board) {\n int ans = 0;\n\n int row = 0;\n int col = 0;\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {\n if (board[i][j] == 'R') {\n row = i;\n col = j;\n break;\n }\n }\n }\n\n int j = col;\n while (j >= 0) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j--;\n }\n\n j = col;\n while (j <= board[0].length - 1) {\n if (board[row][j] == 'B') {\n break;\n } else if (board[row][j] == 'p') {\n ans++;\n break;\n }\n\n j++;\n }\n\n int i = row;\n while (i <= board.length - 1) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i++;\n }\n\n i = row;\n while (i >= 0) {\n if (board[i][col] == 'B') {\n break;\n } else if (board[i][col] == 'p') {\n ans++;\n break;\n }\n\n i--;\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numRookCaptures(vector>& board) {\n int res=0;\n int p=-1,q=-1;\n for(int i=0;i=0)\n break;\n }\n // traverse Up, Down, Left and Right from R\n for(int i=p+1;i=0;i--)\n {\n if(board[i][q]!='.')\n {\n if(board[i][q]=='p')\n res++;\n break;\n }\n }\n \n for(int j=q+1;j=0;j--)\n {\n if(board[p][j]!='.')\n {\n if(board[p][j]=='p')\n res++;\n break;\n }\n }\n return res;\n }\n};" }, { "title": "Minimum Distance Between BST Nodes", "algo_input": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.\n\n \nExample 1:\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 100].\n\t0 <= Node.val <= 105\n\n\n \nNote: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/\n", "solution_py": "# 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 minDiffInBST(self, root: Optional[TreeNode]) -> int:\n if root is None:\n return 0\n temp1=float(inf)\n from collections import deque\n a=deque([root])\n b=[]\n while a:\n node=a.popleft()\n b.append(node.val)\n if node.left:\n a.append(node.left)\n if node.right:\n a.append(node.right)\n b.sort()\n for i in range(0,len(b)-1):\n if b[i+1]-b[i]", "solution_js": "/**\n * @param {TreeNode} root\n * @return {number}\n */\nvar minDiffInBST = function(root) {\n let arr = [];\n \n\tconst helper = (node) => {\n\t\tif (node) {\n\t\t\thelper(node.left);\n\t\t\tarr.push(node.val);\n\t\t\thelper(node.right);\n\t\t}\n\t}\n\thelper(root);\n \n\tlet min = Infinity;\n\tfor (let i = 0; i < arr.length - 1; i++) {\n\t\tconst diff = Math.abs(arr[i] - arr[i + 1]);\n\t\tmin = Math.min(min, diff);\n\t}\n \n\treturn min;\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 \n int mini=Integer.MAX_VALUE;\n\n public void find(TreeNode root,ArrayListarr){\n \n if(root==null){\n return;\n }\n \n \n arr.add(root.val);\n \n find(root.left,arr);\n \n for(int i=arr.size()-2;i>=0;i--){\n \n mini=Math.min(mini,Math.abs(root.val-arr.get(i)));\n }\n \n find(root.right,arr);\n \n arr.remove(arr.size()-1);\n }\n\n public int minDiffInBST(TreeNode root) {\n ArrayListarr=new ArrayList<>();\n find(root,arr);\n return mini; \n }\n}", "solution_c": "class Solution {\n int minDiff=INT_MAX,prev=INT_MAX;\npublic:\n void inorder(TreeNode* p){\n if(p==NULL) return;\n inorder(p->left);\n minDiff=min(minDiff,abs(p->val-prev));\n prev=p->val;\n inorder(p->right);\n }\n int minDiffInBST(TreeNode* root) {\n inorder(root);\n return minDiff;\n }\n};" }, { "title": "Remove Max Number of Edges to Keep Graph Fully Traversable", "algo_input": "Alice and Bob have an undirected graph of n nodes and three types of edges:\n\n\n\tType 1: Can be traversed by Alice only.\n\tType 2: Can be traversed by Bob only.\n\tType 3: Can be traversed by both Alice and Bob.\n\n\nGiven an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\n\nReturn the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.\n\n \nExample 1:\n\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput: 2\nExplanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n\n\nExample 2:\n\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput: 0\nExplanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n\n\nExample 3:\n\n\n\nInput: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput: -1\nExplanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n\n \n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\t1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)\n\tedges[i].length == 3\n\t1 <= typei <= 3\n\t1 <= ui < vi <= n\n\tAll tuples (typei, ui, vi) are distinct.\n\n", "solution_py": "class DSUF:\n def __init__(self, n):\n self.arr = [-1] * n\n def find(self, node):\n p = self.arr[node]\n if p == -1:\n return node\n self.arr[node] = self.find(p)\n return self.arr[node]\n def union(self, a, b):\n aP = self.find(a)\n bP = self.find(b)\n if aP == bP:\n return 0\n self.arr[aP] = bP\n return 1\n def countParents(self):\n count = 0\n for i in self.arr:\n if i == -1:\n count += 1\n return count\n\nclass Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n # Solution - DSU\n # Time - O(ElogV)\n # Space - O(V)\n \n aliceSet = DSUF(n)\n bobSet = DSUF(n)\n \n bothEdges = []\n bobEdges = []\n aliceEdges= []\n for i in range(len(edges)):\n if edges[i][0] == 3:\n bothEdges.append(edges[i])\n elif edges[i][0] == 1:\n aliceEdges.append(edges[i])\n else:\n bobEdges.append(edges[i])\n \n usedEdgeCount = 0\n \n # connect both edges\n for edge in bothEdges:\n aReq = aliceSet.union(edge[1]-1, edge[2]-1)\n bReq = bobSet.union(edge[1]-1, edge[2]-1)\n if aReq and bReq:\n usedEdgeCount += 1\n \n # connect individual edges\n for edge in aliceEdges:\n usedEdgeCount += aliceSet.union(edge[1]-1, edge[2]-1)\n \n for edge in bobEdges:\n usedEdgeCount += bobSet.union(edge[1]-1, edge[2]-1)\n \n if aliceSet.countParents() == 1 and bobSet.countParents() == 1:\n return len(edges) - usedEdgeCount\n \n return -1", "solution_js": "// A common disjoint set class\nfunction DS(n) {\n var root = [...new Array(n + 1).keys()];\n var rank = new Array(n + 1).fill(0);\n this.find = function(v) {\n if (root[v] !== v) root[v] = this.find(root[v]);\n return root[v];\n }\n this.union = function (i, j) {\n var [a, b] = [this.find(i), this.find(j)];\n if (a === b) return false;\n if (rank[a] > rank[b]) root[b] = a;\n else if (rank[a] < rank[b]) root[a] = b;\n else root[a] = b, rank[b]++;\n return true;\n }\n\t// check if the nodes 1-n is in the same set\n this.canFullyTraverse = function() {\n var key = this.find(1);\n for (var i = 2; i <= n; i++) {\n if (this.find(i) !== key) return false;\n }\n return true;\n }\n}\n\n/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number}\n */\nvar maxNumEdgesToRemove = function(n, edges) {\n\t// two persons disjoint set\n var ds1 = new DS(n);\n var ds2 = new DS(n);\n\t// sort edges by type, to make sure we can handle type 3 first\n edges.sort((a, b) => b[0] - a[0]);\n var result = 0;\n edges.forEach(([type, u, v]) => {\n\t\t// when edge type is 3, union u, v for both person's ds\n\t\t// if they are already in the same set, this edge can be remove, result++\n if (type === 3) {\n var [r1, r2] = [ds1.union(u, v), ds2.union(u, v)];\n if (!r1 && !r2) {\n result++;\n }\n\t\t// for specific person\n } else if (type === 1) {\n if (!ds1.union(u, v)) {\n result++;\n }\n } else {\n if (!ds2.union(u, v)) {\n result++;\n }\n }\n });\n\t// if one person cannot fully traverse, return -1\n\t// otherwise, return result\n if (ds1.canFullyTraverse() && ds2.canFullyTraverse()) {\n return result;\n }\n return -1;\n};", "solution_java": "class Solution {\n public int maxNumEdgesToRemove(int n, int[][] edges) \n {\n Arrays.sort(edges, (a, b)->{\n return b[0]-a[0];\n });//giving the priority to third type of edge or the edge which Bob and Alice both can access\n \n //1-based indexing of nodes \n int []parentAlice= new int[n+1];//Graph 1 for Alice connectedness\n int []parentBob= new int[n+1];//Graph 2 for Bob connectedness\n \n for(int i= 0; i< n+1; i++){//every node is pointing to itself, at first no connection is considered all sets are independent(no dependency) \n parentAlice[i]= i;\n parentBob[i]= i;\n }\n \n //number of merged unique node for Alice and Bob that are required to maintain the connectedness of Alice and Bob graph nodes//intialised with one because merging happens in pair \n int mergeAlice= 1;\n int mergeBob= 1;\n \n //number of cyclic or the non dependent node, that are not required for the connectedness of Alice and Bob nodes \n int removeEdge= 0;\n \n for(int []edge: edges)\n {\n int cat= edge[0];//category of edge 1)edge Alice can only access 2)edge Bob can only access 3)edge both Alice and Bob can access\n int u= edge[1];\n int v= edge[2];\n \n if(cat == 3){//edge both Alice and Bob an access\n \n //creating dependency of nodes in graph 1 and 2 \n boolean tempAlice= union(u, v, parentAlice);\n boolean tempBob= union(u, v, parentBob);\n \n if(tempAlice == true)\n mergeAlice+= 1;\n \n if(tempBob == true)\n mergeBob+= 1;\n \n if(tempAlice == false && tempBob == false)//retundant or the cyclic non-dependent edge//both Alice and Bob don't rquire it connection is already there between these pair of nodes\n removeEdge+= 1;\n }\n else if(cat == 2){//edge Bob can only access \n \n //creating dependency of nodes in graph 2\n boolean tempBob= union(u, v, parentBob);\n \n if(tempBob == true)\n mergeBob+= 1;\n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n else{//edge Alice can only access \n \n //creating dependency of nodes in graph 1\n boolean tempAlice= union(u, v, parentAlice);\n \n if(tempAlice == true)\n mergeAlice+= 1; \n else//no merging of set is done, that means that this edge is not required because it will form cycle or the dependency \n removeEdge+= 1;\n }\n }\n if(mergeAlice != n || mergeBob != n)//all node are not connected, connectedness is not maintained \n return -1;\n return removeEdge;//number of edge removed by maintaining the connectedness \n }\n \n public int find(int x, int[] parent)\n {\n if(parent[x] == x)//when we found the absolute root or the leader of the set \n return x;\n \n int temp= find(parent[x], parent);\n \n parent[x]= temp;//Path Compression//child pointing to the absolute root or the leader of the set, while backtracking\n \n return temp;//returning the absolute root \n }\n \n public boolean union(int x, int y, int[] parent)\n {\n int lx= find(x, parent);//leader of set x or the absolute root\n int ly= find(y, parent);//leader of set y or the absolute root\n \n if(lx != ly){//belong to different set merging \n \n //Rank Compression is not done, but you can do it \n parent[lx]= ly;\n \n return true;//union done, dependency created\n }\n else\n return false;//no union done cycle is due to this edge \n }//Please do Upvote, it helps a lot \n}", "solution_c": "class Solution {\npublic:\n vector < int > Ar , Ap , Br , Bp; // alice and bob parent and rank arrays\n static bool cmp(vector < int > & a , vector < int > & b){\n return a[0] > b[0];\n }\n // lets create the alice graph first\n // find function for finding the parent nodes\n int find1(int x){\n if(x == Ap[x]) return x;\n return Ap[x] = find1(Ap[x]);\n }\n // if nodes are already connected return 1 else make the connection and return 0\n bool union1( int x , int y){\n int parX = find1(x);\n int parY = find1(y);\n if(parX == parY) return 1;\n if(Ar[parX] > Ar[parY]){\n Ap[parY] = parX;\n }\n else if(Ar[parX] < Ar[parY]){\n Ap[parX] = parY;\n }\n else {\n Ap[parY] = parX;\n Ar[parX]++;\n }\n return 0;\n }\n // same thing do for bob graph\n int find2(int x){\n if(x == Bp[x]) return x;\n return Bp[x] = find2(Bp[x]);\n }\n\n bool union2( int x , int y){\n int parX = find2(x);\n int parY = find2(y);\n if(parX == parY) return 1;\n if(Br[parX] > Br[parY]){\n Bp[parY] = parX;\n }\n else if(Br[parX] < Br[parY]){\n Bp[parX] = parY;\n }\n else {\n Bp[parY] = parX;\n Br[parX]++;\n }\n return 0;\n }\n\n int maxNumEdgesToRemove(int n, vector>& edges) {\n Ar.resize(n , 1); Ap.resize(n , 1); Br.resize(n , 1); Bp.resize(n , 1);\n\n for(int i = 0; i1 | cnt2 >1) return -1;\n\n return ans;\n\n }\n};" }, { "title": "Sum of Digits in Base K", "algo_input": "Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.\n\nAfter converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.\n\n \nExample 1:\n\nInput: n = 34, k = 6\nOutput: 9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\n\n\nExample 2:\n\nInput: n = 10, k = 10\nOutput: 1\nExplanation: n is already in base 10. 1 + 0 = 1.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 100\n\t2 <= k <= 10\n\n", "solution_py": "class Solution:\n def sumBase(self, n: int, k: int) -> int:\n cnt = 0\n while n:\n cnt += (n % k)\n n //= k\n print(cnt)\n return cnt", "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar sumBase = function(n, k) {\n return n.toString(k).split(\"\").reduce((acc, cur) => +acc + +cur)\n};", "solution_java": "class Solution {\n public int sumBase(int n, int k) {\n int res = 0;\n for (; n > 0; n /= k)\n res += n % k;\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int sumBase(int n, int k) {\n int sum=0;\n while(n!=0) sum+=n%k,n=n/k;\n return sum;\n }\n};" }, { "title": "Binary Tree Postorder Traversal", "algo_input": "Given the root of a binary tree, return the postorder traversal of its nodes' values.\n\n \nExample 1:\n\nInput: root = [1,null,2,3]\nOutput: [3,2,1]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [1]\nOutput: [1]\n\n\n \nConstraints:\n\n\n\tThe number of the nodes in the tree is in the range [0, 100].\n\t-100 <= Node.val <= 100\n\n\n \nFollow up: Recursive solution is trivial, could you do it iteratively?", "solution_py": "from typing import List, Optional\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\tif root is None:\n\t\t\treturn []\n\n\t\tpostorder = []\n\t\tstack = [root]\n\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tpostorder.append(node.val)\n\t\t\tif node.left is not None:\n\t\t\t\tstack.append(node.left)\n\t\t\tif node.right is not None:\n\t\t\t\tstack.append(node.right)\n\n\t\treturn postorder[::-1]\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\t\"\"\"\n\n\tdef postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.postorder_generator(root))\n\n\t@classmethod\n\tdef postorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.postorder_generator(tree.left)\n\t\t\tyield from cls.postorder_generator(tree.right)\n\t\t\tyield tree.val", "solution_js": "class Pair{\n constructor(node, state){\n this.node = node;\n this.state = state;\n }\n}\nvar postorderTraversal = function(root) {\n let ans = [];\n let st = []; // stack\n root != null && st.push(new Pair(root, 1));\n\n while(st.length > 0){\n let top = st[st.length - 1];\n\n if(top.state == 1){\n\n top.state++;\n if(top.node.left != null){\n st.push(new Pair(top.node.left, 1))\n }\n } else if(top.state == 2){\n top.state++;\n if(top.node.right != null){\n st.push(new Pair(top.node.right, 1))\n }\n } else{\n ans.push(top.node.val);\n st.pop();\n }\n }\n return ans;\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 List res = new ArrayList<>();\n public List postorderTraversal(TreeNode root) {\n traversal(root);\n return res;\n }\n\n public void traversal(TreeNode root){\n if(root == null)\n return;\n traversal(root.left);\n traversal(root.right);\n res.add(root.val);\n }\n}", "solution_c": "class Solution {\n void solve(TreeNode *root, vector &ans){\n if(root == NULL) return;\n solve(root->left, ans);\n solve(root->right, ans);\n ans.push_back(root->val);\n }\npublic:\n vector postorderTraversal(TreeNode* root) {\n vector ans;\n solve(root, ans);\n return ans;\n }\n};" }, { "title": "Shortest Bridge", "algo_input": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water.\n\nAn island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.\n\nYou may change 0's to 1's to connect the two islands to form one island.\n\nReturn the smallest number of 0's you must flip to connect the two islands.\n\n \nExample 1:\n\nInput: grid = [[0,1],[1,0]]\nOutput: 1\n\n\nExample 2:\n\nInput: grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t2 <= n <= 100\n\tgrid[i][j] is either 0 or 1.\n\tThere are exactly two islands in grid.\n\n", "solution_py": "class Solution:\n def shortestBridge(self, grid):\n m, n = len(grid), len(grid[0])\n start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n \n stack = [(start_i, start_j)]\n visited = set(stack)\n while stack:\n i, j = stack.pop()\n visited.add((i, j)) \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n stack.append((ii, jj))\n visited.add((ii, jj))\n \n \n ans = 0\n queue = list(visited)\n while queue:\n new_queue = []\n for i, j in queue:\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n if grid[ii][jj] == 1:\n return ans\n new_queue.append((ii, jj))\n visited.add((ii, jj))\n queue = new_queue\n ans += 1", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst DIR = [\n [0,1],\n [0,-1],\n [1,0],\n [-1,0]\n];\n\nvar shortestBridge = function(grid) {\n const que = [];\n const ROWS = grid.length;\n const COLS = grid[0].length;\n\n // find first insland\n outer:\n for(let row=0; row=ROWS || newCol>=COLS) continue;\n if(grid[newRow][newCol] != 1) continue;\n stack.push([newRow, newCol]);\n }\n }\n break outer;\n }\n }\n }\n let steps = 0;\n while(que.length) {\n let size = que.length;\n for(let i=0; i=ROWS || newCol>=COLS) continue;\n if(grid[newRow][newCol] == 2) continue;\n if(grid[newRow][newCol] == 1) return steps;\n grid[newRow][newCol] = 2; // mark as visited.\n que.push([newRow, newCol]);\n }\n }\n steps++;\n }\n return -1;\n};", "solution_java": "class Solution {\n private static int[][] dirs={{1,0},{-1,0},{0,1},{0,-1}};\n public int shortestBridge(int[][] grid) {\n boolean[][] visited=new boolean[grid.length][grid[0].length];\n LinkedList queue=new LinkedList();\n boolean found=false;\n for(int i=0;i0){\n int size=queue.size();\n while(size-- >0){\n Pair pair=queue.poll();\n for(int k=0;k<4;k++){\n int rowDash=pair.row+dirs[k][0];\n int colDash=pair.col+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true )continue;\n if(grid[rowDash][colDash]==1) return level;\n queue.add(new Pair(rowDash,colDash));\n visited[rowDash][colDash]=true;\n }\n }\n level++;\n }\n return -1;\n }\n private void dfs(int[][] grid,int i,int j,LinkedList queue,boolean[][] visited){\n visited[i][j]=true;\n queue.add(new Pair(i,j));\n for(int k=0;k<4;k++){\n int rowDash=i+dirs[k][0];\n int colDash=j+dirs[k][1];\n if(rowDash<0 || colDash<0 || rowDash>=grid.length || colDash>=grid[0].length ||\n visited[rowDash][colDash]==true || grid[rowDash][colDash]==0)continue;\n dfs(grid,rowDash,colDash,queue,visited);\n }\n }\n static class Pair{\n int row;\n int col;\n public Pair(int row,int col){\n this.row=row;\n this.col=col;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void findOneIsland(vector>& grid, int i, int j, queue>& q){\n if(i<0 || j<0 || i==grid.size() || j==grid.size() || grid[i][j]!=1)\n return;\n grid[i][j] = 2;\n q.push({i,j});\n\n findOneIsland(grid, i, j-1, q);\n findOneIsland(grid, i, j+1, q);\n findOneIsland(grid, i-1, j, q);\n findOneIsland(grid, i+1, j, q);\n\n }\n int shortestBridge(vector>& grid) {\n int n = grid.size();\n queue> q;\n int res=0;\n bool OneIslandFound = false;\n for(int i=0;i int:\n return Counter(nums).most_common(1)[0][0]", "solution_js": "var repeatedNTimes = function(nums) {\n\n// loop through the array and then as we go over every num we filter that number and get the length. If the length is equal to 1 that is not the element so we continue if its not equal to one its the element we want and we just return that element. \n\n for (let num of nums) {\n let len = nums.filter(element => element === num).length\n if (len == 1) continue;\n else return num\n }\n\n};", "solution_java": "class Solution {\n public int repeatedNTimes(int[] nums) {\n int count = 0;\n for(int i = 0; i < nums.length; i++) {\n for(int j = i + 1; j < nums.length; j++) {\n if(nums[i] == nums[j])\n count = nums[j];\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int repeatedNTimes(vector& nums) {\n unordered_map mp;\n for(auto it : nums) mp[it]++;\n int n;\n for(auto it : mp) {\n if(it.second == nums.size() / 2) {\n n = it.first;\n break;\n }\n }\n return n;\n }\n};" }, { "title": "Sum of Subsequence Widths", "algo_input": "The width of a sequence is the difference between the maximum and minimum elements in the sequence.\n\nGiven an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.\n\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n\n \nExample 1:\n\nInput: nums = [2,1,3]\nOutput: 6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\n\nExample 2:\n\nInput: nums = [2]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n M = 10**9+7\n res = 0\n le = 1\n re = pow(2, n-1, M)\n #by Fermat's Little Thm\n #inverse of 2 modulo M\n inv = pow(2, M-2, M)\n for num in nums:\n res = (res + num * (le - re))%M\n le = (le * 2) % M\n re = (re * inv) % M\n return res", "solution_js": "var sumSubseqWidths = function(nums) {\n const mod = 1000000007;\n nums.sort((a, b) => a - b), total = 0, power = 1;\n for(let i = 0; i < nums.length; i++) {\n total = (total + nums[i] * power) % mod;\n power = (power * 2) % mod;\n }\n\n power = 1;\n for(let i = nums.length - 1; i >= 0; i--) {\n total = (total - nums[i] * power + mod) % mod;\n power = (power * 2) % mod;\n }\n\n return (total + mod) % mod\n};", "solution_java": "class Solution {\n public int sumSubseqWidths(int[] nums) {\n int MOD = (int)1e9 + 7;\n Arrays.sort(nums);\n\n long ans = 0;\n long p = 1;\n for(int i = 0; i < nums.length; i++){\n ans = (ans + p * nums[i] - p * nums[nums.length - 1 - i]) % MOD;\n p = (p * 2) % MOD;\n }\n return (int)ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int sumSubseqWidths(vector& nums) {\n vector < long long > pow(nums.size() ); \n pow[0] = 1;\n for(int i = 1 ; i& s) {\n int i = -1, j = s.size();\n while (++i < --j){\n //Instead of using temp we can do the following\n s[i] = s[j] + s[i];\n s[j] = s[i] - s[j];\n s[i] = s[i] - s[j];\n }\n }\n};" }, { "title": "Day of the Year", "algo_input": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.\n\n \nExample 1:\n\nInput: date = \"2019-01-09\"\nOutput: 9\nExplanation: Given date is the 9th day of the year in 2019.\n\n\nExample 2:\n\nInput: date = \"2019-02-10\"\nOutput: 41\n\n\n \nConstraints:\n\n\n\tdate.length == 10\n\tdate[4] == date[7] == '-', and all other date[i]'s are digits\n\tdate represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.\n\n", "solution_py": "class Solution:\n def dayOfYear(self, date: str) -> int:\n d={1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}\n year=int(date[:4])\n if year%4==0:\n if year%100==0:\n if year%400==0:\n d[2]=29\n else:\n d[2]=29\n month=int(date[5:7])\n day=int(date[8:])\n ans=0\n for i in range(1,month+1):\n ans+=d[i]\n return ans-(d[month]-day)", "solution_js": "var dayOfYear = function(date) {\n let dat2 = new Date(date)\n let dat1 = new Date(dat2.getFullYear(),00,00)\n let totalTime = dat2 - dat1\n return Math.floor(totalTime/1000/60/60/24)\n};", "solution_java": "class Solution {\n public int dayOfYear(String date) {\n int days = 0;\n int[] arr = {31,28,31,30,31,30,31,31,30,31,30,31};\n String[] year = date.split(\"-\");\n int y = Integer.valueOf(year[0]);\n int month = Integer.valueOf(year[1]);\n int day = Integer.valueOf(year[2]);\n boolean leap = false;\n for(int i = 0; i < month-1; i++){\n days = days+arr[i];\n }\n days = days+day;\n if(y%4==0){\n if(y%100==0){\n if(y%400==0){\n leap = true;\n }\n else{\n leap = false;\n }\n }\n else{\n leap = true;\n }\n }\n else{\n leap = false;\n }\n if(leap==true && month>2){\n System.out.println(\"Leap Year\");\n days = days+1;\n }\n return days;\n }\n}", "solution_c": "class Solution {\npublic:\n bool leapyear(int year){\n return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));\n }\n \n int dayOfYear(string date) {\n vector v;\n int ans = 0;\n int n = date.length();\n for (int i = 0; i < n; i++) {\n if (date[i] >= '0' && date[i] <= '9') {\n ans = ans * 10 + (date[i] - '0'); // subtract '0' to get the integer value\n } else {\n v.push_back(ans);\n ans = 0;\n }\n }\n v.push_back(ans); // add the last value to the vector\n if (v.size() != 3) return -1; // error handling for invalid input\n int year = v[0];\n int month = v[1];\n int day = v[2];\n if (month == 1) return day;\n if (month == 2) return 31 + day;\n \n if (month == 3) return leapyear(year) ? 60 + day : 59 + day;\n if (month == 4) return leapyear(year) ? 91 + day : 90 + day;\n if (month == 5) return leapyear(year) ? 121 + day : 120 + day;\n if (month == 6) return leapyear(year) ? 152 + day : 151 + day;\n if (month == 7) return leapyear(year) ? 182 + day : 181 + day;\n if (month == 8) return leapyear(year) ? 213 + day : 212 + day;\n if (month == 9) return leapyear(year) ? 244 + day : 243 + day;\n if (month == 10) return leapyear(year) ? 274+ day : 273 + day;\n if (month == 11) return leapyear(year) ? 305 + day : 304 + day;\n if (month == 12) return leapyear(year) ? 335 + day : 334 + day;\n return -1;\n }\n};" }, { "title": "Push Dominoes", "algo_input": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.\n\nAfter each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.\n\nWhen a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.\n\nFor the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.\n\nYou are given a string dominoes representing the initial state where:\n\n\n\tdominoes[i] = 'L', if the ith domino has been pushed to the left,\n\tdominoes[i] = 'R', if the ith domino has been pushed to the right, and\n\tdominoes[i] = '.', if the ith domino has not been pushed.\n\n\nReturn a string representing the final state.\n\n \nExample 1:\n\nInput: dominoes = \"RR.L\"\nOutput: \"RR.L\"\nExplanation: The first domino expends no additional force on the second domino.\n\n\nExample 2:\n\nInput: dominoes = \".L.R...LR..L..\"\nOutput: \"LL.RR.LLRRLL..\"\n\n\n \nConstraints:\n\n\n\tn == dominoes.length\n\t1 <= n <= 105\n\tdominoes[i] is either 'L', 'R', or '.'.\n\n", "solution_py": "class Solution:\n def pushDominoes(self, dom: str) -> str:\n from collections import deque\n n = len(dom)\n d = set()\n q = deque()\n arr = [0 for i in range(n)]\n for i in range(n):\n if dom[i] == \"L\":\n arr[i] = -1\n d.add(i)\n q.append((i,\"L\"))\n if dom[i] == \"R\":\n arr[i] = 1\n d.add(i)\n q.append((i,\"R\"))\n while q:\n t1 = set()\n for _ in range(len(q)):\n t = q.popleft()\n if t[1] == \"L\":\n if t[0]-1 >= 0 and t[0]-1 not in d:\n t1.add(t[0]-1)\n arr[t[0]-1] -= 1\n else:\n if t[0]+1 < n and t[0]+1 not in d:\n t1.add(t[0]+1)\n arr[t[0]+1] += 1\n for val in t1:\n d.add(val)\n if arr[val] > 0:\n q.append((val,\"R\"))\n elif arr[val]<0:\n q.append((val,\"L\"))\n ans = \"\"\n for val in arr:\n if val<0:\n ans += \"L\"\n elif val>0:\n ans += \"R\"\n else:\n ans += \".\"\n return ans", "solution_js": "/**\n * @param {string} dominoes\n * @return {string}\n */\nvar pushDominoes = function(dominoes) {\n \n let len = dominoes.length;\n let fall = [];\n let force = 0;\n let answer = \"\";\n \n // Traverse from left to right. Focus on the dominoes falling to the right\n for (let i = 0; i < len; i++) {\n if (dominoes[i] == 'R') {\n force = len;\n } else if (dominoes[i] == 'L') {\n force = 0;\n } else {\n force = Math.max(force-1,0);\n }\n fall[i] = force;\n }\n \n //console.log('fall array 1: ', fall);\n \n // Traverse from right to left. Focus on the dominoes falling to the left\n // Subtract the value from the values above\n for (let i = len-1; i >= 0; i--) {\n if (dominoes[i] == 'L') {\n force = len;\n } else if (dominoes[i] == 'R') {\n force = 0;\n } else {\n force = Math.max(force-1,0);\n }\n fall[i] -= force;\n } \n \n //console.log('fall array 2: ', fall);\n \n // Just traverse through the fall[] array and assign the values in the answer string accordingly\n for (let i = 0; i < len; i++) {\n if (fall[i] < 0)\n answer += 'L';\n else if (fall[i] > 0 )\n answer += 'R';\n else\n answer += '.';\n }\n \n //console.log('answer: ', answer);\n \n return answer;\n \n};", "solution_java": "// Time complexity: O(N)\n// Space complexity: O(N), where N is the length of input string\nclass Solution {\n public String pushDominoes(String dominoes) {\n // ask whether dominoes could be null\n final int N = dominoes.length();\n if (N <= 1) return dominoes;\n char[] res = dominoes.toCharArray();\n int i = 0;\n while (i < N) {\n if (res[i] == '.') {\n i++;\n } else if (res[i] == 'L') { // push left\n int j = i-1;\n while (j >= 0 && res[j] == '.') {\n res[j--] = 'L';\n }\n i++;\n } else { // res[i] == 'R'\n int j = i+1;\n while (j < N && res[j] == '.') { // try to find 'R' or 'L' in the right side\n j++;\n }\n if (j < N && res[j] == 'L') { // if found 'L', push left and right\n for (int l = i+1, r = j-1; l < r; l++, r--) {\n res[l] = 'R';\n res[r] = 'L';\n }\n i = j + 1;\n } else { // if no 'L', push right\n while (i < j) {\n res[i++] = 'R';\n }\n }\n }\n }\n return String.valueOf(res);\n }\n}", "solution_c": "class Solution {\npublic:\n string pushDominoes(string dominoes) {\n #define SET(ch, arr) \\\n if (dominoes[i] == ch) { count = 1; prev = ch; } \\\n else if (dominoes[i] != '.') prev = dominoes[i]; \\\n if (prev == ch && dominoes[i] == '.') arr[i] = count++;\n\n string res = \"\";\n char prev;\n int n = dominoes.size(), count = 1;\n\n vector left(n, 0), right(n, 0);\n for (int i = 0; i < n; i++) {\n SET('R', right);\n }\n\n prev = '.';\n for (int i = n-1; i >= 0; i--) {\n SET('L', left);\n }\n\n for (int i = 0; i < n; i++) {\n if (!left[i] && !right[i]) res += dominoes[i];\n else if (!left[i]) res += 'R';\n else if (!right[i]) res += 'L';\n else if (left[i] == right[i]) res += '.';\n else if (left[i] < right[i]) res += 'L';\n else res += 'R';\n }\n\n return res;\n }\n};" }, { "title": "Unique Paths III", "algo_input": "You are given an m x n integer array grid where grid[i][j] could be:\n\n\n\t1 representing the starting square. There is exactly one starting square.\n\t2 representing the ending square. There is exactly one ending square.\n\t0 representing empty squares we can walk over.\n\t-1 representing obstacles that we cannot walk over.\n\n\nReturn the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n\n \nExample 1:\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput: 2\nExplanation: We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n\n\nExample 2:\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput: 4\nExplanation: We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n\n\nExample 3:\n\nInput: grid = [[0,1],[2,0]]\nOutput: 0\nExplanation: There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 20\n\t1 <= m * n <= 20\n\t-1 <= grid[i][j] <= 2\n\tThere is exactly one starting cell and one ending cell.\n\n", "solution_py": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n ans, empty = 0, 1\n \n def dfs(grid: List[List[int]], row: int, col: int, count: int, visited) -> None:\n if row >= len(grid) or col >= len(grid[0]) or row < 0 or col < 0 or grid[row][col] == -1:\n return\n nonlocal ans\n if grid[row][col] == 2:\n if empty == count:\n ans += 1\n return\n if (row, col) not in visited:\n visited.add((row, col))\n dfs(grid, row + 1, col, count + 1, visited)\n dfs(grid, row - 1, col, count + 1, visited)\n dfs(grid, row, col + 1, count + 1, visited)\n dfs(grid, row, col - 1, count + 1, visited)\n visited.remove((row, col))\n \n row, col = 0, 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n row, col = i, j\n elif grid[i][j] == 0:\n empty += 1\n dfs(grid, row, col, 0, set())\n return ans", "solution_js": "// 980. Unique Paths III\nvar uniquePathsIII = function(grid) {\n const M = grid.length; // grid height\n const N = grid[0].length; // grid width\n let result = 0; // final result\n let startY = 0, startX = 0; // starting point coordinates\n let finalY = 0, finalX = 0; // endpoint coordinates\n let empty = 0; // count of empty squares\n let visit = Array(M); // visited squares (MxN of booleans)\n\n // Initialization of required variables\n for (let i = 0; i < M; i++) {\n visit[i] = Array(N).fill(false); // now: \"visit[i][j] === false\"\n for (let j = 0; j < N; j++) {\n switch (grid[i][j]) {\n case 0 : empty++; break;\n case 1 : startY = i; startX = j; break;\n case 2 : finalY = i; finalX = j; break;\n }\n }\n }\n\n // Recursively run DFS and get the answer in the \"result\" variable\n dfs(startY, startX, visit, 0);\n return result;\n\n // DFS implementation\n function dfs (startY, startX, visit, step) {\n\n // If it's a wrong square, then exit immediately\n if (startY < 0 || startY >= M || // off grid (height)\n startX < 0 || startX >= N || // off grid (width)\n visit[startY][startX] || // already processed\n grid [startY][startX] === -1 // this is an obstacle\n ) return; // ... exit now\n\n // Base case: we're at the endpoint, need to stop the recursion.\n // If all of squares are visited, increase the \"result\":\n // (count of paths from start to the end).\n if (startY === finalY && startX === finalX) {\n if (step - 1 === empty) result++;\n return;\n }\n\n // Run DFS for neighboring squares.\n // Increase the number of steps (count of the visited squares).\n visit[startY][startX] = true; // mark current square as visited\n dfs(startY-1, startX, visit, step + 1); // top\n dfs(startY, startX+1, visit, step + 1); // right\n dfs(startY+1, startX, visit, step + 1); // bottom\n dfs(startY, startX-1, visit, step + 1); // left\n visit[startY][startX] = false; // restore visited square\n }\n};", "solution_java": "class Solution {\n int walk = 0;\n public int uniquePathsIII(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0) {\n walk++;\n }\n }\n }\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n return ways(grid, i, j, m, n, 0);\n }\n }\n }\n return 0;\n }\n public int ways(int[][] grid, int cr, int cc, int m, int n, int count) {\n if (cr < 0 || cr == m || cc < 0 || cc == n || grid[cr][cc] == -1) {\n return 0;\n }\n if (grid[cr][cc] == 2) {\n if (count - 1 == walk) return 1;\n return 0;\n }\n grid[cr][cc] = -1;\n int ans = 0;\n int[] r = {0, 1, 0, -1};\n int[] c = {1, 0, -1, 0};\n for (int i = 0; i < 4; i++) {\n ans += ways(grid, cr + r[i], cc + c[i], m, n, count + 1);\n }\n grid[cr][cc] = 0;\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int dfs(vector>&grid,int x,int y,int zero){\n // Base Condition\n if(x < 0 || y < 0 || x >= grid.size() || y >= grid[0].size() || grid[x][y] == -1){\n return 0;\n }\n if(grid[x][y] == 2){\n return zero == -1 ? 1 : 0; // Why zero = -1, because in above example we have 9 zero's. So, when we reach the final cell we are covering one cell extra that means if all zero all covered then on reaching final it will make zero count = -1\n // If that's the case we find the path and return '1' otherwise return '0';\n }\n grid[x][y] = -1; // mark the visited cells as -1;\n zero--; // and reduce the zero by 1\n\n int totalPaths = dfs(grid, x + 1, y, zero) + // calculating all the paths available in 4 directions\n dfs(grid, x - 1, y, zero) +\n dfs(grid, x, y + 1, zero) +\n dfs(grid, x, y - 1, zero);\n\n // Let's say if we are not able to count all the paths. Now we use Backtracking over here\n grid[x][y] = 0;\n zero++;\n\n return totalPaths; // if we get all the paths, simply return it.\n }\n\n int uniquePathsIII(vector>& grid) {\n int start_x,start_y=0,cntzero=0;\n\n for(int i=0;i int:\n cnt, res, mask = [1] + [0] * 1023, 0, 0\n for ch in word:\n mask ^= 1 << (ord(ch) - ord('a'))\n res += cnt[mask]\n for n in range(10):\n res += cnt[mask ^ 1 << n];\n cnt[mask] += 1\n return res", "solution_js": "/**\n * @param {string} word\n * @return {number}\n */\nvar wonderfulSubstrings = function(word) {\n let hashMap={},ans=0,binaryRepresentation=0,t,pos,number,oneBitToggled;\n hashMap[0]=1;\n for(let i=0;im;\n m[0]++;\n long long int ans=0;\n for(int i=0;i= array.length) {\n answer.push(array)\n }\n\n const setObject = new Set()\n\n for (let index=pos; index> permuteUnique(int[] nums) {\n List> ans = new ArrayList<>();\n Arrays.sort(nums);\n boolean used[] = new boolean[nums.length];\n \n permutationsFinder(nums,ans,new ArrayList<>(),used);\n \n return ans;\n }\n \n static void permutationsFinder(int[] nums,List> ans,List list,boolean used[]){\n if(list.size() == nums.length){\n ans.add(new ArrayList<>(list));\n return;\n }\n \n for(int i=0;i0 && nums[i]==nums[i-1] && !used[i-1]) continue;\n list.add(nums[i]);\n used[i] = true;\n permutationsFinder(nums,ans,list,used);\n list.remove(list.size()-1);\n used[i] = false;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void fun(vector& nums, vector>&ans,int i)\n {\n if(i==nums.size())\n {\n ans.push_back(nums);\n return;\n }\n int freq[21]={0};\n for(int j=i;j> permuteUnique(vector& nums) {\n vector>ans;\n fun(nums,ans,0);\n return ans;\n }\n};" }, { "title": "Remove Duplicate Letters", "algo_input": "Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.\n\n \nExample 1:\n\nInput: s = \"bcabc\"\nOutput: \"abc\"\n\n\nExample 2:\n\nInput: s = \"cbacdcbc\"\nOutput: \"acdb\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of lowercase English letters.\n\n\n \nNote: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\n", "solution_py": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n \n\t\tlast_occ = {}\n\t\tstack = []\n\t\tvisited = set()\n\n\t\tfor i in range(len(s)):\n\t\t\tlast_occ[s[i]] = i\n\n\t\tfor i in range(len(s)):\n\n\t\t\tif s[i] not in visited:\n\t\t\t\twhile (stack and stack[-1] > s[i] and last_occ[stack[-1]] > i):\n\t\t\t\t\tvisited.remove(stack.pop())\n\n\t\t\t\tstack.append(s[i])\n\t\t\t\tvisited.add(s[i])\n\n\t\treturn ''.join(stack)", "solution_js": "var removeDuplicateLetters = function(s) {\n let sset = [...new Set(s)]\n if(Math.min(sset) == sset[0]) return [...sset].join('');\n else {\n sset.sort();\n return [...sset].join('');\n }\n};", "solution_java": "class Solution {\n public String removeDuplicateLetters(String s) {\n int[] lastIndex = new int[26];\n for (int i = 0; i < s.length(); i++){\n lastIndex[s.charAt(i) - 'a'] = i; // track the lastIndex of character presence\n }\n \n boolean[] seen = new boolean[26]; // keep track seen\n Stack st = new Stack();\n \n for (int i = 0; i < s.length(); i++) {\n int curr = s.charAt(i) - 'a';\n if (seen[curr]) continue; // if seen continue as we need to pick one char only\n while (!st.isEmpty() && st.peek() > curr && i < lastIndex[st.peek()]){\n seen[st.pop()] = false; // pop out and mark unseen\n }\n st.push(curr); // add into stack\n seen[curr] = true; // mark seen\n }\n\n StringBuilder sb = new StringBuilder();\n while (!st.isEmpty())\n sb.append((char) (st.pop() + 'a'));\n return sb.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string removeDuplicateLetters(string s) {\n int len = s.size();\n string res = \"\";\n unordered_map M;\n unordered_map V;\n stack S;\n \n for (auto c : s) {\n if (M.find(c) == M.end()) M[c] = 1;\n else M[c]++; \n }\n for (unordered_map::iterator iter=M.begin(); iter!=M.end(); iter++) V[iter->first] = false;\n \n cout< 0) {\n V[s[S.top()]] = false;\n S.pop();\n }\n S.push(i);\n V[s[i]] = true;\n }\n while (!S.empty()) {\n res = s[S.top()] + res;\n S.pop();\n }\n return res;\n }\n};\n\n\nAnalysis\nTime complexity O(n)\nspace complexity O(n)" }, { "title": "Most Frequent Subtree Sum", "algo_input": "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.\n\nThe subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).\n\n \nExample 1:\n\nInput: root = [5,2,-3]\nOutput: [2,-3,4]\n\n\nExample 2:\n\nInput: root = [5,2,-5]\nOutput: [2]\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", "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 findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n def dfs(root):\n \n if not root: return 0\n \n l = dfs(root.left)\n r = dfs(root.right)\n res = root.val + l + r\n \n d[res] += 1\n return res\n \n d = collections.Counter()\n dfs(root)\n maxi = max(d.values())\n return [i for i in d if d[i] == maxi]\n \n\t\t# An Upvote will be encouraging\n \n ", "solution_js": "var findFrequentTreeSum = function(root) {\n\tconst hash = new Map();\n\tconst result = [];\n\tlet max = 0;\n\tconst dfs = (node = root) => {\n\t\tif (!node) return 0;\n\t\tconst { left, right, val } = node;\n\t\tconst sum = val + dfs(left) + dfs(right);\n\t\tconst count = hash.get(sum) ?? 0;\n\t\thash.set(sum, count + 1);\n\t\tmax = Math.max(max, count + 1);\n\t\treturn sum;\n\t};\n\n\tdfs();\n\thash.forEach((value, key) => value === max && result.push(key));\n\treturn result;\n};", "solution_java": "class Solution {\n public int[] findFrequentTreeSum(TreeNode root) {\n\n HashMap map=new HashMap<>();\n int sum=sum(root,map);\n int max=0;\n int count=0;\n for(Integer key:map.keySet()){\n max=Math.max(max,map.get(key));\n }\n\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n count++;\n }\n }\n int[] ans=new int[count];\n int counter=0;\n for(Integer key:map.keySet()){\n if(max==map.get(key)){\n ans[counter++]=key;\n }\n }\n\n return ans;\n\n }\n public int sum(TreeNode root,HashMap map){\n if(root==null)return 0;\n int lh=sum(root.left,map);\n int rh=sum(root.right,map);\n map.put(lh+rh+root.val,map.getOrDefault(lh+rh+root.val,0)+1);\n return lh+rh+root.val;\n }\n}", "solution_c": "class Solution {\nprivate:\n unordered_map m;\n int maxi = 0;\n int f(TreeNode* root){\n if(!root) return 0;\n int l = f(root->left);\n int r = f(root->right);\n int sum = root->val + l + r;\n m[sum]++;\n maxi = max(maxi, m[sum]);\n return sum;\n }\npublic:\n vector findFrequentTreeSum(TreeNode* root) {\n vector ans;\n f(root);\n for(auto &e : m){\n if(e.second == maxi) ans.push_back(e.first);\n }\n return ans;\n }\n};" }, { "title": "Mirror Reflection", "algo_input": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.\n\nThe square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.\n\nGiven the two integers p and q, return the number of the receptor that the ray meets first.\n\nThe test cases are guaranteed so that the ray will meet a receptor eventually.\n\n \nExample 1:\n\nInput: p = 2, q = 1\nOutput: 2\nExplanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n\n\nExample 2:\n\nInput: p = 3, q = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= q <= p <= 1000\n\n", "solution_py": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n\n L = lcm(p,q)\n\n if (L//q)%2 == 0:\n return 2\n\n return (L//p)%2", "solution_js": "// Time complexity: O(log (min(p,q))\n// Space complexity: O(1)\n\nvar mirrorReflection = function(p, q) {\n\tlet ext = q, ref = p;\n\t\n\twhile (ext % 2 == 0 && ref % 2 == 0) {\n\t\text /= 2;\n\t\tref /= 2;\n\t}\n\t\n\tif (ext % 2 == 0 && ref % 2 == 1) return 0;\n\tif (ext % 2 == 1 && ref % 2 == 1) return 1;\n\tif (ext % 2 == 1 && ref % 2 == 0) return 2;\n\t\n\treturn -1;\n};", "solution_java": " class Solution {\n public int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0){\n p >>= 1; q >>= 1;\n }\n return 1 - p % 2 + q % 2;\n }\n};", "solution_c": "class Solution {\npublic:\n int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0){\n p/=2;\n q/=2;\n }\n return 1 - p % 2 + q % 2;\n }\n};" }, { "title": "Partition Labels", "algo_input": "You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.\n\nNote that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\n\nReturn a list of integers representing the size of these parts.\n\n \nExample 1:\n\nInput: s = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.\n\n\nExample 2:\n\nInput: s = \"eccbbbbdec\"\nOutput: [10]\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 500\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def partitionLabels(self, s: str) -> List[int]:\n d = defaultdict(list)\n for i, char in enumerate(s):\n d[char].append(i)\n nums = []\n \n for v in d.values():\n nums.append([v[0], v[-1]])\n\n start = nums[0][0]\n maxIndex = nums[0][1]\n ans = []\n for i in range(1, len(nums)):\n if nums[i][0] <= maxIndex:\n maxIndex = max(maxIndex, nums[i][1])\n else:\n ans.append(maxIndex - start + 1)\n start = nums[i][0]\n maxIndex = nums[i][1]\n ans.append(maxIndex - start + 1)\n # print(ans)\n return ans", "solution_js": "var partitionLabels = function(s) {\n let last = 0, first = 0;\n\n let arr = [...new Set(s)], ss = [];\n let temp = '';\n\n first = s.indexOf(arr[0]);\n last = s.lastIndexOf(arr[0]);\n\n for(let i = 1; i partitionLabels(String s) {\n \n Listlr=new ArrayList<>();\n\n HashMapmp=new HashMap<>();\n\n int count=0;\n\n for(int i=0;i partitionLabels(string s) {\n unordered_mapmp;\n // filling impact of character's\n for(int i = 0; i < s.size(); i++){\n char ch = s[i];\n mp[ch] = i;\n }\n // making of result\n vector res;\n int prev = -1;\n int maxi = 0;\n\n for(int i = 0; i < s.size(); i++){\n maxi = max(maxi, mp[s[i]]);\n if(maxi == i){\n // partition time\n res.push_back(maxi - prev);\n prev = maxi;\n }\n }\n return res;\n }\n};" }, { "title": "Maximum Side Length of a Square with Sum Less than or Equal to Threshold", "algo_input": "Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.\n\n \nExample 1:\n\nInput: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput: 2\nExplanation: The maximum side length of square with sum less than 4 is 2 as shown.\n\n\nExample 2:\n\nInput: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput: 0\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 300\n\t0 <= mat[i][j] <= 104\n\t0 <= threshold <= 105\n\n", "solution_py": "class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n # prefix matrix\n dp = [[0]*(len(mat[0])+1) for _ in range(len(mat)+1)]\n \n for i in range(1, len(mat)+1):\n for j in range(1, len(mat[0])+1):\n dp[i][j] = dp[i][j-1] + dp[i-1][j] - dp[i-1][j-1] + mat[i-1][j-1]\n \n #bin search\n max_side = 0\n for i in range(1, len(mat) + 1):\n for j in range(1, len(mat[0]) + 1):\n if min(i, j) < max_side:\n continue\n left = 0\n right = min(i,j)\n while left <= right:\n mid = (left+right)//2\n pref_sum = dp[i][j] - dp[i-mid][j] - dp[i][j-mid] + dp[i-mid][j-mid]\n if pref_sum <= threshold:\n max_side = max(max_side, mid)\n left = mid + 1\n else:\n right = mid - 1\n return max_side\n ", "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} threshold\n * @return {number}\n */\nvar maxSideLength = function(mat, threshold) {\n const n = mat.length, m = mat[0].length;\n \n // build sum matrix\n let sum = [];\n for(let i=0; i<=n; i++) {\n sum.push(new Array(m+1).fill(0));\n for(let j=0; j<=m; j++) {\n if(i==0 || j==0) {\n continue;\n }\n sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + mat[i-1][j-1];\n }\n }\n \n // function to check square sum <= threshold\n const underThreshold = function(len) {\n for(let i=len; i<=n; i++) {\n for(let j=len; j<=m; j++) {\n if(sum[i][j] - sum[i-len][j] - sum[i][j-len] + sum[i-len][j-len] <= threshold) {\n return true;\n }\n }\n }\n return false;\n };\n \n // binary search\n let l=0, r=Math.min(n, m);\n while(l<=r) {\n const mid = Math.floor((l+r)/2);\n if(underThreshold(mid)) {\n l = mid+1;\n } else {\n r = mid-1;\n }\n }\n return r;\n};", "solution_java": "class Solution {\n public int maxSideLength(int[][] mat, int threshold) {\n int rows = mat.length;\n int cols = mat[0].length;\n int[][] preSum = new int[rows+1][cols+1];\n for(int i=1;i<=rows;i++){\n for(int j=1;j<=cols;j++){\n preSum[i][j] = preSum[i-1][j] + preSum[i][j-1] - preSum[i-1][j-1] + mat[i-1][j-1];\n }\n }\n int lo=1,hi=Math.min(rows,cols);\n while(lo<=hi){\n int m = (lo+hi)>>1;\n if(fun(preSum,threshold,rows,cols,m)) lo=m+1;\n else hi=m-1;\n }\n return lo-1;\n }\n private boolean fun(int[][] preSum, int maxSum,int rows, int cols, int size){\n for(int r=size;r<=rows;r++){\n for(int c=size;c<=cols;c++){\n int sum = preSum[r][c] - preSum[r-size][c] - preSum[r][c-size] + preSum[r-size][c-size];\n if(sum <= maxSum) return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxSideLength(vector>& mat, int threshold) {\n int m = mat.size();\n int n = mat[0].size();\n \n int least = min (m,n);\n \n vector> dp (m+1, vector (n+1, 0));\n \n /*\n create dp matrix with sum of all squares\n so for the following input matrix\n 1 1 1 1\n 1 0 0 0\n 1 0 0 0\n 1 0 0 0\n \n m = 4; n = 4; least = 4; threshold = 6\n you get the dp matrix to be:\n 0 0 0 0 0\n 0 1 2 3 4\n 0 2 3 4 5\n 0 3 4 5 6\n 0 4 5 6 7\n */\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n dp[i+1][j+1] = mat[i][j] + dp[i+1][j] + dp[i][j+1] - dp[i][j];\n }\n }\n \n int sum = 0;\n \n /*\n from the previous example the once we start looking from least = 4 to see if the sum is less than threshold\n for least = 4; sum = 7 - 0 - 0 + 0. (looking at the full 4 x 4 matrix) 7 is > threshold.. so keep looking..\n for least = 3; sum = 5 - 0 - 0 + 0. (looking at the 3 x 3 matrix) .. 5 < threshold.. return 3.\n \n say if the threshold was lower e.g. threshold = 2?\n continuing...\n for least = 3; sum = 6 - 3 - 0 + 0 = 3.\n for least = 3; sum = 6 - 0 - 3 + 0 = 3;\n for least = 3; sum = 7 - 4 - 4 + 1 = 0;\n \n */\n \n for(int k = least; k > 0; k--) {\n for(int i = k; i < m+1; i++) {\n for(int j = k; j < n+1; j++) {\n sum = dp[i][j] - dp[i-k][j] - dp[i][j-k] + dp[i-k][j-k];\n if(sum <= threshold) {\n return k;\n }\n }\n }\n }\n \n return 0;\n }\n};" }, { "title": "Longest Uncommon Subsequence II", "algo_input": "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.\n\nAn uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.\n\nA subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n\n\n\tFor example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"aebdc\" to get \"abc\". Other subsequences of \"aebdc\" include \"aebdc\", \"aeb\", and \"\" (empty string).\n\n\n \nExample 1:\nInput: strs = [\"aba\",\"cdc\",\"eae\"]\nOutput: 3\nExample 2:\nInput: strs = [\"aaa\",\"aaa\",\"aa\"]\nOutput: -1\n\n \nConstraints:\n\n\n\t2 <= strs.length <= 50\n\t1 <= strs[i].length <= 10\n\tstrs[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def findLUSlength(self, s: List[str]) -> int:\n def lcs(X, Y):\n m = len(X)\n n = len(Y)\n L = [[None]*(n + 1) for i in range(m + 1)]\n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0 or j == 0 :\n L[i][j] = 0\n elif X[i-1] == Y[j-1]:\n L[i][j] = L[i-1][j-1]+1\n else:\n L[i][j] = max(L[i-1][j], L[i][j-1])\n return L[m][n]\n \n k = 0 \n mp = {}\n for i in s:\n if len(i) not in mp:\n mp[len(i)] = [i]\n else:\n mp[len(i)].append(i)\n k = max(k , len(i))\n \n t = k\n while(k):\n if k not in mp:\n k -= 1\n else:\n curr = mp[k]\n n = len(curr)\n for i in range(n):\n f = 0\n for j in range(n):\n if(i != j and curr[i] == curr[j]):\n f = 1\n break\n if(not(f)):\n ff = 0 \n for j in range(k+1 , t+1):\n if(ff):break\n if(j not in mp): continue\n for jj in mp[j]:\n if(lcs(curr[i] , jj) == len(curr[i])):\n ff = 1\n break\n if(not(ff)):return len(curr[i])\n k-=1\n \n return -1\n\n \n\n ", "solution_js": "var findLUSlength = function(strs) {\n\tstrs.sort((a, b) => b.length - a.length);\n\tconst isSubsequence = (a, b) => {\n\t\tconst A_LENGTH = a.length;\n\t\tconst B_LENGTH = b.length;\n\t\tif (A_LENGTH > B_LENGTH) return false;\n\t\tif (a === b) return true;\n\t\tconst matches = [...b].reduce((pos, str) => {\n\t\t\treturn a[pos] === str ? pos + 1 : pos;\n\t\t}, 0);\n\t\treturn matches === A_LENGTH;\n\t}\n\n\tfor (let a = 0; a < strs.length; a++) {\n\t\tlet isUncommon = true;\n\n\t\tfor (let b = 0; b < strs.length; b++) {\n\t\t\tif (a === b) continue;\n\t\t\tif (isSubsequence(strs[a], strs[b])) {\n\t\t\t\tisUncommon = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (isUncommon) return strs[a].length;\n\n\t}\n\treturn -1;\n};", "solution_java": "class Solution {\n public int findLUSlength(String[] strs) {\n Arrays.sort(strs,(a,b) -> b.length() - a.length()); // sort descending order by length\n // store the frequency of all strings in array\n Map map = new HashMap<>();\n for(String s : strs) map.put(s,map.getOrDefault(s,0)+1);\n\n for(int i=0;i&strs,int index){\n for(int i=0;i& strs) {\n sort(strs.begin(),strs.end(),[](string &s,string &t){\n return s.size()>t.size();\n });\n int ans=-1;\n for(int i=0;i int:\n h1, h2, h3 = [], [], []\n heapq.heappush(h1, 1)\n heapq.heappush(h2, 1)\n heapq.heappush(h3, 1)\n ugly_number = 1\n last_ugly_number = 1\n count = 1\n while count < n:\n if 2 * h1[0] <= 3 * h2[0] and 2 * h1[0] <= 5 * h3[0]:\n # pop from h1\n x = heapq.heappop(h1)\n ugly_number = 2 * x\n if ugly_number == last_ugly_number:\n # do nothing\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n elif 3 * h2[0] <= 2 * h1[0] and 3 * h2[0] <= 5 * h3[0]:\n # pop from h2\n x = heapq.heappop(h2)\n ugly_number = 3 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n else:\n # pop from h3\n x = heapq.heappop(h3)\n ugly_number = 5 * x\n if ugly_number == last_ugly_number:\n continue\n count+=1\n last_ugly_number = ugly_number\n heapq.heappush(h1, ugly_number)\n heapq.heappush(h2, ugly_number)\n heapq.heappush(h3, ugly_number)\n\n return last_ugly_number", "solution_js": "var nthUglyNumber = function(n) {\nlet uglyNo = 1;\nlet uglySet = new Set(); // Set to keep track of all the ugly Numbers to stop repetition\nuglySet.add(uglyNo);\nlet minHeap = new MinPriorityQueue(); // Javascript provides inbuilt min and max heaps, constructor does not require callback function for primitive types but a comparator callback for object data types, to know which key corresponds to the priority\n//callback looks like this new MinPriorityQueue((bid) => bid.value)\n// if this is confusing, check the documentation here\n// https://github.com/datastructures-js/priority-queue/blob/master/README.md#constructor\nwhile(n>1){\n if(!uglySet.has(uglyNo*2)){// add only if the set does not have this ugly no.\n minHeap.enqueue(uglyNo*2,uglyNo*2);// enqueue takes two inputs element and priority respectively, both are same here\n uglySet.add(uglyNo*2);\n }\n if(!uglySet.has(uglyNo*3)){\n minHeap.enqueue(uglyNo*3,uglyNo*3);\n uglySet.add(uglyNo*3);\n }\n if(!uglySet.has(uglyNo*5)){\n minHeap.enqueue(uglyNo*5,uglyNo*5);\n uglySet.add(uglyNo*5);\n }\n uglyNo = minHeap.dequeue().element;//dequeue returns an object with two properties priority and element\n n--;\n}\n\nreturn uglyNo;\n};", "solution_java": "// Ugly number II\n// https://leetcode.com/problems/ugly-number-ii/\n\nclass Solution {\n public int nthUglyNumber(int n) {\n int[] dp = new int[n];\n dp[0] = 1;\n int i2 = 0, i3 = 0, i5 = 0;\n for (int i = 1; i < n; i++) {\n dp[i] = Math.min(dp[i2] * 2, Math.min(dp[i3] * 3, dp[i5] * 5));\n if (dp[i] == dp[i2] * 2) i2++;\n if (dp[i] == dp[i3] * 3) i3++;\n if (dp[i] == dp[i5] * 5) i5++;\n }\n return dp[n - 1];\n }\n}", "solution_c": "class Solution {\npublic:\n int nthUglyNumber(int n) {\n\n int dp[n+1];\n dp[1] = 1;\n\n int p2 = 1, p3 = 1, p5 = 1;\n int t;\n\n for(int i = 2; i < n+1; i++){\n t = min(dp[p2]*2, min(dp[p3]*3, dp[p5]*5));\n dp[i] = t;\n\n if(dp[i] == dp[p2]*2){\n p2++;\n }\n if(dp[i] == dp[p3]*3){\n p3++;\n }\n if(dp[i] == dp[p5]*5){\n p5++;\n }\n }\n return dp[n];\n\n }\n};" }, { "title": "Search in Rotated Sorted Array", "algo_input": "There is an integer array nums sorted in ascending order (with distinct values).\n\nPrior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].\n\nGiven the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n \nExample 1:\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutput: 4\nExample 2:\nInput: nums = [4,5,6,7,0,1,2], target = 3\nOutput: -1\nExample 3:\nInput: nums = [1], target = 0\nOutput: -1\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5000\n\t-104 <= nums[i] <= 104\n\tAll values of nums are unique.\n\tnums is an ascending array that is possibly rotated.\n\t-104 <= target <= 104\n\n", "solution_py": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n l, r = 0, len(nums) - 1\n \n while l<=r:\n mid = (l+r)//2\n if target == nums[mid]:\n return mid\n \n if nums[l]<=nums[mid]:\n if target > nums[mid] or target nums[r]:\n r = mid - 1\n else:\n l = mid + 1\n \n return -1", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n const len = nums.length;\n if (len === 1 && nums[0] === target) return 0;\n const h = nums.findIndex((val, i) => nums[i === 0 ? nums.length - 1 : i - 1] > val);\n if (h !== 0) nums = nums.slice(h).concat(nums.slice(0, h));\n // console.log(h, nums)\n let lo = 0, hi = len - 1;\n while (lo !== hi) {\n if (lo + 1 === hi) {\n if (nums[lo] === target) return (lo + h) % len;\n if (nums[hi] === target) return (hi + h) % len;\n break;\n }\n\n const i = Math.floor((lo + hi + 1) / 2);\n // console.log(lo, hi, i)\n const val = nums[i];\n if (val === target) return (i + h) % len;\n if (val > target) hi = i;\n else lo = i;\n }\n\n return -1;\n};", "solution_java": "class Solution {\n public int search(int[] nums, int target) {\n int pivot = findPivot(nums);\n int ans = binarySearch(nums, target, 0, pivot);\n if(ans!=-1){\n return ans;\n }\n return binarySearch(nums, target, pivot+1, nums.length-1);\n }\n \n public int findPivot(int[] arr){\n int start = 0, end = arr.length-1;\n while(start<=end){\n int mid = start + (end-start)/2;\n if(midarr[mid+1]){\n return mid;\n }\n if(mid>start && arr[mid-1]>arr[mid]){\n return mid-1;\n }\n if(arr[mid]<=arr[start]){\n end = mid-1;\n }else{\n start = mid+1;\n }\n }\n return -1;\n }\n \n public int binarySearch(int[] arr, int target, int start, int end){\n \n while(start<=end){\n int mid = start+ (end-start)/2;\n \n \n if(targetarr[mid]){\n start = mid+1;\n }else{\n return mid;\n }\n \n \n }\n return -1;\n }\n \n}", "solution_c": "class Solution \n{\npublic:\n int search(vector& nums, int target) \n {\n int n=nums.size()-1;\n if(nums[0]==target)\n return 0;\n if(nums.size()==1)\n return -1; \n // find the index of the minimum element ie pivot\n int pivot=-1;\n int low=0;\n int high=n;\n while(low<=high)\n {\n int mid=(low+high)/2;\n if(mid==0)\n {\n if(nums[mid]< nums[mid+1] && nums[mid]< nums[n])\n {\n pivot=mid;\n break;\n }\n else\n {\n low=mid+1;\n }\n }\n \n else if(mid==n)\n {\n if(nums[mid] < nums[0] && nums[mid] < nums[mid-1])\n {\n pivot=mid;\n break;\n }\n else \n {\n high=mid-1;\n }\n }\n else if(nums[mid]=nums[0] && nums[mid]<=nums[n])\n high=mid-1;\n else if(nums[mid] >= nums[0])\n low=mid+1;\n else if(nums[mid] < nums[0])\n high=mid-1;\n }\n cout< target)\n high1=mid1-1;\n else if(nums[mid1] nums[0])\n {\n int low2=0;\n int high2=pivot-1;\n if(pivot==0)\n {\n low2=0;\n high2=n;\n }\n while(low2<=high2)\n {\n int mid2=(low2+high2)/2;\n if(nums[mid2]==target)\n return mid2;\n else if(nums[mid2] > target)\n high2=mid2-1;\n else if(nums[mid2] we don't want to return -42; hence check\n if not self.is_neg and not self.is_pos:\n # no sign has been set yet\n if sign==\"+\":\n self.is_pos = True\n elif sign==\"-\":\n self.is_neg = True\n return\n\n def add_to_int(self, num):\n if not self.num:\n self.num = num\n else:\n self.num = (self.num*10) + num\n\n def myAtoi(self, s: str) -> int:\n # remove the leading and trailing spaces\n self.is_neg = False\n self.is_pos = False\n self.num = None\n s=s.strip()\n for i in s:\n # ignore the rest of the string if a non digit character is read\n if i in (\"+\",\"-\"):\n # only read the first symbol; break if second symbol is read\n if self.is_pos or self.is_neg or isinstance(self.num, int):\n # one of the two symbols is read or a number is read\n break\n self.assign_sign(i)\n continue\n try:\n i = int(i)\n self.add_to_int(i)\n except ValueError:\n # it's neither a sign, nor a number; terminate\n break\n\n # outside the loop; compile the result\n if not self.num:\n return 0\n upper_limit = 2**31 - 1\n if self.is_pos or (not self.is_pos and not self.is_neg):\n if self.num > upper_limit:\n self.num = upper_limit\n elif self.is_neg:\n if self.num > upper_limit+1:\n self.num = upper_limit+1\n self.num = -1 * self.num\n return self.num", "solution_js": "const toNumber = (s) => {\n let res = 0;\n for (let i = 0; i < s.length; i++) {\n res = res * 10 + (s.charCodeAt(i) - '0'.charCodeAt(0));\n }\n \n return res\n}\n\nvar myAtoi = function(s) {\n s = s.trim();\n let r = s.match(/^(\\d+|[+-]\\d+)/);\n \n if (r) {\n let m = r[0], res;\n switch (m[0]) {\n case \"-\":\n res = toNumber(m.slice(1)) * -1;\n break;\n case '+':\n res = toNumber(m.slice(1));\n break;\n default:\n res = toNumber(m);\n break;\n }\n \n if (res < (1 << 31)) return (1 << 31);\n if (res > -(1 << 31) - 1) return -(1 << 31) - 1;\n return res;\n }\n \n return 0;\n};", "solution_java": "class Solution {\n public int myAtoi(String s) {\n long n=0;\n int i=0,a=0;\n s=s.trim();\n if(s.length()==0)\n return 0;\n if(s.charAt(i)=='+' || s.charAt(i)=='-')\n a=1;\n while(a='0' && s.charAt(i)<='9')\n n=n*10+(int)(s.charAt(i)-'0');\n else\n break;\n }\n if(s.charAt(0)=='-')\n n=-n;\n if(n>2147483647)\n n=2147483647;\n if(n<-2147483648)\n n=-2147483648;\n return (int)n;\n }\n}", "solution_c": "class Solution\n{\n public:\n int myAtoi(string s)\n {\n long long ans = 0;\n int neg = 1;\n int i = 0;\n while (i < s.length() and s[i] == ' ')\n {\n i++;\n }\n\n if (s[i] == '-' || s[i] == '+')\n {\n neg = s[i] == '-' ? -1 : 1;\n i++;\n }\n\n while (i < s.length() && (s[i] >= '0' && s[i] <= '9'))\n {\n\n ans = ans *10 + (s[i] - '0');\n \t// ans *= 10;\n i++;\n if (ans * neg >= INT_MAX) return INT_MAX;\n if (ans * neg <= INT_MIN) return INT_MIN;\n }\n return ans * neg;\n }\n};" }, { "title": "Jump Game", "algo_input": "You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.\n\nReturn true if you can reach the last index, or false otherwise.\n\n \nExample 1:\n\nInput: nums = [2,3,1,1,4]\nOutput: true\nExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\nExample 2:\n\nInput: nums = [3,2,1,0,4]\nOutput: false\nExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def canJump(self, nums: List[int]) -> bool:\n \"\"\"\n # Memoization + DFS Solution\n # TLE as we have as much as n decisions depending on nums[i] which could be\n # 10^5 as an uppercase according to problem constraints\n # better off with a greedy approach\n\n cache = {} # i : bool\n\n def dfs(i):\n if i == len(nums) -1:\n return True\n if nums[i] == 0:\n return False\n if i in cache:\n return cache[i]\n for j in range(1, nums[i] + 1):\n res = dfs(i + j)\n if res:\n cache[i] = True\n return cache[i]\n cache[i] = False\n return cache[i]\n\n return dfs(0)\n \"\"\"\n # Greedy Solution\n # Key with greedy is to find a local and gobal optimum\n # here we find the furthest distance we can travel with each index\n\n # futhest index reachable\n reachable = 0\n\n # iterate through all indexes and if the current index is futher than what we can travel return fasle\n for i in range(len(nums)):\n if i > reachable:\n return False\n\n reachable = max(reachable, nums[i] + i)\n # if the futherest distance we can jump to is greater or equal than the last index break\n if reachable >= len(nums) - 1:\n break\n\n return True", "solution_js": "var canJump = function(nums) {\n let target = nums.length-1;\n let max = 0,index = 0;\n\n while(index <= target){\n max = Math.max(max,index + nums[index]);\n\n if(max >= target) return true;\n\n if(index >= max && nums[index] === 0) return false;\n\n index++;\n }\n\n return false;\n};", "solution_java": "class Solution {\n public boolean canJump(int[] nums)\n {\n int maxjump = 0;\n for(int i=0;i& nums) {\n int ans = nums[0];\n if(nums.size()>1&&ans==0) return false;\n for(int i=1; i=target:\n if summ == target:\n res.append(curr)\n return\n for i in range(len(nums)):\n if i !=0 and nums[i]==nums[i-1]:\n continue\n dfs(nums[i+1:],summ+nums[i],curr+[nums[i]])\n dfs(sorted(candidates),0,[])\n return res", "solution_js": "/**\n * @param {number[]} candidates\n * @param {number} target\n * @return {number[][]}\n */\nvar combinationSum2 = function(candidates, target) {\n candidates.sort((a, b) => a - b);\n \n const ans = [];\n \n function dfs(idx, t, st) {\n if (t === 0) {\n ans.push(Array.from(st));\n return;\n }\n for (let i = idx; i < candidates.length; i++) {\n if (i > idx && candidates[i - 1] === candidates[i]) continue;\n if (candidates[i] > t) break;\n st.push(candidates[i]);\n dfs(i + 1, t - candidates[i], st);\n st.pop();\n }\n }\n \n dfs(0, target, []);\n \n return ans;\n};", "solution_java": "class Solution {\n public List> combinationSum2(int[] candidates, int target) {\n List> res = new ArrayList<>();\n List path = new ArrayList<>();\n // O(nlogn)\n Arrays.sort(candidates);\n boolean[] visited = new boolean[candidates.length];\n helper(res, path, candidates, visited, target, 0);\n return res;\n }\n private void helper(List> res,\n List path, int[] candidates,\n boolean[] visited, int remain, int currIndex\n ){\n if (remain == 0){\n res.add(new ArrayList<>(path));\n return;\n }\n if (remain < 0){\n return;\n }\n\n for(int i = currIndex; i < candidates.length; i++){\n if (visited[i]){\n continue;\n }\n if (i > 0 && candidates[i] == candidates[i - 1] && !visited[i - 1]){\n continue;\n }\n int curr = candidates[i];\n path.add(curr);\n visited[i] = true;\n helper(res, path, candidates, visited, remain - curr, i + 1);\n path.remove(path.size() - 1);\n\n visited[i] = false;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n vector> ans;vector temp;\n void f(vector& nums,int target,int i){\n if(target==0){\n ans.push_back(temp);\n return;\n }\n if(i>=nums.size())\n return;\n if(nums[i]<=target){\n temp.push_back(nums[i]);\n f(nums,target-nums[i],i+1);\n temp.pop_back();\n while(i> combinationSum2(vector& candidates, int target) {\n sort(candidates.begin(),candidates.end());\n f(candidates,target,0);\n return ans;\n }\n};" }, { "title": "Constrained Subsequence Sum", "algo_input": "Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.\n\nA subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n\n \nExample 1:\n\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\n\nExample 2:\n\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\n\nExample 3:\n\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\n\n \nConstraints:\n\n\n\t1 <= k <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\n", "solution_py": "class Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n deque = []\n for i, num in enumerate(nums):\n \n while(deque and deque[0] < i - k): # delete that didn't end with a number in A[i-k:i]\n deque.pop(0)\n \n if deque: # compute the max sum we can get at index i\n nums[i] = nums[deque[0]] + num\n \n while(deque and nums[deque[-1]] < nums[i]): \n # delet all the sequence that smaller than current sum, becaus there will never be\n # considers ==> smaller than current sequence, and end before current sequence\n deque.pop()\n \n if nums[i] > 0: # if nums[i] < 0, it can't be a useful prefix sum \n \tdeque.append(i)\n \n return max(nums)", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar constrainedSubsetSum = function(nums, k) {\n const queue = [[0, nums[0]]];\n let max = nums[0];\n for (let i = 1; i < nums.length; i++) {\n const cur = queue.length ? nums[i] + Math.max(0, queue[0][1]) : nums[i];\n max = Math.max(max, cur);\n while(queue.length && queue[queue.length-1][1] < cur) queue.pop();\n queue.push([i, cur]);\n while(queue.length && queue[0][0] <= i-k) queue.shift();\n }\n return max;\n};", "solution_java": "class Solution {\n public int constrainedSubsetSum(int[] nums, int k) {\n int n=nums.length;\n int[] dp=new int[n];\n int res=nums[0];\n Queue queue=new PriorityQueue<>((a,b)->dp[b]-dp[a]); //Declaring Max heap\n\n Arrays.fill(dp,Integer.MIN_VALUE);\n dp[0]=nums[0];\n queue.offer(0);\n\n for(int j=1;j& nums, int k) {\n priority_queue> que;\n int ret = nums[0], curr;\n que.push({nums[0], 0});\n for (int i = 1; i < nums.size(); i++) {\n while (!que.empty() && que.top()[1] < i - k) {\n que.pop();\n }\n curr = max(0, que.top()[0]) + nums[i];\n ret = max(ret, curr);\n que.push({curr, i});\n }\n return ret;\n }\n};" }, { "title": "Minimum Distance to the Target Element", "algo_input": "Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.\n\nReturn abs(i - start).\n\nIt is guaranteed that target exists in nums.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4,5], target = 5, start = 3\nOutput: 1\nExplanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n\n\nExample 2:\n\nInput: nums = [1], target = 1, start = 0\nOutput: 0\nExplanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\n\n\nExample 3:\n\nInput: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput: 0\nExplanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 104\n\t0 <= start < nums.length\n\ttarget is in nums.\n\n", "solution_py": "class Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n if nums[start] == target: return 0\n left, right = start-1, start+1\n N = len(nums)\n while True:\n if left >=0 and nums[left] == target:\n return start - left\n if right < N and nums[right] == target:\n return right - start\n left -= 1\n right += 1", "solution_js": "var getMinDistance = function(nums, target, start) {\n let min = Infinity;\n for(let i=nums.indexOf(target);i& nums, int target, int start){\n int ans = INT_MAX;\n for(int i = 0; i < nums.size(); i++){\n int temp = 0;\n if (nums[i] == target){\n temp = abs(i - start);\n if (temp < ans){\n ans = temp;\n }\n }\n }\n return ans;\n }\n};" }, { "title": "Number of Boomerangs", "algo_input": "You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).\n\nReturn the number of boomerangs.\n\n \nExample 1:\n\nInput: points = [[0,0],[1,0],[2,0]]\nOutput: 2\nExplanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\n\n\nExample 2:\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 2\n\n\nExample 3:\n\nInput: points = [[1,1]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tn == points.length\n\t1 <= n <= 500\n\tpoints[i].length == 2\n\t-104 <= xi, yi <= 104\n\tAll the points are unique.\n\n", "solution_py": "class Solution:\n def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n def sq(a):\n return a * a\n\n def euclid(a, b, c, d):\n dist = sq(a - c) + sq(b - d)\n return sq(dist)\n\n n = len(points)\n res = 0\n for i in range(n):\n count = defaultdict(lambda : 0)\n for j in range(n):\n d = euclid(points[i][0], points[i][1], points[j][0], points[j][1])\n res += count[d] * 2\n count[d] += 1\n\n return res", "solution_js": "var numberOfBoomerangs = function(points) {\n\tconst POINTS_LEN = points.length;\n\tlet result = 0;\n\n\tfor (let i = 0; i < POINTS_LEN; i++) {\n\t\tconst hash = new Map();\n\n\t\tfor (let j = 0; j < POINTS_LEN; j++) {\n\t\t\tif (i === j) continue;\n\t\t\tconst [x1, y1] = points[i];\n\t\t\tconst [x2, y2] = points[j];\n\t\t\tconst dis = Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);\n\t\t\tconst value = hash.get(dis) ?? 0;\n\n\t\t\tif (value > 0) result += value * 2;\n\t\t\thash.set(dis, value + 1);\n\t\t}\n\t}\n\n\treturn result;\n};", "solution_java": "class Solution {\n public int numberOfBoomerangs(int[][] points) {\n \n int answer = 0;\n \n for (int p=0; p hm = new HashMap();\n \n for (int q=0;q 0) {\n if (hm.containsKey(distance)) {\n hm.put(distance, hm.get(distance) + 1);\n } else {\n hm.put(distance, 1);\n }\n }\n \n }\n \n for (Double dist : hm.keySet()) {\n int occ = hm.get(dist);\n if (occ > 1) {\n answer = answer + ((occ) * (occ - 1));\n }\n }\n }\n \n return answer;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfBoomerangs(vector>& points) {\n\n int cnt = 0, n = points.size();\n for(int i = 0; i < n; i++)\n {\n map mp;\n for(int j = 0; j < n; j++)\n {\n if(i == j)\n continue;\n\n int tmp = findDistance(points[i], points[j]);\n if(mp.find(tmp) != mp.end())\n cnt += mp[tmp] * 2; // 2 is multiplied bcoz the order of j & k can be k & j also\n\n mp[tmp]++;\n }\n }\n\n return cnt;\n }\n\n int findDistance(vector &p1, vector &p2)\n {\n return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);\n }\n};" }, { "title": "Sum of Distances in Tree", "algo_input": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n\nYou are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\n\nReturn an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.\n\n \nExample 1:\n\nInput: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput: [8,12,6,10,10,10]\nExplanation: The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.\n\n\nExample 2:\n\nInput: n = 1, edges = []\nOutput: [0]\n\n\nExample 3:\n\nInput: n = 2, edges = [[1,0]]\nOutput: [1,1]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 3 * 104\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 <= ai, bi < n\n\tai != bi\n\tThe given input represents a valid tree.\n\n", "solution_py": "from typing import List\n\nROOT_PARENT = -1\n\nclass Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n @see https://leetcode.com/problems/sum-of-distances-in-tree/discuss/130583/C%2B%2BJavaPython-Pre-order-and-Post-order-DFS-O(N)\n :param n:\n :param edges:\n :return:\n \"\"\"\n g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree\n\n root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)\n\n # considering \"root\" as starting node, we create a tree.\n # Now defining,\n # tree_nodes[i] = number of nodes in the tree rooted at node i\n # distances[i] = sum of distances of all nodes from ith node to all the\n # other nodes of the tree\n tree_nodes, distances = [0] * n, [0] * n\n\n def postorder(rt: int, parent: int):\n \"\"\"\n updating tree_nodes and distances from children of rt. To update them, we must know their\n values at children. And that is why post order traversal is used\n\n After the traversal is done,\n tree_nodes[rt] = all the nodes in tree rooted at rt\n distances[rt] = sum of distances from rt to all the nodes of tree rooted at rt\n\n :param rt:\n :param parent:\n \"\"\"\n tree_nodes[rt] = 1\n\n for c in g[rt]:\n if c != parent:\n postorder(c, rt)\n\n # adding number of nodes in subtree rooted at c to tree rooted at rt\n tree_nodes[rt] += tree_nodes[c]\n\n # moving to rt from c will increase distances by nodes in tree rooted at c\n distances[rt] += distances[c] + tree_nodes[c]\n\n def preorder(rt: int, parent: int):\n \"\"\"\n we start with \"root\" and update its children.\n distances[root] = sum of distances between root and all the other nodes in tree.\n\n In this function, we calculate distances[c] with the help of distances[root] and\n that is why preorder traversal is required.\n :param rt:\n :param parent:\n :return:\n \"\"\"\n for c in g[rt]:\n if c != parent:\n distances[c] = (\n (n - tree_nodes[c]) # rt -> c increase this much distance\n +\n (distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance\n )\n preorder(c, rt)\n\n postorder(root, ROOT_PARENT)\n preorder(root, ROOT_PARENT)\n\n return distances\n\n @staticmethod\n def create_undirected_graph(edges: List[List[int]], n: int):\n \"\"\"\n :param edges:\n :param n:\n :return: graph from edges. Note that this undirect graph is a tree. (Any node can be\n picked as root node)\n \"\"\"\n g = [[] for _ in range(n)]\n\n for u, v in edges:\n g[u].append(v)\n g[v].append(u)\n\n return g", "solution_js": "var sumOfDistancesInTree = function(n, edges) {\n let graph = {};\n for (let [start, end] of edges) {\n if (!graph[start]) graph[start] = [];\n if (!graph[end]) graph[end] = [];\n graph[start].push(end);\n graph[end].push(start);\n }\n \n let visited = new Set(), distanceFromZero = 0, totalChildren = {};\n // Find the sum distance from node O to all other nodes and the total children of each node\n function dfs(node, sum = 0) {\n visited.add(node);\n distanceFromZero += sum;\n if (!graph[node]) return;\n let child = 0;\n for (let nextNode of graph[node]) {\n if (visited.has(nextNode)) continue;\n child += dfs(nextNode, sum + 1);\n }\n totalChildren[node] = child;\n return child + 1;\n }\n dfs(0);\n\n let dp = [distanceFromZero];\n visited = new Set();\n function findDistance(node) {\n visited.add(node);\n if (!graph[node]) return;\n for (let nextNode of graph[node]) {\n if (visited.has(nextNode)) {\n dp[node] = dp[nextNode] + (n - 2);\n break;\n }\n }\n if (node !== 0 && totalChildren[node]) dp[node] -= totalChildren[node] * 2;\n for (let nextNode of graph[node]) {\n if (visited.has(nextNode)) continue;\n else findDistance(nextNode);\n }\n }\n\n findDistance(0);\n return dp;\n};", "solution_java": "class Solution {\n private Map> getGraph(int[][] edges) {\n Map> graph = new HashMap<>();\n for(int[] edge: edges) {\n graph.putIfAbsent(edge[0], new LinkedList<>());\n graph.putIfAbsent(edge[1], new LinkedList<>());\n \n graph.get(edge[0]).add(edge[1]);\n graph.get(edge[1]).add(edge[0]); \n }\n \n return graph;\n }\n \n public int[] sumOfDistancesInTree(int n, int[][] edges) { \n if(n < 2 || edges == null) {\n return new int[]{0};\n }\n \n int[] countSubNodes = new int[n];\n Arrays.fill(countSubNodes, 1);\n int[] distances = new int[n];\n Map> graph = getGraph(edges);\n postOrderTraversal(0, -1, countSubNodes, distances, graph);\n preOrderTraversal(0, -1, countSubNodes, distances, graph, n);\n return distances;\n }\n \n private void postOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n postOrderTraversal(child, node, countSubNodes, distances, graph);\n countSubNodes[node] += countSubNodes[child];\n distances[node] += distances[child] + countSubNodes[child];\n }\n }\n }\n \n private void preOrderTraversal(int node, int parent, int[] countSubNodes, int[] distances, Map> graph, int n) {\n List children = graph.get(node);\n for(int child: children) {\n if(child != parent) {\n\t\t\t\tdistances[child] = distances[node] + (n - countSubNodes[child]) - countSubNodes[child];\n\t\t\t\tpreOrderTraversal(child, node, countSubNodes, distances, graph, n); \n }\n }\n }\n}``", "solution_c": "/*\n \n Finding sum of distance from ith node to all other nodes takes O(n), so it will take O(n^2)\n if done naively to find distance for all.\n \n x---------------------y\n / \\ \\\n o o o\n / / \\ \n o o o\n \n Above is a graph where x and y are subtrees with them as the root. They both are neighbors\n and are connected by an edge.\n \n From x's POV\n x\n / | \\ \n o o y \n / \\ \n o o \n / \\\n o o\n \n From y's POV\n y \n / \\ \n x o \n / | / \\\n o o o o\n /\n o \n \n As evident froma above, the tree structure looks different when we change the root of tree.\n So even if we find the sum of distance for node 0 as root, the subanswers are actually not correct\n for other nodes when they are the root of tree. The subanswers are only correct when node 0 is root,\n since that is how it was computed.\n \n We use something called re-rooting, this allows us to find a relation so that we can change the root of the tree\n and use the answer from its neighbor to compute answer for it.\n So if we compute the answer for node 0 as root, we can find the answers for its children, then those children can \n be used to compute for their neighbors and so on.\n \n For the 1st diagram:\n distance[x] = sum(x) + sum(y) + count(y)\n \n distance[x] is the overall sum of distance with root as x\n sum(i) is the sum of distance of all the descendents for a subtree rooted at i\n count(i) is the no. of descendent nodes in the subtree rooted at i\n \n Now why count(y) ?\n Consider a node z in subtree y, dist(x, z) = dist(y, z) + 1\n So sum(y) already accounts for dist(y, z) and we just need to add 1\n So if there are n_y nodes in the subtree, we need to add +1 that many times.\n \n distance[x] = sum(x) + sum(y) + count(y) -----------------1\n distance[y] = sum(y) + sum(x) + count(x) -----------------2\n \n From (1) - (2)\n distance[x] - distance[y] = count(y) - count(x) ----------3\n distance[x] = distance[y] - count(x) + count(y)\n \n Above relation can be used to find the answer for a neighbor, when the answer for\n the other neighbor is known.\n \n In our case, we can compute the answer for node 0 as root in one traversal of post order.\n Then in another traversal with again root as 0, compute the answer for its children and from\n them to their children nodes and so on.\n \n distance[child] = distance[parent] - count(child) + (N - count(child))\n Since we also know the no. of nodes in subtree with child as root, the remaining nodes = (N - count(child))\n \n \n Re-rooting Ref: https://leetcode.com/problems/sum-of-distances-in-tree/solution/\n \n TC: O(N)\n SC: O(N)\n*/\nclass Solution {\nprivate:\n int n = 0;\n // subtree_distance[i] = Sum of distance to other nodes when the ith-node is root\n vector subtree_distance;\n // subtree_count[i] = no. of nodes in the subtree with ith-node as root\n vector subtree_count;\npublic:\n void postorder(int root, int parent, vector>& graph) {\n // Perform DFS for the child nodes\n for(auto child: graph[root]) {\n // Avoid iterating to the parent, it will create a loop otherwise\n if(child != parent) {\n postorder(child, root, graph);\n // Update the subtree count and sum of distance\n subtree_count[root] += subtree_count[child];\n // distance[X] = distance[X] + distance[Y] + n_Y\n subtree_distance[root] += subtree_distance[child] + subtree_count[child];\n }\n }\n }\n \n void preorder(int root, int parent, vector>& graph) {\n for(auto child: graph[root]) {\n if(child != parent) {\n // distance[child] = distance[parent] - count[child] + count(parent)\n subtree_distance[child] = subtree_distance[root] - subtree_count[child] + (n - subtree_count[child]);\n preorder(child, root, graph);\n }\n }\n }\n \n vector reRootingSol(int n, vector>& edges) {\n // create an undirected graph\n vector > graph(n);\n for(auto edge: edges) {\n int src = edge[0], dst = edge[1];\n graph[src].emplace_back(dst);\n graph[dst].emplace_back(src);\n }\n \n this->n = n;\n this->subtree_count.resize(n, 1);\n this->subtree_distance.resize(n, 0);\n \n // This computes the subtree sum and subtree node count when 0 is the root of graph\n // Imagine looking at the graph from node 0's POV\n postorder(0, -1, graph);\n // Since we have computed the sum distance from node's POV, we can use that information\n // to find the sum of distance from each node's POV i.e imagine looking at the graph from\n // POV of each node\n preorder(0, -1, graph);\n return this->subtree_distance;\n }\n \n vector sumOfDistancesInTree(int n, vector>& edges) {\n return reRootingSol(n, edges);\n }\n};" }, { "title": "Number of Orders in the Backlog", "algo_input": "You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:\n\n\n\t0 if it is a batch of buy orders, or\n\t1 if it is a batch of sell orders.\n\n\nNote that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.\n\nThere is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:\n\n\n\tIf the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.\n\tVice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.\n\n\nReturn the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\nOutput: 6\nExplanation: Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.\n\n\nExample 2:\n\nInput: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\nOutput: 999999984\nExplanation: Here is what happens with the orders:\n- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).\n\n\n \nConstraints:\n\n\n\t1 <= orders.length <= 105\n\torders[i].length == 3\n\t1 <= pricei, amounti <= 109\n\torderTypei is either 0 or 1.\n", "solution_py": "class Solution:\n def getNumberOfBacklogOrders(self, orders):\n b, s = [], []\n heapq.heapify(b)\n heapq.heapify(s)\n \n for p,a,o in orders:\n if o == 0:\n heapq.heappush(b, [-p, a])\n \n elif o == 1:\n heapq.heappush(s, [p, a])\n \n # Check \"good\" condition\n while s and b and s[0][0] <= -b[0][0]:\n a1, a2 = b[0][1], s[0][1]\n \n if a1 > a2:\n b[0][1] -= a2\n heapq.heappop(s)\n elif a1 < a2:\n s[0][1] -= a1\n heapq.heappop(b)\n else:\n heapq.heappop(b)\n heapq.heappop(s)\n \n count = sum([a for p,a in b]) + sum([a for p,a in s])\n return count % (10**9 + 7)", "solution_js": "var getNumberOfBacklogOrders = function(orders) {\n const buyHeap = new Heap((child, parent) => child.price > parent.price)\n const sellHeap = new Heap((child, parent) => child.price < parent.price)\n \n for (let [price, amount, orderType] of orders) {\n \n // sell\n if (orderType) {\n \n // while there are amount to be decremented from the sell,\n // orders to in the buy backlog, and the price of the largest\n // price is greater than the sell price decrement the\n // amount of the order with the largest price by the amount\n while (amount > 0 && buyHeap.peak() && buyHeap.peak().price >= price) {\n if (buyHeap.peak().amount > amount) {\n buyHeap.peak().amount -= amount\n amount = 0\n } else {\n amount -= buyHeap.pop().amount\n }\n }\n \n // if there is any amount left, add it to the sale backlog\n if (amount) {\n sellHeap.push({ price, amount })\n }\n\n // buy\n } else {\n \n // while there are amount to be decremented from the buy,\n // orders to in the sell backlog, and the price of the smallest\n // price is less than the buy price decrement the\n // amount of the order with the smallest price by the amount\n while (amount > 0 && sellHeap.peak() && sellHeap.peak().price <= price) {\n if (sellHeap.peak().amount > amount) {\n sellHeap.peak().amount -= amount\n amount = 0\n } else {\n amount -= sellHeap.pop().amount;\n }\n }\n \n // if there is any amount left, add it to the buy backlog\n if (amount) {\n buyHeap.push({ price, amount })\n }\n }\n }\n \n // total all of the amounts in both backlogs and return the result\n let accumultiveAmount = 0;\n for (const { amount } of buyHeap.store) {\n accumultiveAmount += amount;\n }\n for (const { amount } of sellHeap.store) {\n accumultiveAmount += amount;\n }\n return accumultiveAmount % 1000000007\n};\n\nclass Heap {\n constructor(fn) {\n this.store = [];\n this.fn = fn;\n }\n \n peak() {\n return this.store[0];\n }\n \n size() {\n return this.store.length;\n }\n \n pop() {\n if (this.store.length < 2) {\n return this.store.pop();\n }\n const result = this.store[0];\n this.store[0] = this.store.pop();\n this.heapifyDown(0);\n return result;\n }\n \n push(val) {\n this.store.push(val);\n this.heapifyUp(this.store.length - 1);\n }\n \n heapifyUp(child) {\n while (child) {\n const parent = Math.floor((child - 1) / 2);\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n child = parent;\n } else {\n return child;\n }\n }\n }\n \n heapifyDown(parent) {\n while (true) {\n let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n if (this.shouldSwap(child2, child)) {\n child = child2\n }\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n parent = child;\n } else {\n return parent;\n }\n }\n }\n \n shouldSwap(child, parent) {\n return child && this.fn(this.store[child], this.store[parent]);\n }\n}", "solution_java": "class Solution {\n \n PriorityQueue buyBackLog;\n PriorityQueue sellBackLog;\n \n static int MOD = 1_000_000_007;\n \n \n public int getNumberOfBacklogOrders(int[][] orders) {\n \n //max heap, heapify on price\n buyBackLog = new PriorityQueue((a, b) -> (b.price - a.price));\n //min heap, heapify on price\n sellBackLog = new PriorityQueue((a, b) -> (a.price - b.price));\n \n \n //handle all order\n for(int[] order : orders){\n int price = order[0];\n int quantity = order[1];\n int orderType = order[2];\n \n if(orderType == 0){\n //buy order \n handleBuyOrder(new Order(price, quantity));\n \n }else if(orderType == 1){ \n //sell order\n handleSellOrder(new Order(price, quantity));\n }\n }\n \n long counts = 0L;\n \n //count buy backlog\n while(!buyBackLog.isEmpty()){\n counts += buyBackLog.remove().quantity; \n counts %= MOD;\n }\n \n //count sell backlog\n while(!sellBackLog.isEmpty()){\n counts += sellBackLog.remove().quantity; \n counts %= MOD;\n }\n \n \n return (int) (counts % MOD);\n }\n \n \n \n \n private void handleBuyOrder(Order buyOrder){\n //just add buyorder, if there is no sell back log\n if(sellBackLog.isEmpty()){\n buyBackLog.add(buyOrder);\n return;\n }\n \n \n while(!sellBackLog.isEmpty() && buyOrder.price >= sellBackLog.peek().price && buyOrder.quantity > 0){\n //selloder with minumum price\n Order sellOrder = sellBackLog.remove();\n \n if(buyOrder.quantity >= sellOrder.quantity){\n buyOrder.quantity -= sellOrder.quantity;\n sellOrder.quantity = 0;\n } else {\n //decrement sell order, add remaining sellorder\n sellOrder.quantity -= buyOrder.quantity;\n sellBackLog.add(sellOrder);\n \n buyOrder.quantity = 0;\n }\n }\n \n //add reaming buyorder\n if(buyOrder.quantity > 0){\n buyBackLog.add(buyOrder);\n }\n }\n \n \n private void handleSellOrder(Order sellOrder){\n //just add sell order, if there is no buy backlog\n if(buyBackLog.isEmpty()){\n sellBackLog.add(sellOrder);\n return;\n }\n \n \n while(!buyBackLog.isEmpty() && buyBackLog.peek().price >= sellOrder.price && sellOrder.quantity > 0){\n //buy order with maximum price\n Order buyOrder = buyBackLog.remove();\n \n if(sellOrder.quantity >= buyOrder.quantity){\n sellOrder.quantity -= buyOrder.quantity;\n buyOrder.quantity = 0;\n \n }else{\n //decrement buy order quantity, add remaining buyorder\n buyOrder.quantity -= sellOrder.quantity;\n buyBackLog.add(buyOrder);\n \n sellOrder.quantity = 0;\n }\n }\n \n //add remaining sell order\n if(sellOrder.quantity > 0){\n sellBackLog.add(sellOrder);\n }\n }\n}\n\nclass Order{\n int price;\n int quantity;\n \n public Order(int price, int quantity){\n this.price = price;\n this.quantity = quantity;\n }\n}", "solution_c": "class Solution {\npublic:\n int getNumberOfBacklogOrders(vector>& orders) {\n int n = orders.size();\n //0 - buy , 1 - sell; \n priority_queue> buyBacklog;\n priority_queue , vector> , greater>> sellBacklog;\n \n for(auto order : orders) {\n if(order[2] == 0) \n buyBacklog.push(order);\n else \n sellBacklog.push(order);\n \n while(!buyBacklog.empty() && !sellBacklog.empty() && sellBacklog.top()[0] <= buyBacklog.top()[0]) {\n auto btop = buyBacklog.top();\n buyBacklog.pop();\n auto stop = sellBacklog.top();\n sellBacklog.pop();\n int diff = btop[1] - stop[1];\n if(diff > 0) {\n btop[1] = diff;\n buyBacklog.push(btop);\n }\n else if(diff<0) {\n stop[1] = abs(diff);\n sellBacklog.push(stop);\n }\n }\n }\n \n int ans = 0 , mod = 1e9+7;\n while(!buyBacklog.empty()){\n ans = (ans +buyBacklog.top()[1])%mod;\n buyBacklog.pop();\n }\n while(!sellBacklog.empty()){\n ans = (ans+ sellBacklog.top()[1])%mod;\n sellBacklog.pop();\n }\n return ans;\n }\n};" }, { "title": "Minimum Deletions to Make Character Frequencies Unique", "algo_input": "A string s is called good if there are no two different characters in s that have the same frequency.\n\nGiven a string s, return the minimum number of characters you need to delete to make s good.\n\nThe frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1.\n\n \nExample 1:\n\nInput: s = \"aab\"\nOutput: 0\nExplanation: s is already good.\n\n\nExample 2:\n\nInput: s = \"aaabbbcc\"\nOutput: 2\nExplanation: You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".\n\nExample 3:\n\nInput: s = \"ceabaacb\"\nOutput: 2\nExplanation: You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\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 minDeletions(self, s: str) -> int:\n # Get the frequency of each character sorted in reverse order\n frequencies = sorted(Counter(s).values(), reverse=True)\n \n total_deletions = 0\n next_unused_freq = len(s)\n for freq in frequencies:\n # It is impossible for the frequency to be higher\n next_unused_freq = min(next_unused_freq, freq)\n total_deletions += freq - next_unused_freq\n\n # We cannot have another character with this frequency,\n # so decrement next_unused_freq\n if next_unused_freq > 0:\n next_unused_freq -= 1\n\n return total_deletions", "solution_js": "var minDeletions = function(s) {\n let freq = new Array(26).fill(0); // Create an array to store character frequencies\n \n for (let i = 0; i < s.length; i++) {\n freq[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; // Count the frequency of each character\n }\n \n freq.sort((a, b) => a - b); // Sort frequencies in ascending order\n \n let del = 0; // Initialize the deletion count\n \n for (let i = 24; i >= 0; i--) {\n if (freq[i] === 0) {\n break; // No more characters with this frequency\n }\n \n if (freq[i] >= freq[i + 1]) {\n let prev = freq[i];\n freq[i] = Math.max(0, freq[i + 1] - 1);\n del += prev - freq[i]; // Update the deletion count\n }\n }\n \n return del; // Return the minimum deletions required\n};", "solution_java": "class Solution {\n private int N = 26;\n public int minDeletions(String s) {\n int[] array = new int[N];\n for (char ch : s.toCharArray()) {\n array[ch - 'a']++;\n }\n int ans = 0;\n Set set = new HashSet<>();\n for (int i : array) {\n if (i == 0) continue;\n while (set.contains(i)) {\n i--;\n ans++;\n }\n if (i != 0) {\n set.add(i);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minDeletions(string s) {\n //Array to store the count of each character.\n vector freq (26, 0);\n \n //Calculatimg frequency of all characters.\n for (char c : s){\n freq[c - 'a']++;\n }\n \n //sorting the frequencies. So the greatest frequencies are in right side.\n sort(freq.begin(), freq.end());\n \n int del = 0; //to store the deletions.\n \n //Checking if 2 frequencies are same, if same then decrease the frequency so that it becomes less than the next greater one.So Start from the 2nd greatest frequency that is at freq[24].\n for (int i = 24; i >= 0; i--) {\n \n if(freq[i] == 0) break; // if frequency is 0 that means no more character is left.\n \n if(freq[i] >= freq[i+1]){\n int prev = freq[i]; //To store the frequency before deletion.\n freq[i] = max(0, freq[i+1] -1); //New frequency should be 1 less than the previous frequency in the array.\n del += prev - freq[i]; //Calculating deleted characters \n }\n }\n return del;\n }\n};" }, { "title": "Kids With the Greatest Number of Candies", "algo_input": "There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.\n\nReturn a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.\n\nNote that multiple kids can have the greatest number of candies.\n\n \nExample 1:\n\nInput: candies = [2,3,5,1,3], extraCandies = 3\nOutput: [true,true,true,false,true] \nExplanation: If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n\n\nExample 2:\n\nInput: candies = [4,2,1,1,2], extraCandies = 1\nOutput: [true,false,false,false,false] \nExplanation: There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\n\n\nExample 3:\n\nInput: candies = [12,1,12], extraCandies = 10\nOutput: [true,false,true]\n\n\n \nConstraints:\n\n\n\tn == candies.length\n\t2 <= n <= 100\n\t1 <= candies[i] <= 100\n\t1 <= extraCandies <= 50\n\n", "solution_py": "class Solution:\n def kidsWithCandies(self, candy, extra):\n #create an array(res) with all values as True and it's lenght is same as candies\n res = [True]*len(candy)\n #iterate over the elements in the array candy\n for i in range(len(candy)):\n #if the no. of canides at curr position + extra is greater than or equal to the maximum of candies then continue \n if (candy[i] + extra) >= max(candy):\n continue\n #if not \n else:\n #change the value of that position in res as false\n res[i] = False\n #return the res list\n return res ", "solution_js": "var kidsWithCandies = function(candies, extraCandies) {\n //First find out maximum number in array:->\n let max=0, res=[]; \n for(let i=0; imax) max=candies[i];\n }\n console.log(max)\n \n /*Now add extraCandies with every element in array and checks if\n\tthat sum is equals to or greater than max and return true and false otherwise; */\n \n for(let i=0; i=max) res.push(true);\n else res.push(false);\n }\n return res;\n};", "solution_java": "class Solution {\n public List kidsWithCandies(int[] candies, int extraCandies) {\n Listresult = new ArrayList<>(candies.length); // better practice since the length is known\n int theHighest=candies[0]; //always good practice to start from known value or to check constraints, 0 or -1\n for (int i = 1; i= theHighest) or (candies[i] >= theHighest-extraCandies)\n int mathLogic = theHighest - extraCandies;\n for (int i = 0; i=10 or 6 >=10-5\n if (candies[i] >= mathLogic) {\n result.add(true);\n } else {\n result.add(false);\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector kidsWithCandies(vector& candies, int extraCandies) {\n vector ans;\n int i = 0, size, max = 0;\n size = candies.size();\n for(i = 0; imax) max = candies[i];\n }\n for(i = 0; i= max){\n ans.push_back(true);\n }\n else ans.push_back(false);\n }\n return ans;\n }\n};" }, { "title": "X of a Kind in a Deck of Cards", "algo_input": "In a deck of cards, each card has an integer written on it.\n\nReturn true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:\n\n\n\tEach group has exactly X cards.\n\tAll the cards in each group have the same integer.\n\n\n \nExample 1:\n\nInput: deck = [1,2,3,4,4,3,2,1]\nOutput: true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].\n\n\nExample 2:\n\nInput: deck = [1,1,1,2,2,2,3,3]\nOutput: false\nExplanation: No possible partition.\n\n\n \nConstraints:\n\n\n\t1 <= deck.length <= 104\n\t0 <= deck[i] < 104\n\n", "solution_py": "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n \n f=defaultdict(int)\n \n for j in deck:\n f[j]+=1\n \n \n import math\n \n u=list(f.values())\n \n g=u[0]\n \n for j in range(1,len(u)):\n g=math.gcd(g,u[j])\n return g!=1\n \n ", "solution_js": "var hasGroupsSizeX = function(deck) {\n let unique = [...new Set(deck)], three = 0, two = 0, five = 0, size = 0, same = 0, s = 0;\n\n for(let i = 0; i= 2; \n }\n private int gcd(int a, int b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}", "solution_c": "class Solution {\npublic:\n int gcd(int a,int b)\n {\n while(a>0 && b>0)\n {\n if(a>b) a=a%b;\n else b=b%a;\n }\n return (a==0? b:a);\n }\n bool hasGroupsSizeX(vector& deck) {\n unordered_map mp;\n vector v;\n for(auto i:deck)\n {\n mp[i]++;\n }\n for(auto it:mp)\n {\n v.push_back(it.second);\n }\n int g=-1;\n for(int i=0;i1;\n }\n};" }, { "title": "Reverse Pairs", "algo_input": "Given an integer array nums, return the number of reverse pairs in the array.\n\nA reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].\n\n \nExample 1:\nInput: nums = [1,3,2,3,1]\nOutput: 2\nExample 2:\nInput: nums = [2,4,3,5,1]\nOutput: 3\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5 * 104\n\t-231 <= nums[i] <= 231 - 1\n\n", "solution_py": "from sortedcontainers import SortedList\nclass Solution:\n \"\"\"\n For each sub array nums[0, i]\n We sum the reverse pairs count\n of x, s.t x in [0, i-1] and nums[x] >= 2 * nums[i] + 1 \n Using a BST(sortedList) to get logN insert and lookup time.\n Time: O(NlogN)\n Space: O(N)\n \"\"\"\n def reversePairs(self, nums: List[int]) -> int:\n res = 0\n bst = SortedList()\n for e in nums:\n res += len(bst) - bst.bisect_left(2 * e + 1) # the count is the N - index\n bst.add(e) # add the the bst\n return res", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar reversePairs = function(nums) {\n \n let ans = mergeSort(nums,0,nums.length-1);\n return ans;\n \n \n};\n\nvar mergeSort = function(nums,l,h){\n if(l>=h){\n return 0;\n }\n let m = Math.floor((l+h)/2);\n let inv = mergeSort(nums,l,m);\n inv = inv + mergeSort(nums,m+1,h);\n inv = inv + merge(nums,l,m,h);\n return inv;\n}\n\nvar merge = function (nums,l,m,h){\n let cnt = 0;\n let j=m+1;\n for(let i=l;i<=m;i++){\n while(j<=h && nums[i]> 2*nums[j]){\n j++;\n }\n cnt = cnt+(j-(m+1));\n }\n \n let left = l, right=m+1,temp=[];\n while(left<=m && right<=h){\n if(nums[left]<=nums[right]){\n temp.push(nums[left]);\n left++;\n }\n else{\n temp.push(nums[right]);\n right++;\n }\n }\n while(left<=m){\n temp.push(nums[left]);\n left++;\n }\n while(right<=h){\n temp.push(nums[right]);\n right++;\n }\n for(let i=l;i<=h;i++){\n nums[i]=temp[i-l];\n }\n return cnt;\n \n}", "solution_java": "class Solution {\n int cnt;\n public int reversePairs(int[] nums) {\n int n = nums.length;\n cnt = 0;\n sort(0 , n - 1 , nums);\n return cnt;\n }\n void sort(int l , int r , int nums[]){\n if(l == r){\n return;\n }\n int mid = l + (r - l) / 2;\n sort(l , mid , nums);\n sort(mid + 1 , r , nums);\n merge(l , mid , r , nums);\n }\n void merge(int l , int mid , int r , int nums[]){\n int n1 = mid - l + 1;\n int n2 = r - mid;\n int a[] = new int[n1];\n int b[] = new int[n2];\n for(int i = 0; i < n1; i++){\n a[i] = nums[l + i];\n }\n for(int j = 0; j < n2; j++){\n b[j] = nums[mid + 1 + j];\n int idx = upperBound(a , 0 , n1 - 1 , 2L * (long)b[j]);\n if(idx <= n1) {\n cnt += n1 - idx;\n }\n }\n int i = 0;\n int j = 0;\n int k = l;\n while(i < n1 && j < n2){\n if(b[j] <= a[i]){\n nums[k++] = b[j++];\n }\n else{\n nums[k++] = a[i++];\n }\n }\n while(i < n1){\n nums[k++] = a[i++];\n }\n while(j < n2){\n nums[k++] = b[j++];\n }\n }\n int upperBound(int a[] , int l , int r , long x){\n int ans = r + 1;\n while(l <= r){\n int mid = l + (r - l) / 2;\n if((long)a[mid] > x){\n ans = mid;\n r = mid - 1;\n }\n else{\n l = mid + 1;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int merge_count(vector &nums,int s,int e){\n int i;\n int mid = (s+e)/2;\n int j=mid+1;\n long long int count=0;\n for(i=s;i<=mid;i++){\n while((j<=e)&&((double)nums[i]/2.0)>nums[j]){\n j++;\n }\n count += j-(mid+1);\n }\n i=s;j=mid+1;\n vector ans;\n while((i<=mid)&&(j<=e)){\n if(nums[i]<=nums[j]){\n ans.push_back(nums[i]);\n i++;\n }\n else{\n ans.push_back(nums[j]);\n j++;\n }\n }\n while(i<=mid){\n ans.push_back(nums[i]);\n i++;\n }\n while(j<=e){\n ans.push_back(nums[j]);\n j++;\n }\n for(int k=s;k<=e;k++){\n nums[k]=ans[k-s];\n }\n return count;\n }\n\n int reverse_count(vector &nums,int s,int e){\n if(s>=e){\n return 0;\n }\n int mid = (s+e)/2;\n int l_count = reverse_count(nums,s,mid);\n int r_count = reverse_count(nums,mid+1,e);\n int s_count = merge_count(nums,s,e);\n return (l_count+r_count+s_count);\n }\n\n int reversePairs(vector& nums) {\n int res = reverse_count(nums,0,nums.size()-1);\n return res;\n }\n};" }, { "title": "Balance a Binary Search Tree", "algo_input": "Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.\n\nA binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.\n\n \nExample 1:\n\nInput: root = [1,null,2,null,3,null,4,null,null]\nOutput: [2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\n\n\nExample 2:\n\nInput: root = [2,1,3]\nOutput: [2,1,3]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t1 <= Node.val <= 105\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 balanceBST(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n arr = []\n self.flatTree(root, arr)\n return self.createTree(arr, 0, len(arr))\n \n def flatTree(self, root, arr):\n if not root:\n return\n self.flatTree(root.left, arr)\n arr.append(root)\n self.flatTree(root.right, arr)\n \n def createTree(self, arr, start, length):\n if length == 0:\n return None\n root = arr[start + length / 2]\n root.left = self.createTree(arr, start, length / 2)\n root.right = self.createTree(arr, start + length / 2 + 1, length - length / 2 - 1)\n return root", "solution_js": "var balanceBST = function(root) {\nlet arr = [];//store sorted value in array\nlet InOrder = (node) => {//inorder helper to traverse and store sorted values in array\n if(!node)\n return;\n InOrder(node.left);\n arr.push(node.val);\n InOrder(node.right);\n}\nInOrder(root);\nlet BalancedFromSortedArray = (arr, start, end) => {//create Balanced tree from sorted array\n if(start>end)\n return null;\n let mid = Math.floor((start+end)/2);\n let newNode = new TreeNode(arr[mid]);\n newNode.left = BalancedFromSortedArray(arr,start,mid-1);\n newNode.right = BalancedFromSortedArray(arr,mid+1,end);\n return newNode;\n}\nlet Balanced = BalancedFromSortedArray(arr,0,arr.length-1);\nreturn Balanced;\n};", "solution_java": "class Solution {\n public TreeNode balanceBST(TreeNode root) {\n List arr = new ArrayList();\n InOrder( root, arr);\n return sortedArrayToBST( arr, 0, arr.size()-1);\n }\n \n public void InOrder(TreeNode node, List arr){\n if(node != null){\n InOrder( node.left, arr);\n arr.add(node.val);\n InOrder( node.right, arr);\n }\n }\n \n public TreeNode sortedArrayToBST(List arr, int start, int end) {\n\n if (start > end) {\n return null;\n }\n \n int mid = (start + end) / 2;\n \n TreeNode node = new TreeNode(arr.get(mid));\n node.left = sortedArrayToBST(arr, start, mid - 1);\n node.right = sortedArrayToBST(arr, mid + 1, end);\n \n return node;\n }\n}", "solution_c": "class Solution {\npublic:\n vector nums ;\n void traverse(TreeNode * root){\n if(!root) return ;\n traverse(root->left) ;\n nums.push_back(root->val) ;\n traverse(root->right) ;\n return ;\n }\n\n TreeNode * makeTree(int s , int e){\n if(s > e) return nullptr ;\n int m = (s + e) / 2 ;\n TreeNode * root = new TreeNode(nums[m]) ;\n\n root->left = makeTree(s,m - 1) ;\n root->right = makeTree(m + 1,e) ;\n\n return root ;\n }\n\n TreeNode* balanceBST(TreeNode* root) {\n traverse(root) ;\n return makeTree(0,size(nums) - 1) ;\n }\n};" }, { "title": "Bitwise ORs of Subarrays", "algo_input": "We have an array arr of non-negative integers.\n\nFor every (contiguous) subarray sub = [arr[i], arr[i + 1], ..., arr[j]] (with i <= j), we take the bitwise OR of all the elements in sub, obtaining a result arr[i] | arr[i + 1] | ... | arr[j].\n\nReturn the number of possible results. Results that occur more than once are only counted once in the final answer\n\n \nExample 1:\n\nInput: arr = [0]\nOutput: 1\nExplanation: There is only one possible result: 0.\n\n\nExample 2:\n\nInput: arr = [1,1,2]\nOutput: 3\nExplanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.\n\n\nExample 3:\n\nInput: arr = [1,2,4]\nOutput: 6\nExplanation: The possible results are 1, 2, 3, 4, 6, and 7.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5 * 104\n\t0 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def subarrayBitwiseORs(self, arr: List[int]) -> int:\n \n \n ans=set(arr)\n \n # each element is a subarry\n \n \n one = set()\n \n # to get the ans for the subarray of size >1\n # starting from 0th element to the ending element\n \n \n one.add(arr[0])\n \n for i in range(1,len(arr)):\n \n two=set()\n \n for j in one:\n \n two.add(j | arr[i])\n \n # subarray from the element in one set to the current ele(i th one)\n \n ans.add(j| arr[i])\n \n \n two.add(arr[i])\n \n # adding curr element to set two so that from next iteration we can take sub array starting from curr element \n \n one = two\n \n return len(ans)\n ", "solution_js": "/** https://leetcode.com/problems/bitwise-ors-of-subarrays/\n * @param {number[]} arr\n * @return {number}\n */\nvar subarrayBitwiseORs = function(arr) {\n // Hashset to store the unique bitwise\n this.uniqueBw = new Set();\n \n // Dynamic programming\n dp(arr, arr.length - 1);\n \n return this.uniqueBw.size;\n};\n\nvar dp = function(arr, currIdx) {\n // Base, reach beginning of the array\n if (currIdx === 0) {\n // Store the value to unique bitwise, since it's only single number, we store the actual value\n this.uniqueBw.add(arr[0]);\n \n // Return array\n return [arr[0]];\n }\n \n // DP to previous index\n let prev = dp(arr, currIdx - 1);\n \n // Number at current index\n let firstBw = arr[currIdx];\n \n // Add number at current index to hashset, since it's only single number, we store the actual value\n this.uniqueBw.add(firstBw);\n \n // Another hashset to store the result of bitwise operation between number at current index with result from previous index\n let currRes = new Set();\n currRes.add(firstBw);\n \n // Loop through result form previous index\n for (let i = 0; i < prev.length; i++) {\n // Perform bitwise operation OR\n let curr = arr[currIdx] | prev[i];\n \n // Add to unique bitwise collection\n this.uniqueBw.add(curr);\n \n // Add to current result\n currRes.add(curr);\n }\n\n // Return current result as an array\n return [...currRes];\n};", "solution_java": "class Solution {\n public int subarrayBitwiseORs(int[] arr) {\n int n = arr.length;\n Set s = new HashSet();\n LinkedList queue = new LinkedList();\n for(int i = 0; i< n; i++){\n int size = queue.size();\n if(!queue.contains(arr[i])){\n queue.offer(arr[i]);\n s.add(arr[i]);\n }\n int j = 0;\n while(j& arr) {\n vectors;\n int l=0;\n for(int a:arr) {\n int r=s.size();\n s.push_back(a);\n for(int i=l;i(begin(s), end(s)).size();\n }\n};" }, { "title": "Find Resultant Array After Removing Anagrams", "algo_input": "You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.\n\nIn one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.\n\nReturn words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.\n\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, \"dacb\" is an anagram of \"abdc\".\n\n \nExample 1:\n\nInput: words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]\nOutput: [\"abba\",\"cd\"]\nExplanation:\nOne of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = \"bbaa\" and words[1] = \"baba\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"baba\",\"cd\",\"cd\"].\n- Since words[1] = \"baba\" and words[0] = \"abba\" are anagrams, we choose index 1 and delete words[1].\n Now words = [\"abba\",\"cd\",\"cd\"].\n- Since words[2] = \"cd\" and words[1] = \"cd\" are anagrams, we choose index 2 and delete words[2].\n Now words = [\"abba\",\"cd\"].\nWe can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.\n\nExample 2:\n\nInput: words = [\"a\",\"b\",\"c\",\"d\",\"e\"]\nOutput: [\"a\",\"b\",\"c\",\"d\",\"e\"]\nExplanation:\nNo two adjacent strings in words are anagrams of each other, so no operations are performed.\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length <= 10\n\twords[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n i = 0\n while i < len(words) - 1:\n if sorted(words[i]) == sorted(words[i + 1]):\n words.remove(words[i + 1])\n continue\n i += 1\n return words", "solution_js": "var removeAnagrams = function(words) {\n let n = words.length;\n \n for(let i=0; i 0){\n return false\n }\n }\n return true\n}", "solution_java": "class Solution {\n public List removeAnagrams(String[] words) {\n String prev =\"\";\n List li=new ArrayList<>();\n for(int i=0;i removeAnagrams(vector& words) {\n for(int i = 1;i int:\n i=0\n while i0:\n flag =True\n break\n i+=1\n small = str(num)\n num = str(num)\n m=''\n for i in range(len(str(num))):\n if num[i]==change:\n m+='9'\n else:\n m+=num[i]\n m = int(m)\n s =''\n for i in range(len(num)):\n if small[i]==sc:\n if flag:\n s+='0'\n else:\n if small[i]==\"0\":\n s+='0'\n else:\n s+='1'\n else:\n s+=small[i]\n small = int(s)\n return m - small", "solution_js": "var maxDiff = function(num) {\n let occur = undefined;\n let max = num.toString().split(\"\");\n let min = num.toString().split(\"\");\n for(i=0;i1){\n occur = min[i];\n if(i===0) zerone = 1;\n else zerone = 0;\n min[i] = zerone; \n } \n if(min[i]===occur) min[i] = zerone;\n }\n return +max.join(\"\")-+min.join(\"\");\n};", "solution_java": "class Solution {\n public int maxDiff(int num) {\n int[] arr = new int[String.valueOf(num).length()];\n for (int i = arr.length - 1; i >= 0; i--){\n arr[i] = num % 10;\n num /= 10;\n }\n return max(arr.clone()) - min(arr);\n }\n\n private int max(int[] arr){ // find max\n for (int i = 0, t = -1; i < arr.length; i++){\n if (t == -1 && arr[i] != 9){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = 9;\n }\n }\n return parse(arr);\n }\n\n private int min(int[] arr){ // find min\n int re = arr[0] == 1? 0 : 1;\n int t = arr[0] == 1? -1 : arr[0];\n for (int i = 0; i < arr.length; i++){\n if (t == -1 && arr[i] != 0 && arr[i] != arr[0]){\n t = arr[i];\n }\n if (t == arr[i]){\n arr[i] = re;\n }\n }\n return parse(arr);\n }\n\n private int parse(int[] arr){\n int ans = 0;\n for (int i = 0; i < arr.length; i++){\n ans = 10 * ans + arr[i];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int power10(int n)\n {\n int total=1;\n for(int i=0;i v;\n vector w;\n int n = num;\n while (n > 0)\n {\n v.push_back(n % 10);\n w.push_back(n % 10);\n n /= 10;\n }\n \n //Finding maximum number\n int d = v.size();\n int j = d - 1;\n for (int i = d - 1; i >= 0; i--)\n {\n if (v[i] != 9)\n {\n j = i;\n break;\n }\n }\n \n\n for (int i = 0; i <= j; i++)\n {\n if (v[i] == v[j])\n {\n v[i] = 9;\n }\n }\n long long int res = 0;\n for (int i = d - 1; i >= 0; i--)\n {\n res += (v[i] * power10(i));\n }\n\n //Finding minimum number \n int t = w.size();\n if (w[t - 1] == 1)\n {\n int l = -1;\n for (int i = t - 2; i >= 0; i--)\n {\n if (w[i] != 0 && w[i]!=1)\n {\n l = i;\n break;\n }\n }\n for (int i = 0; i <= l; i++)\n {\n if (w[i] == w[l])\n {\n w[i] = 0;\n }\n }\n }\n else\n {\n for (int i = 0; i < t; i++)\n {\n if (w[i] == w[t - 1])\n {\n w[i] = 1;\n }\n }\n }\n long long int res2 = 0;\n for (int i = t - 1; i >= 0; i--)\n {\n res2 += (power10(i) * w[i]);\n }\n return res-res2;\n }\n};" }, { "title": "Keys and Rooms", "algo_input": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.\n\nWhen you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.\n\nGiven an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.\n\n \nExample 1:\n\nInput: rooms = [[1],[2],[3],[]]\nOutput: true\nExplanation: \nWe visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.\n\n\nExample 2:\n\nInput: rooms = [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n\n\n \nConstraints:\n\n\n\tn == rooms.length\n\t2 <= n <= 1000\n\t0 <= rooms[i].length <= 1000\n\t1 <= sum(rooms[i].length) <= 3000\n\t0 <= rooms[i][j] < n\n\tAll the values of rooms[i] are unique.\n\n", "solution_py": "class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n # Create a set of for rooms visited\n visited_rooms = set()\n \n # Create a queue to do a breadth first search visiting rooms\n # Append the first room, 0, to the queue to begin the search\n queue = collections.deque()\n queue.append(0)\n \n # Perform the breadth first search with the queue\n while queue:\n for _ in range(0, len(queue)):\n # Search the room\n room_number = queue.popleft()\n \n # If we haven't visited the room, get the keys from the room\n if room_number not in visited_rooms:\n \n # Collect the keys from the room\n found_keys = rooms[room_number]\n \n # Add the keys to the queue so they can be tested\n for key in found_keys:\n queue.append(key)\n \n # Add the current room to the visited set\n visited_rooms.add(room_number)\n \n # If we visited all of the rooms, then the number of visited rooms should be\n # equal to the number of total rooms\n if len(visited_rooms) == len(rooms):\n return True\n \n return False", "solution_js": "function dfs(current,all,visited){\n if(visited.size==all.length){\n return true;\n }\n for(let i=0;i> rooms) {\n \t\t boolean[] visited = new boolean[rooms.size()];\n \t\t visited[0]= true;\n \t\t for(int a:rooms.get(0))\n \t\t {\n \t\t\t if(!visited[a])\n \t\t\t {\n \t\t\t\t bfs(a, visited, rooms.size()-1, rooms);\n \t\t\t\t \n \t\t\t }\n \t\t }\n \t\t //System.out.println(\"arr -->>\"+Arrays.toString(visited));\n \t\tfor(boolean a:visited)\n \t\t{\n \t\t\tif(!a)\n \t\t\t\treturn false;\n \t\t}\n \t return true;\n \t \n \t }\n \t public void bfs(int key, boolean[] vivsted, int target,List> rooms)\n \t {\n \t\t\n \t\t\n \t\t vivsted[key] = true;\n \t\t for(int a:rooms.get(key))\n \t\t {\n \t\t\t if(!vivsted[a])\n \t\t\t {\n \t\t\t\t bfs(a, vivsted, target, rooms);\n \t\t\t }\n \t\t }\n \t\t \n \t\t \n \t\t\n \t }\n \n}", "solution_c": "class Solution {\npublic:\n void dfs(int node, vector>& rooms,vector &visited){\n visited[node]=1;\n \n for(auto it: rooms[node]){\n if(visited[it]==0)\n dfs(it, rooms, visited);\n else continue;\n }\n return;\n }\n \n bool canVisitAllRooms(vector>& rooms) {\n int n=rooms.size();\n vector visited(n,0);\n \n dfs(0,rooms,visited);\n \n for(int i=0;i int:\n if max(nums) == 0:\n return 0\n \n return sum([x.bit_count() for x in nums]) + max([x.bit_length() for x in nums]) - 1", "solution_js": "var minOperations = function(nums) {\n let maxpow = 0, ans = 0, pow, val\n for (let i = 0; i < nums.length; i++) {\n for (val = nums[i], pow = 0; val > 0; ans++)\n if (val % 2) val--\n else pow++, val /= 2\n ans -= pow\n if (pow > maxpow) maxpow = pow\n }\n return ans + maxpow\n};", "solution_java": "class Solution {\n public int minOperations(int[] nums) {\n int odd = 0, even = 0;\n Map map = new HashMap<>();\n for (int n : nums){\n int res = dfs(n, map);\n odd += res >> 5;\n even = Math.max(res & 0b11111, even);\n }\n\n return odd + even;\n }\n\n private int dfs(int n, Map map){\n if (n == 0) return 0;\n if (map.containsKey(n)) return map.get(n);\n\n int res = n % 2 << 5;\n res += dfs(n / 2, map) + (n > 1? 1 : 0);\n\n map.put(n, res);\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int minOperations(vector& nums) {\n int ans = 0;\n int t = 33;\n while(t--){\n int flag = false;\n for(int i = 0; i int:\n logs.sort(key=lambda x: x[0])\n print(logs)\n living = 0\n max_living = 0\n year = 0\n\n for ind, (start, stop) in enumerate(logs):\n born = ind+1\n dead = 0\n for i in range(ind):\n if logs[i][1] <= start:\n dead += 1\n \n living = born - dead\n # print(born, dead, living, max_living)\n if living > max_living:\n max_living = living\n year = start\n\n \n \n return year", "solution_js": "var maximumPopulation = function(logs) {\n const count = new Array(101).fill(0);\n \n for (const [birth, death] of logs) {\n count[birth - 1950]++;\n count[death - 1950]--;\n }\n \n let max = 0;\n \n for (let i = 1; i < 101; i++) {\n count[i] += count[i - 1];\n \n if (count[i] > count[max]) max = i;\n }\n \n return 1950 + max;\n };", "solution_java": "class Solution {\n public int maximumPopulation(int[][] logs) {\n\n int[] year = new int[2051];\n\n // O(n) -> n is log.length\n\n for(int[] log : logs){\n\n year[log[0]] += 1;\n year[log[1]] -= 1;\n }\n\n int maxNum = year[1950], maxYear = 1950;\n\n // O(100) -> 2050 - 1950 = 100\n\n for(int i = 1951; i < year.length; i++){\n year[i] += year[i - 1]; // Generating Prefix Sum\n\n if(year[i] > maxNum){\n maxNum = year[i];\n maxYear = i;\n }\n }\n\n return maxYear;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumPopulation(vector>& logs) {\n int arr[101]={0};\n for(vector log : logs){\n arr[log[0]-1950]++;\n arr[log[1]-1950]--;\n }\n int max=0,year,cnt=0;\n for(int i=0;i<101;i++){\n cnt+=arr[i];\n if(cnt>max)\n max=cnt,year=i;\n }\n return year+1950;\n }\n};" }, { "title": "Remove Element", "algo_input": "Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.\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 val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; 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 = [3,2,2,3], val = 3\nOutput: 2, nums = [2,2,_,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\nExample 2:\n\nInput: nums = [0,1,2,2,3,0,4,2], val = 2\nOutput: 5, nums = [0,1,4,0,3,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n \nConstraints:\n\n\n\t0 <= nums.length <= 100\n\t0 <= nums[i] <= 50\n\t0 <= val <= 100\n\n", "solution_py": "class Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n step = 0\n while step < len(nums):\n if nums[step] == val:\n nums.pop(step)\n continue\n step+=1\n return len(nums)", "solution_js": "var removeElement = function(nums, val) {\n for(let i = 0; i < nums.length; i++){\n if(nums[i] === val){\n nums.splice(i, 1);\n i--;\n }\n }\n return nums.length;\n};", "solution_java": "class Solution {\n public int removeElement(int[] nums, int val) {\n int ind = 0;\n for(int i=0; i& nums, int val) {\n int left = 0;\n int right = nums.size() - 1;\n while (left <= right) {\n if (nums[left] != val) {\n ++left;\n }\n else if (nums[right] == val) {\n --right;\n }\n else if (left < right) {\n nums[left++] = nums[right--];\n }\n }\n return left;\n }\n};" }, { "title": "Longest Word in Dictionary through Deleting", "algo_input": "Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.\n\n \nExample 1:\n\nInput: s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]\nOutput: \"apple\"\n\n\nExample 2:\n\nInput: s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]\nOutput: \"a\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\t1 <= dictionary.length <= 1000\n\t1 <= dictionary[i].length <= 1000\n\ts and dictionary[i] consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def findLongestWord(self, s: str, dictionary: list[str]) -> str:\n solution = \"\"\n for word in dictionary:\n j = 0\n for i in range(len(s)):\n if s[i] == word[j]:\n j+=1\n if j == len(word):\n solution = word if len(word) > len(solution) or len(word) == len(solution) and word < solution else solution\n break\n return solution", "solution_js": "/**\n * @param {string} s\n * @param {string[]} dictionary\n * @return {string}\n */\nvar findLongestWord = function(s, dictionary) {\n const getLen = (s1, s2) => {\n let i = 0, j = 0;\n while(i < s1.length && j < s2.length) {\n if(s1[i] == s2[j]) { i++, j++; }\n else i++;\n }\n if(j != s2.length) return 0;\n return s2.length;\n }\n let ans = '', ml = 0;\n for(let word of dictionary) {\n const len = getLen(s, word);\n if(len > ml) {\n ans = word;\n ml = len;\n }\n else if(len == ml && ans > word) {\n ans = word;\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public String findLongestWord(String s, List dictionary) {\n \n int[] fre=new int[26];\n \n \n String ans=\"\";\n int flag=0;\n int[] fff=new int[26];\n char[] ch = s.toCharArray();\n for(char c : ch)\n fre[c-'a']+=1;\n \n for(String s1 : dictionary)\n { \n fff=fre.clone();\n int[] fre1=new int[26];\n char[] ch1 = s1.toCharArray();\n for(char c : ch1)\n {\n \n fre1[c-'a']+=1;\n }\n \n for(char c : ch1)\n {\n if(fre1[c-'a'] <= fff[c-'a'])\n { flag=0;\n fff[c-'a']-=1; \n fre1[c-'a']-=1;\n }\n else\n {flag=1;\n break;} \n }\n if(flag==0)\n {\n if(ans != \"\")\n {\n if(ans.length() s1.charAt(m))\n {\n f=1;\n break;\n }\n \n }\n if(f==1)\n ans=s1;\n }\n }\n }\n else\n ans =s1;\n }\n else\n {\n flag=0;\n }\n }\n \n return ans;\n \n }\n}", "solution_c": "class Solution {\nprivate:\n //checks whether the string word is a subsequence of s\n bool isSubSeq(string &s,string &word){\n int start=0;\n for(int i=0;i& dictionary) {\n string ans=\"\";\n for(string word:dictionary){\n if(word.size()>=ans.size() and isSubSeq(s,word)){\n if(word.size()>ans.size()){\n ans=word;\n } else if(word.size()==ans.size() and word Optional[ListNode]:\n store = []\n curr = head\n while curr:\n store.append(curr.val)\n curr = curr.next\n store.sort()\n dummyNode = ListNode(0)\n temp = dummyNode\n \n for i in store:\n x = ListNode(val = i)\n temp.next = x\n temp = x\n return dummyNode.next", "solution_js": "function getListSize(head) {\n let curr = head;\n let size = 0;\n\n while(curr !== null) {\n size += 1;\n\n curr = curr.next;\n }\n\n return size;\n}\n\nfunction splitInHalf(head, n) {\n let node1 = head;\n let curr = head;\n\n for (let i = 0; i < Math.floor(n / 2) - 1; i++) {\n curr = curr.next;\n }\n\n const node2 = curr.next;\n curr.next = null;\n\n return [\n node1,\n Math.floor(n / 2),\n node2,\n n - Math.floor(n / 2),\n ]\n}\n\nfunction merge(head1, head2) {\n if (head1.val > head2.val) {\n return merge(head2, head1)\n }\n\n const head = head1;\n let curr = head1;\n\n let runner1 = curr.next;\n let runner2 = head2;\n\n while (runner1 !== null || runner2 !== null) {\n const runner1Value = runner1 ? runner1.val : Infinity;\n const runner2Value = runner2 ? runner2.val : Infinity;\n\n if (runner1Value < runner2Value) {\n curr.next = runner1;\n runner1 = runner1.next;\n } else {\n curr.next = runner2;\n runner2 = runner2.next;\n }\n\n curr = curr.next;\n }\n\n curr.next = null;\n return head;\n}\n\nvar sortList = function(head) {\n const size = getListSize(head);\n\n function mergeSort(node, n) {\n if (n <= 1) {\n return node;\n }\n\n const [node1, n1, node2, n2] = splitInHalf(node, n);\n const [merged1, merged2] = [mergeSort(node1, n1), mergeSort(node2, n2)];\n\n return merge(merged1, merged2);\n }\n\n return mergeSort(head, size);\n};", "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode sortList(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n\n ListNode mid = middle(head);\n\n ListNode left = sortList(head);\n ListNode right = sortList(mid);\n\n return mergeTwoLists(left, right);\n }\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode head = new ListNode();\n ListNode tail = head;\n while (list1 != null && list2 != null) {\n if (list1.val < list2.val) {\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n } else {\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n }\n }\n\n tail.next = (list1 != null) ? list1 : list2;\n\n return head.next;\n }\n\n public ListNode middle(ListNode head) {\n ListNode midprev = null;\n while (head != null && head.next != null) {\n midprev = (midprev == null) ? head : midprev.next;\n head = head.next.next;\n }\n ListNode mid = midprev.next;\n midprev.next = null;\n return mid;\n }\n}", "solution_c": " // Please upvote if it helps\nclass Solution {\npublic:\n ListNode* sortList(ListNode* head) {\n //If List Contain a Single or 0 Node\n if(head == NULL || head ->next == NULL)\n return head;\n\n ListNode *temp = NULL;\n ListNode *slow = head;\n ListNode *fast = head;\n\n // 2 pointer appraoach / turtle-hare Algorithm (Finding the middle element)\n while(fast != NULL && fast -> next != NULL)\n {\n temp = slow;\n slow = slow->next; //slow increment by 1\n fast = fast ->next ->next; //fast incremented by 2\n\n }\n temp -> next = NULL; //end of first left half\n\n ListNode* l1 = sortList(head); //left half recursive call\n ListNode* l2 = sortList(slow); //right half recursive call\n\n return mergelist(l1, l2); //mergelist Function call\n\n }\n\n //MergeSort Function O(n*logn)\n ListNode* mergelist(ListNode *l1, ListNode *l2)\n {\n ListNode *ptr = new ListNode(0);\n ListNode *curr = ptr;\n\n while(l1 != NULL && l2 != NULL)\n {\n if(l1->val <= l2->val)\n {\n curr -> next = l1;\n l1 = l1 -> next;\n }\n else\n {\n curr -> next = l2;\n l2 = l2 -> next;\n }\n\n curr = curr ->next;\n\n }\n\n //for unqual length linked list\n\n if(l1 != NULL)\n {\n curr -> next = l1;\n l1 = l1->next;\n }\n\n if(l2 != NULL)\n {\n curr -> next = l2;\n l2 = l2 ->next;\n }\n\n return ptr->next;\n }\n};" }, { "title": "Maximum Candies Allocated to K Children", "algo_input": "You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.\n\nYou are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.\n\nReturn the maximum number of candies each child can get.\n \nExample 1:\n\nInput: candies = [5,8,6], k = 3\nOutput: 5\nExplanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.\n\n\nExample 2:\n\nInput: candies = [2,5], k = 11\nOutput: 0\nExplanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.\n\n\n \nConstraints:\n\n\n\t1 <= candies.length <= 105\n\t1 <= candies[i] <= 107\n\t1 <= k <= 1012\n\n", "solution_py": "def canSplit(candies, mid, k):\n split = 0\n for i in candies:\n split += i//mid\n if split >= k:\n return True\n else:\n return False\n\nclass Solution:\n def maximumCandies(self, candies: List[int], k: int) -> int:\n end = sum(candies)//k\n start = 1\n ans = 0\n while start <= end:\n mid = (start + end)//2\n if canSplit(candies, mid, k):\n start = mid + 1\n ans = mid\n else:\n end = mid - 1\n return ans", "solution_js": "var maximumCandies = function(candies, k) {\n const n = candies.length;\n \n let left = 1;\n let right = 1e7 + 1;\n \n while (left < right) {\n const mid = (left + right) >> 1;\n const pilesAvail = divideIntoPiles(mid);\n\n if (pilesAvail < k) right = mid;\n else left = mid + 1;\n }\n \n return right - 1;\n \n \n function divideIntoPiles(pileSize) {\n let piles = 0;\n \n for (let i = 0; i < n; ++i) {\n const count = candies[i];\n \n piles += Math.floor(count / pileSize);\n }\n \n return piles;\n }\n};", "solution_java": "class Solution {\n public boolean canSplit(int[] candies, long k, long mid) {\n long split = 0;\n for(int i = 0; i < candies.length; ++i) {\n split += candies[i]/mid;\n } \n if(split >= k)\n return true;\n else\n return false;\n }\n \n public int maximumCandies(int[] candies, long k) {\n long sum = 0;\n for(int i = 0; i < candies.length; ++i) {\n sum += candies[i];\n }\n long start = 1, end = sum;\n long ans = 0;\n while(start <= end) {\n long mid = (start + end)/2;\n if(canSplit(candies, k, mid)) {\n ans = mid;\n start = mid + 1;\n } else {\n end = mid-1;\n }\n }\n return (int)ans;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canSplit(vector& candies, long long k, long long mid) {\n long long split = 0;\n for(int i = 0; i < candies.size(); ++i) {\n split += candies[i]/mid;\n } \n if(split >= k)\n return true;\n else\n return false;\n }\n \n int maximumCandies(vector& candies, long long k) {\n long long sum = 0;\n for(int i = 0; i < candies.size(); ++i) {\n sum += candies[i];\n }\n long long start = 1, end = sum/k;\n long long ans = 0;\n while(start <= end) {\n long long mid = (start + end)/2;\n if(canSplit(candies, k, mid)) {\n ans = mid;\n start = mid + 1;\n } else {\n end = mid-1;\n }\n }\n return ans;\n }\n};" }, { "title": "Number of Steps to Reduce a Number to Zero", "algo_input": "Given an integer num, return the number of steps to reduce it to zero.\n\nIn one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.\n\n \nExample 1:\n\nInput: num = 14\nOutput: 6\nExplanation: \nStep 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.\n\n\nExample 2:\n\nInput: num = 8\nOutput: 4\nExplanation: \nStep 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.\n\n\nExample 3:\n\nInput: num = 123\nOutput: 12\n\n\n \nConstraints:\n\n\n\t0 <= num <= 106\n\n", "solution_py": "class Solution:\n def numberOfSteps(self, num: int) -> int:\n count=0\n while num:\n if num%2:\n num=num-1\n else:\n num=num//2\n count+=1\n return count", "solution_js": "var numberOfSteps = function(num) {\n let steps = 0\n while (num > 0) {\n if (num % 2 === 0) {\n num = num/2\n steps++\n }\n\n if (num % 2 === 1) {\n num--\n steps++\n }\n }\n\n return steps\n\n};", "solution_java": "class Solution {\n public int numberOfSteps(int num) {\n return helper(num,0);\n }\n public int helper(int n,int c){\n if(n==0) return c;\n if(n%2==0){ //check for even no.\n return helper(n/2,c+1);\n }\n \n return helper(n-1,c+1);\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfSteps(int num) {\n int count = 0;\n while (num > 0)\n {\n if (num % 2==0)\n {\n num = num/2;\n count++;\n }\n else\n {\n if(num > 1)\n {\n num -= 1;\n count++;\n }\n else\n {\n count++;\n break;\n }\n }\n }\n return count;\n }\n};" }, { "title": "Number of Flowers in Full Bloom", "algo_input": "You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.\n\nReturn an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.\n\n \nExample 1:\n\nInput: flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]\nOutput: [1,2,2,2]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\nExample 2:\n\nInput: flowers = [[1,10],[3,3]], persons = [3,3,2]\nOutput: [2,2,1]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\n \nConstraints:\n\n\n\t1 <= flowers.length <= 5 * 104\n\tflowers[i].length == 2\n\t1 <= starti <= endi <= 109\n\t1 <= persons.length <= 5 * 104\n\t1 <= persons[i] <= 109\n\n", "solution_py": "class Solution:\n def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n #we ADD flowers in the order in which they start, but we remove them in the order they \n #end. For this reason, we sort the flowers by starting time but put them in a heap, \n #in which we remove them by ending time\n starts = sorted(flowers) #keep flowers untouched in case array should be constant\n blooming = [] #heap of active flowers\n answer = [-1] * len(people) #output array\n hours = [(people[i], i) for i in range(len(people))] #the people, ordered and indexed by their time\n hours.sort()\n\n i = 0 #going through starts\n for hour, person in hours:\n #add all flowers that have started\n while i < len(starts) and starts[i][0] <= hour:\n heappush(blooming, (starts[i][1], starts[i][0]))\n i += 1\n #now remove all flowers that have ended. Note that we only care about the absolute smallest, \n #and in python minheaps, that is always the first element - even if no other element's order \n #is guaranteed\n while blooming and blooming[0][0] < hour: #as long as the soonest to end blooming flower hasn't already stopped\n heappop(blooming)\n answer[person] = len(blooming)\n \n return answer", "solution_js": "/**\n * @param {number[][]} flowers\n * @param {number[]} persons\n * @return {number[]}\n */\nvar fullBloomFlowers = function(flowers, persons) {\n // *** IDEATION *** //\n // key observation:\n // total number of flowers see on day i =\n // number of flowers has already bloomed so far on day i - number of flowers already ended (\"died\") prior to day i\n\n // find number of flowers already bloomed on day i\n // each flower has a start day\n // start array = [1, 3, 9, 4] for example\n // on day 8, there are 3 flowers bloomed:\n // equivalent to find the number of elements in the \"start\" array which is less than or equal to 8\n\n // find number of flowers already ended on day i\n // each flower has an end day\n // end array = [6, 7, 12, 13] for example\n // on day 8, there are 2 flowers already ended:\n // equivalent to find the number of elements in the \"end\" array which is less than 8\n // equivalent to find the number of elements in the \"end\" array which is less than or equal to 7\n\n // both process above can be solved efficiently with binary search on a sorted array\n // hence we need to first build 2 array \"start\" and \"end\" and sorted it\n // then apply the formula at the beginning to return the required answer\n\n // *** IMPLEMENTATION *** //\n // step 1: build the \"start\" and \"end\" array\n let start = [];\n let end = [];\n\n for (let i = 0; i < flowers.length; i++) {\n start[i] = flowers[i][0];\n end[i] = flowers[i][1];\n }\n\n // step 2: sort the \"start\" and \"end\" array\n start.sort((a, b) => a - b);\n end.sort((a, b) => a - b);\n\n // step 3: apply the observation formula using a binarySearch function\n let res = [];\n for (let j = 0; j < persons.length; j++) {\n res[j] = binarySearch(start, persons[j]) - binarySearch(end, persons[j] - 1);\n }\n return res;\n\n // step 4: implement the binarySearch function (variant from standard binarySearch)\n function binarySearch(array, k) {\n // array is sorted;\n // obj is to find the number of elements in array which is less than or equal to \"k\"\n let left = 0;\n let right = array.length - 1;\n let index = -1;\n\n while (left <= right) {\n let mid = left + Math.floor((right - left) / 2);\n if (k < array[mid]) {\n right = mid - 1;\n } else {\n index = Math.max(index, mid); // record the index whenever k >= array[mid]\n left = mid + 1;\n }\n }\n\n // all elements with in array from position '0' to position 'index' will be less than or equal to k\n return index + 1;\n }\n};", "solution_java": "class Solution {\npublic int[] fullBloomFlowers(int[][] flowers, int[] persons) {\n int n = persons.length;\n int[] result = new int[n];\n\n TreeMap treeMap = new TreeMap<>();\n // See explanation here: https://leetcode.com/problems/my-calendar-iii/discuss/109556/JavaC%2B%2B-Clean-Code\n for (int[] flower : flowers) {\n treeMap.put(flower[0], treeMap.getOrDefault(flower[0], 0) + 1);\n // use end + 1 instead of end\n treeMap.put(flower[1] + 1, treeMap.getOrDefault(flower[1] + 1, 0) - 1);\n }\n\n TreeMap sum = new TreeMap<>();\n int prev = 0;\n for (Map.Entry entry : treeMap.entrySet()) {\n prev += entry.getValue();\n sum.put(entry.getKey(), prev);\n }\n\n for (int i = 0; i < n; i++) {\n Map.Entry entry = sum.floorEntry(persons[i]);\n // if entry is null then result[i] = 0\n if (entry != null) result[i] = entry.getValue();\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector fullBloomFlowers(vector>& flowers, vector& persons) {\n vector> line; \n for (auto& f : flowers) {\n line.push_back({f[0], +1}); \n line.push_back({f[1]+1, -1}); \n }\n sort(line.begin(), line.end()); \n int prefix = 0; \n vector time, vals; \n for (auto& l : line) {\n time.push_back(l[0]); \n vals.push_back(prefix += l[1]); \n }\n vector ans; \n for (auto& p : persons) {\n auto it = upper_bound(time.begin(), time.end(), p); \n if (it == time.begin()) ans.push_back(0); \n else ans.push_back(vals[it - time.begin() - 1]); \n }\n return ans; \n }\n};" }, { "title": "H-Index", "algo_input": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.\n\nAccording to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n − h papers have no more than h citations each.\n\nIf there are several possible values for h, the maximum one is taken as the h-index.\n\n \nExample 1:\n\nInput: citations = [3,0,6,1,5]\nOutput: 3\nExplanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\nExample 2:\n\nInput: citations = [1,3,1]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tn == citations.length\n\t1 <= n <= 5000\n\t0 <= citations[i] <= 1000\n\n", "solution_py": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n num = sorted(citations)\n h = 0\n j = len(num)-1\n for i in range(len(num)):\n if i+1 <=num[i] and j-i+1>=num[i]:\n h =max(num[i],h)\n elif i+1 <= num[i] and j-i+1 num[i] and j-i+1 >=num[i]:\n h = max(h, num[i])\n \n return h", "solution_js": "var hIndex = function(citations) {\n citations.sort((a,b)=>b-a)\n let i=0\n while(citations[i]>i) i++\n\n return i\n};", "solution_java": "class Solution {\n public int hIndex(int[] citations) {\n int n = citations.length;\n Arrays.sort(citations);\n for(int i = 0; i < n; i++) {\n int hlen = (n-1) - i + 1;\n if(citations[i] >= hlen) {\n return hlen;\n }\n }\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n int hIndex(vector& citations) {\n sort(citations.begin(),citations.end(),greater());\n int ans=0;\n for(int i=0;i=i+1) ans=i+1;\n }\n return ans;\n }\n};" }, { "title": "Binary Tree Level Order Traversal II", "algo_input": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).\n\n \nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[15,7],[9,20],[3]]\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": "class Solution:\n def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:\n def dfs(node, level, result):\n if not node:\n return\n if level >= len(result):\n result.append([])\n result[level].append(node.val)\n dfs(node.left, level+1, result)\n dfs(node.right, level+1, result)\n result = []\n dfs(root, 0, result)\n return result[::-1]", "solution_js": "var levelOrderBottom = function(root) {\n let solution = []\n function dfs(node, level) {\n if(!node) return null\n\n if(!solution[level]) solution[level] = []\n solution[level].push(node.val)\n\n dfs(node.left, level + 1)\n dfs(node.right, level + 1)\n }\n dfs(root, 0)\n return solution.reverse()\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> levelOrderBottom(TreeNode root) {\n Queue al=new LinkedList<>();\n List> fal=new LinkedList<>();\n if(root==null) return fal;\n al.offer(root);\n while(!al.isEmpty()){\n List aal=new LinkedList<>();\n int num=al.size();\n for(int i=0;i,std::greater>& levelVals)\n {\n if (root == nullptr)\n return;\n \n if (levelVals.find(level) == levelVals.end())\n levelVals[level] = {root->val};\n else\n levelVals[level].push_back(root->val);\n \n dft(root->left,level+1,levelVals);\n dft(root->right,level+1,levelVals);\n }\npublic:\n vector> levelOrderBottom(TreeNode* root) {\n map,std::greater> levelVals;\n dft(root,0,levelVals);\n \n vector> res;\n for (const auto& [level,vals] : levelVals)\n res.push_back(vals);\n \n return res;\n }\n};" }, { "title": "Count Good Nodes in Binary Tree", "algo_input": "Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.\n\nReturn the number of good nodes in the binary tree.\n\n \nExample 1:\n\n\n\nInput: root = [3,1,4,3,null,1,5]\nOutput: 4\nExplanation: Nodes in blue are good.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.\n\nExample 2:\n\n\n\nInput: root = [3,3,null,4,2]\nOutput: 3\nExplanation: Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.\n\nExample 3:\n\nInput: root = [1]\nOutput: 1\nExplanation: Root is considered as good.\n\n \nConstraints:\n\n\n\tThe number of nodes in the binary tree is in the range [1, 10^5].\n\tEach node's value is between [-10^4, 10^4].\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 goodNodes(self, root: TreeNode) -> int:\n \n def dfs(node,maxVal):\n if not node:\n return 0\n res=1 if node.val>=maxVal else 0\n maxVal=max(maxVal,node.val)\n res+=dfs(node.left,maxVal)\n res+=dfs(node.right,maxVal)\n return res\n return dfs(root,root.val)", "solution_js": "var goodNodes = function(root) {\n let ans = 0;\n const traverse = (r = root, mx = root.val) => {\n if(!r) return;\n if(r.val >= mx) {\n ans++;\n }\n let childMax = Math.max(mx, r.val);\n traverse(r.left, childMax);\n traverse(r.right, childMax);\n }\n traverse();\n return ans;\n};", "solution_java": "class Solution {\n int ans = 0;\n public int goodNodes(TreeNode root) {\n if (root == null) return 0;\n dfs(root, root.val);\n return ans;\n }\n\n void dfs(TreeNode root, int mx) {\n if (root == null) return;\n\n mx = Math.max(mx, root.val);\n if(mx <= root.val) ans++;\n\n dfs(root.left, mx);\n dfs(root.right, mx);\n\n }\n}", "solution_c": "class Solution {\npublic:\n int count=0;\n void sol(TreeNode* root,int gr){\n if(!root)return; // base condition \n \n if(gr<=root->val){ //check point max element increase count\n gr=max(gr,root->val);\n count++;\n }\n \n if(root->left) sol(root->left,gr);\n if(root->right) sol(root->right,gr);\n \n }\n int goodNodes(TreeNode* root) {\n \n if(!root->left && !root->right) return 1; //check for if there is one node\n int gr=root->val;\n sol(root,gr);\n return count;\n \n }\n};" }, { "title": "Cheapest Flights Within K Stops", "algo_input": "There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.\n\nYou are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.\n\n \nExample 1:\n\nInput: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\nOutput: 700\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\n\n\nExample 2:\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput: 200\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\n\n\nExample 3:\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput: 500\nExplanation:\nThe graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 100\n\t0 <= flights.length <= (n * (n - 1) / 2)\n\tflights[i].length == 3\n\t0 <= fromi, toi < n\n\tfromi != toi\n\t1 <= pricei <= 104\n\tThere will not be any multiple flights between two cities.\n\t0 <= src, dst, k < n\n\tsrc != dst\n\n", "solution_py": "class Solution:\n\tdef findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n\t\tgraph = defaultdict(list)\n\t\tfor u,v,w in flights: graph[u].append((v,w))\n\n\t\tpq = [(0,src,0)]\n\t\tdis = [float('inf')]*n\n\n\t\twhile pq:\n\t\t\tc,n,l = heappop(pq)\n\t\t\tif n==dst: return c\n\t\t\tif l > k or l>= dis[n]: continue\n\t\t\tdis[n] = l\n\t\t\tfor v,w in graph[n]:\n\t\t\t\theappush(pq,(c+w,v,l+1))\n\t\treturn -1", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} flights\n * @param {number} src\n * @param {number} dst\n * @param {number} k\n * @return {number}\n */\nconst MAX_PRICE=Math.pow(10,8);\nvar findCheapestPrice = function(n, flights, src, dst, k) {\n let prev=[];\n let step=0;\n let curr=[];\n for(let i=0;i=MAX_PRICE)continue;\n let totalCostToReachDst=prev[src]+p;\n curr[dst]=Math.min(curr[dst],totalCostToReachDst);\n }\n step++;\n prev=curr;\n \n }\n return prev[dst]>=MAX_PRICE?-1:prev[dst];\n \n};", "solution_java": "class Solution {\n public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {\n // Initialize Prices arr with infinity & src 0\n int[] prices = new int[n];\n for(int i = 0; i < n; i++)\n prices[i] = Integer.MAX_VALUE;\n prices[src] = 0;\n \n // Build Adj list {key: src | val: dst+price}\n Map> flightsMap = new HashMap<>();\n for(int[] flight : flights){\n int flightSrc = flight[0];\n int flightDst = flight[1];\n int flightPrice = flight[2];\n \n List flightsList = flightsMap.getOrDefault(flightSrc, new ArrayList<>());\n flightsList.add(new int[]{flightDst, flightPrice});\n flightsMap.put(flightSrc, flightsList);\n }\n \n // Start Bellman ford Algo\n Queue q = new LinkedList<>();\n q.offer(src);\n while(k >= 0 && !q.isEmpty()){\n int[] tempPrices = new int[n]; // Temporary Prices Arr\n for(int i = 0; i < n; i++)\n tempPrices[i] = prices[i];\n \n int size = q.size();\n for(int i = 0; i < size; i++){\n int curSrc = q.poll();\n int curPrice = prices[curSrc];\n List curFlightsList = flightsMap.getOrDefault(curSrc, new ArrayList<>());\n for(int[] flight : curFlightsList){\n int flightDst = flight[0];\n int flightPrice = flight[1];\n int newPrice = curPrice + flightPrice;\n if(newPrice < tempPrices[flightDst]){\n tempPrices[flightDst] = newPrice;\n q.offer(flightDst);\n }\n }\n }\n for(int i = 0; i < n; i++) // Copy Temp Prices to Original Price Arr\n prices[i] = tempPrices[i];\n k--;\n }\n int totalPrice = prices[dst];\n return totalPrice == Integer.MAX_VALUE? -1 : totalPrice;\n }\n}", "solution_c": "class Solution {\npublic:\n #define f first\n #define s second\n int findCheapestPrice(int n, vector>& flights, int src, int dst, int k){\n priority_queue< array, vector>, greater>> pq;\n unordered_map>> g;\n\n for(auto& f : flights){\n g[f[0]].push_back({f[1],f[2]});\n }\n vector dis(n,INT_MAX);\n pq.push({0,src,0});\n while(!pq.empty()){\n int c = pq.top()[0];\n int cur = pq.top()[1];\n int lvl = pq.top()[2];\n pq.pop();\n if(cur==dst) return c;\n if(lvl > k || lvl >= dis[cur]) continue;\n dis[cur] = lvl;\n for(auto& nei : g[cur]){\n pq.push({c+nei.s, nei.f, lvl+1});\n }\n }\n return -1;\n }\n};" }, { "title": "Restore IP Addresses", "algo_input": "A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.\n\n\n\tFor example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\", \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses.\n\n\nGiven a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.\n\n \nExample 1:\n\nInput: s = \"25525511135\"\nOutput: [\"255.255.11.135\",\"255.255.111.35\"]\n\n\nExample 2:\n\nInput: s = \"0000\"\nOutput: [\"0.0.0.0\"]\n\n\nExample 3:\n\nInput: s = \"101023\"\nOutput: [\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 20\n\ts consists of digits only.\n\n", "solution_py": "class Solution:\n def restoreIpAddresses(self, s: str):\n def isValid(st):\n if(len(st)!=len(str(int(st)))):\n return False\n st = int(st)\n if(st>255 or st<0):\n return False\n return True\n \n validIps = []\n for i in range(1,4):\n s1 = s[:i]\n if(not isValid(s1)):\n continue\n for j in range(i+1, min(len(s), i+4)):\n s2 = s[i:j]\n if(not isValid(s2)):\n continue\n for k in range(j+1,min(len(s), j+4)):\n s3 = s[j:k]\n if(not isValid(s3)):\n continue\n s4 = s[k:]\n if(not isValid(s4)):\n continue\n currentIp = s1+\".\"+s2+\".\"+s3+\".\"+s4\n validIps.append(currentIp)\n return validIps", "solution_js": "var restoreIpAddresses = function(s) {\n const results = [];\n\n const go = (str, arr) => {\n // if we used every character and have 4 sections, it's a good IP!\n if (str.length === 0 && arr.length === 4) {\n results.push(arr.join('.'));\n return;\n }\n // we already have too many in the array, let's just stop\n if (arr.length >= 4) {\n return;\n }\n // chop off next 3 characters and continue recursing\n if (str.length > 2 && +str.substring(0, 3) < 256 && +str.substring(0, 3) > 0 && str[0] !== '0') {\n go(str.slice(3), [...arr, str.substring(0, 3)]);\n }\n // chop off next 2 characters and continue recursing\n if (str.length > 1 && +str.substring(0, 2) > 0 && str[0] !== '0') {\n go(str.slice(2), [...arr, str.substring(0, 2)]);\n }\n // chop off next 1 character and continue recursing, in this case, starting with 0 is OK\n if (str.length > 0 && +str.substring(0, 1) >= 0) {\n go(str.slice(1), [...arr, str.substring(0, 1)]);\n }\n return;\n }\n\n go(s, []);\n\n return results;\n};", "solution_java": "class Solution {\n public List restoreIpAddresses(String s) {\n List ans = new ArrayList<>();\n\n int len = s.length();\n for(int i = 1; i < 4 && i < len-2 ; i++ ){\n for(int j = i + 1; j < i + 4 && j < len-1 ; j++ ){\n for(int k = j+1 ; k < j + 4 && k < len ; k++){\n String s1 = s.substring(0,i);\n String s2 = s.substring(i,j);\n String s3 = s.substring(j,k);\n String s4 = s.substring(k,len);\n if(isValid(s1) && isValid(s2) && isValid(s3) && isValid(s4))\n ans.add(s1+\".\"+s2+\".\"+s3+\".\"+s4);\n }\n }\n }\n return ans;\n }\n boolean isValid(String s){\n if(s.length() > 3 || s.length()==0 || (s.charAt(0)=='0' && s.length()>1) || Integer.parseInt(s) > 255)\n return false;\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n vector res;\n void dfs(string s,int idx,string curr_ip,int cnt)\n {\n if(cnt>4)\n return;\n if(cnt==4&&idx==s.size())\n {\n res.push_back(curr_ip);\n // return;\n }\n for(int i=1;i<4;i++)\n {\n if(idx+i>s.size())\n break;\n string str=s.substr(idx,i);\n if((str[0]=='0'&&str.size()>1)||(i==3&&stoi(str)>=256))\n continue;\n dfs(s,idx+i,curr_ip+str+(cnt==3?\"\":\".\"),cnt+1);\n }\n }\n vector restoreIpAddresses(string s)\n {\n dfs(s,0,\"\",0);\n return res;\n \n \n }\n};" }, { "title": "Split Array into Consecutive Subsequences", "algo_input": "You are given an integer array nums that is sorted in non-decreasing order.\n\nDetermine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:\n\n\n\tEach subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).\n\tAll subsequences have a length of 3 or more.\n\n\nReturn true if you can split nums according to the above conditions, or false otherwise.\n\nA subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).\n\n \nExample 1:\n\nInput: nums = [1,2,3,3,4,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5\n\n\nExample 2:\n\nInput: nums = [1,2,3,3,4,4,5,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,4,5]\nOutput: false\nExplanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-1000 <= nums[i] <= 1000\n\tnums is sorted in non-decreasing order.\n\n", "solution_py": "class Solution:\n\n from collections import defaultdict\n\n def isPossible(self, nums):\n # If the length of the array is less than 3, it's not possible to create subsequences of length 3 or more.\n if len(nums) < 3:\n return False\n\n # 'count' dictionary stores the frequency of each number in the input array.\n count = defaultdict(int)\n\n # 'tails' dictionary stores the number of subsequences that end at a certain number.\n tails = defaultdict(int)\n\n # Populate the 'count' dictionary with the frequency of each number.\n for num in nums:\n count[num] += 1\n\n # Iterate through the input array.\n for num in nums:\n # If the count of the current number is 0, it means this number has already been used in a subsequence.\n if count[num] == 0:\n continue\n # If there is a subsequence that ends with the current number minus 1,\n # it means we can extend that subsequence by adding the current number.\n elif tails[num - 1] > 0:\n tails[num - 1] -= 1 # Decrease the count of the tails that end with the current number minus 1.\n tails[num] += 1 # Increase the count of the tails that end with the current number.\n # If there are enough numbers after the current number to form a subsequence,\n # create a new subsequence starting with the current number.\n elif count[num + 1] > 0 and count[num + 2] > 0:\n count[num + 1] -= 1 # Decrease the count of the next number.\n count[num + 2] -= 1 # Decrease the count of the number after the next number.\n tails[num + 2] += 1 # Increase the count of the tails that end with the number after the next number.\n else:\n # If we can't extend an existing subsequence or start a new one, return False.\n return False\n\n # Decrease the count of the current number since it's used in a subsequence.\n count[num] -= 1\n\n # If the function successfully iterates through the entire array, return True.\n return True", "solution_js": "var isPossible = function(nums) {\n\tconst need = new Map();\n\tconst hash = nums.reduce((map, num) => {\n\t\tconst count = map.get(num) ?? 0;\n\t\tmap.set(num, count + 1);\n\t\treturn map;\n\t}, new Map());\n\n\tfor (const num of nums) {\n\t\tconst current = hash.get(num);\n\t\tif (current === 0) continue;\n\n\t\tconst currentNeed = need.get(num);\n\t\tconst next1 = hash.get(num + 1);\n\t\tconst next2 = hash.get(num + 2);\n\t\tif (currentNeed > 0) {\n\t\t\tconst need1 = need.get(num + 1) ?? 0;\n\t\t\tneed.set(num, currentNeed - 1);\n\t\t\tneed.set(num + 1, need1 + 1);\n\t\t} else if (next1 > 0 && next2 > 0) {\n\t\t\tconst need3 = need.get(num + 3) ?? 0;\n\t\t\thash.set(num + 1, next1 - 1);\n\t\t\thash.set(num + 2, next2 - 1);\n\t\t\tneed.set(num + 3, need3 + 1);\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t\thash.set(num, current - 1);\n\t}\n\treturn true;\n};", "solution_java": "class Solution {\n public boolean isPossible(int[] nums) {\n int[] freq = new int[2002], subEnd = new int[2002];\n for (int i : nums) {\n int num = i + 1001;\n freq[num]++;\n }\n for (int i : nums) {\n int num = i + 1001;\n if (freq[num] == 0) continue; // Num already in use\n freq[num]--;\n if (subEnd[num - 1] > 0) { // Put into existing subsequence\n subEnd[num - 1]--;\n subEnd[num]++;\n }\n // New subsequence of size 3 is possible\n else if (freq[num + 1] > 0 && freq[num + 2] > 0) {\n freq[num + 1]--;\n freq[num + 2]--;\n subEnd[num + 2]++; // New subsequence\n } else return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPossible(vector& nums) {\n priority_queue, greater> pq;\n unordered_map um;\n for(int &num : nums)\n {\n pq.push(num);\n um[num]++;\n }\n queue q;\n int count = 0, prev;\n while(!pq.empty())\n {\n if(count == 0)\n {\n prev = pq.top();\n pq.pop();\n count++;\n }\n else if(pq.top() == prev+1)\n {\n if(um[pq.top()] >= um[prev])\n {\n um[prev]--;\n pq.pop();\n prev += 1;\n count++;\n }\n else if(um[pq.top()] < um[prev])\n {\n um[prev]--;\n if(count <= 2) return false;\n while(!q.empty())\n {\n pq.push(q.front());\n q.pop();\n }\n count = 0;\n }\n }\n else if(pq.top() == prev)\n {\n q.push(pq.top());\n pq.pop();\n if(pq.empty())\n {\n if(count <= 2) return false;\n while(!q.empty())\n {\n pq.push(q.front());\n q.pop();\n }\n count = 0;\n }\n }\n else if(pq.top() > prev+1)\n {\n if(count <= 2) return false;\n\n while(!q.empty())\n {\n pq.push(q.front());\n q.pop();\n }\n count = 0;\n }\n }\n if(count > 0 && count <= 2) return false;\n return true;\n }\n};" }, { "title": "Equal Sum Arrays With Minimum Number of Operations", "algo_input": "You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.\n\nReturn the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1​​​​​ if it is not possible to make the sum of the two arrays equal.\n\n \nExample 1:\n\nInput: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n\n\nExample 2:\n\nInput: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput: -1\nExplanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\n\n\nExample 3:\n\nInput: nums1 = [6,6], nums2 = [1]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 105\n\t1 <= nums1[i], nums2[i] <= 6\n\n", "solution_py": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \n\t\t# step1. determine the larger array and the smaller array, and get the difference on sum\n sum1 = sum(nums1)\n sum2 = sum(nums2)\n \n if sum1==sum2:\n return 0\n elif sum1>sum2:\n larger_sum_nums = nums1\n smaller_sum_nums = nums2\n else:\n larger_sum_nums = nums2\n smaller_sum_nums = nums1\n\t\t\n sum_diff = abs(sum1-sum2)\n \n # step2. calculate the max \"gain\" at each position (how much difference we can reduce if operating on that position) \n gains_in_larger_array = [num-1 for num in larger_sum_nums]\n gains_in_smaller_array = [6-num for num in smaller_sum_nums]\n \n\t\t# step3. sort the \"gain\" and check the least number of steps to reduce the difference to 0\n gains = gains_in_larger_array + gains_in_smaller_array\n gains.sort(reverse = True)\n \n count = 0\n target_diff = sum_diff\n \n for i in range(len(gains)):\n target_diff -= gains[i]\n count += 1\n \n if target_diff <= 0:\n return count\n\t\t\n\t\t# return -1 if the difference still cannot be reduced to 0 even after operating on all positions\n return -1", "solution_js": "var minOperations = function(nums1, nums2) {\n /*\n Two impossible cases:\n min1...max1 ... min2...max2 -> we can't make them equal\n min2...max2 ... min1...max1 -> we can't make them equal\n */\n let min1 = nums1.length * 1;\n let max1 = nums1.length * 6;\n let min2 = nums2.length * 1;\n let max2 = nums2.length * 6;\n if (min2 > max1 || min1 > max2) {\n return -1;\n }\n let sum1 = nums1.reduce((acc,cur) => acc + cur);\n let sum2 = nums2.reduce((acc,cur) => acc + cur);\n if (sum1 === sum2) return 0;\n if (sum1 < sum2) {\n return helper(nums1, nums2, sum1, sum2);\n } else {\n return helper(nums2, nums1, sum2, sum1);\n }\n // T.C: O(M + N), M = # of nums1, N = # of nums2\n // S.C: O(1)\n};\n\n// Condition: sum of A < sum of B\n// the idea is to add the maximum possible value to sumA and\n// subtract the maximum possible value from sumB so that\n// we make sumA >= sumB as soon as possible\nfunction helper(A, B, sumA, sumB) {\n let freqA = new Array(7).fill(0);\n let freqB = new Array(7).fill(0);\n for (let i = 0; i < A.length; i++) {\n freqA[A[i]]++;\n }\n for (let i = 0; i < B.length; i++) {\n freqB[B[i]]++;\n }\n let count = 0;\n for (let i = 1; i <= 6; i++) {\n // increase sumA\n while (freqA[i] > 0 && sumA < sumB) {\n sumA += 6-i;\n freqA[i]--;\n count++;\n }\n let j = 7-i;\n // decrease sumB\n while (freqB[j] > 0 && sumA < sumB) {\n sumB -= j-1;\n freqB[j]--;\n count++;\n }\n if (sumA >= sumB) break;\n }\n return count;\n}", "solution_java": "class Solution {\n public int minOperations(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length;\n if (m > 6 * n || n > 6 * m) return -1;\n\n int sum1 = 0, sum2 = 0;\n for (int i : nums1) sum1 += i;\n for (int i : nums2) sum2 += i;\n\n int diff = sum1 - sum2;\n if (diff == 0) return 0;\n\n return (diff > 0 ? helper(nums1, nums2, diff)\n : helper(nums2, nums1, -diff));\n }\n\n private int helper(int[] nums1, int[] nums2, int diff) {\n // count[i] : frequency of numbers that can reduce the diff by i\n int[] count = new int[6];\n for (int num : nums1) count[num - 1]++;\n for (int num : nums2) count[6 - num]++;\n\n int res = 0;\n for (int i = 5; i > 0; i--) {\n int c = Math.min(count[i], diff / i + (diff % i == 0 ? 0 : 1));\n\n res += c;\n diff -= c * i;\n\n if (diff <= 0) break;\n }\n return res;\n }\n}", "solution_c": "/**\n * @brief\n * Given two array, return the minimum numbers we have to change the values to make two arrays sum equal\n *\n * [Observation]\n * Since the value is from 1 ~ 6\n *\n * Min sum of the array = len(arr)\n * Max sum of the array = 6 len(arr)\n *\n * When to arrays range cannot overlap -> no answer\n *\n * If there is a answer -> sum s, value will be between s1 and s2\n * So, let's say if s1 is smaller, we would like to increase s1's element and decrease s2's element\n * -> We only have to design for s1 is smaller than s2.\n *\n * [Key] Which element's should we increase and decrease?\n * To minimize the changing elements, we change the number who can mostly decrease the differences.\n * So, we compare the smallest element in num1 and largest in num2.\n * -> sorting\n *\n * @algo sorting + greedy\n * Time O(NlogN) for sorting\n * Space O(1)\n */\nclass Solution {\npublic:\n int minOperations(vector& nums1, vector& nums2) {\n int l1 = nums1.size(); // l1 ~ 6l1\n int l2 = nums2.size(); // l2 ~ 6l2\n\n if(6*l1 < l2 || 6*l2 < l1) {\n return -1;\n }\n\n int sum1 = accumulate(nums1.begin(), nums1.end(), 0);\n int sum2 = accumulate(nums2.begin(), nums2.end(), 0);\n if(sum1 > sum2) return minOperations(nums2, nums1);\n\n sort(nums1.begin(), nums1.end());\n sort(nums2.begin(), nums2.end(), greater());\n // let us design the way where sum1 <= sum2\n int ans = 0, ptr1 = 0, ptr2 = 0;\n int diff = sum2 - sum1;\n\n while(diff > 0) {\n if(ptr2 == l2 || ptr1 < l1 && (6 - nums1[ptr1]) >= (nums2[ptr2] - 1)) {\n diff -= (6 - nums1[ptr1]);\n ans++;\n ptr1++;\n }\n else {\n diff -= (nums2[ptr2] - 1);\n ans++;\n ptr2++;\n }\n }\n return ans;\n }\n};" }, { "title": "Longest Arithmetic Subsequence of Given Difference", "algo_input": "Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.\n\nA subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.\n\n \nExample 1:\n\nInput: arr = [1,2,3,4], difference = 1\nOutput: 4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].\n\nExample 2:\n\nInput: arr = [1,3,5,7], difference = 1\nOutput: 1\nExplanation: The longest arithmetic subsequence is any single element.\n\n\nExample 3:\n\nInput: arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput: 4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t-104 <= arr[i], difference <= 104\n\n", "solution_py": "class Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n d = defaultdict(int)\n for num in arr:\n if num - difference in d:\n d[num] = d[num - difference] + 1\n else:\n d[num] = 1\n return max((d[x] for x in d))", "solution_js": "var longestSubsequence = function(arr, difference) {\n const map = new Map()\n let max = 0\n for(let num of arr) {\n const prev = map.has(num - difference) ? map.get(num -difference) : 0\n const val = prev + 1\n map.set(num, val)\n max = Math.max(max, val)\n }\n return max\n};", "solution_java": "class Solution {\n public int longestSubsequence(int[] arr, int difference) {\n int max = 1;\n Map map = new HashMap<>();\n for (int i = 0; i < arr.length; i++) {\n // find the target element using the current element and the given difference\n int target = arr[i] - difference;\n // find if an AP for the target element exists in map and its length (else default to 1 - each element is an AP)\n int currAns = map.getOrDefault(target, 0) + 1;\n // add the current answer to the map\n // the amswer will override any previous answers with the same key (with an equal or greater answer)\n // for eg, in this case: .......X.....X\n // here X is the same number but the 2nd X will have an equal or larger AP sequence (logically)\n map.put(arr[i], currAns);\n // get max answer\n max = Math.max(max, currAns);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestSubsequence(vector& arr, int difference) {\n \n int n = arr.size();\n \n unordered_mapmp;\n multisets;\n int ans = 1;\n \n for(int i=0;i bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[1]\n #since we have odd number of complimenting residues,\n #we should also care about residue=0 and residue=k//2\n \n i,j =1,k-1\n pairs = 0\n while i0 and i==j:\n pairs+=count[i]/2\n pairs+= count[0]/2\n n = len(arr)\n return pairs == n//2", "solution_js": "var canArrange = function(arr, k) {\n let map = new Map();\n let index = 0;\n for(let i = 0; i < arr.length; i++){\n let val = arr[i] % k;\n if(val<0) val+=k;\n if(map.get(k-val)) map.set(k-val, map.get(k-val) - 1), index--;\n else if(map.get(-val)) map.set(-val, map.get(-val) - 1), index--;\n else map.set(val, map.get(val) + 1 || 1), index++;\n }\n return !index;\n};", "solution_java": "class Solution {\n public boolean canArrange(int[] arr, int k) {\n int[] frequency = new int[k];\n for(int num : arr){\n num %= k;\n if(num < 0) num += k;\n frequency[num]++;\n }\n if(frequency[0]%2 != 0) return false;\n \n for(int i = 1; i <= k/2; i++)\n if(frequency[i] != frequency[k-i]) return false;\n\t\t\t\n return true;\n }\n}", "solution_c": "//ask the interviewer\n//can we have negative values?\n\nclass Solution {\npublic:\n bool canArrange(vector& arr, int k)\n {\n unordered_mapmemo;//remainder : occurence\n\n //we are storing the frequency of curr%k\n //i.e. the frequency of the remainder\n for(auto curr : arr)\n {\n int remainder = ((curr%k)+k)%k;\n memo[remainder]++;\n }\n\n for(int i =1; i<=k/2; i++)\n {\n if(memo[i] != memo[k-i])\n return false;\n }\n if(memo[0]%2 != 0)\n return false;\n return true;\n }\n};" }, { "title": "Power of Four", "algo_input": "Given an integer n, return true if it is a power of four. Otherwise, return false.\n\nAn integer n is a power of four, if there exists an integer x such that n == 4x.\n\n \nExample 1:\nInput: n = 16\nOutput: true\nExample 2:\nInput: n = 5\nOutput: false\nExample 3:\nInput: n = 1\nOutput: true\n\n \nConstraints:\n\n\n\t-231 <= n <= 231 - 1\n\n\n \nFollow up: Could you solve it without loops/recursion?", "solution_py": "import math \nclass Solution:\n def isPowerOfFour(self, n: int) -> bool:\n\n if n <= 0:\n return False\n return math.log(n, 4).is_integer()", "solution_js": "var isPowerOfFour = function(n) {\n if(n==1){\n return true\n }\n let a=1;\n for(let i=2;i<=30;i++){\n a=a*4\n if(a===n){\n return true\n }\n }\n return false\n};", "solution_java": "class Solution {\n public boolean isPowerOfFour(int n) {\n return (Math.log10(n)/Math.log10(4))%1==0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPowerOfFour(int n) {\n if(n==1)\n return true;\n long long p=1;\n for(int i=1;in)\n return false;\n }\n return false;\n }\n};" }, { "title": "Diagonal Traverse II", "algo_input": "Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.\n\n \nExample 1:\n\nInput: nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,4,2,7,5,3,8,6,9]\n\n\nExample 2:\n\nInput: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i].length <= 105\n\t1 <= sum(nums[i].length) <= 105\n\t1 <= nums[i][j] <= 105\n\n", "solution_py": "class Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n\t\t# sort the index of element\n heap = list()\n n = len(nums)\n for i in range(n):\n m = len(nums[i])\n for j in range(m):\n heapq.heappush(heap,[i+j,j,i])\n\t\t\t\t\n\t\t# append the element one by one\n ans = []\n while heap:\n temp = heapq.heappop(heap)\n ans.append(nums[temp[2]][temp[1]])\n return ans", "solution_js": "var findDiagonalOrder = function(nums) {\n let vals = []; // [row, diagonal value, actual value]\n for (let i = 0; i < nums.length; i++) {\n for (let j = 0; j < nums[i].length; j++) {\n vals.push([i, i + j, nums[i][j]]);\n }\n }\n vals.sort((a, b) => {\n if (a[1] === b[1]) return b[0] - a[0];\n return a[1] - b[1];\n })\n return vals.map(val => val[2]);\n};", "solution_java": "\tclass Solution {\npublic int[] findDiagonalOrder(List> nums) {\n HashMap> map = new HashMap();\n \n for(int i = 0 ; i < nums.size() ; i++){\n for(int j = 0 ; j < nums.get(i).size() ; j++){\n int z = i + j;\n if(map.containsKey(z)){\n map.get(z).add(nums.get(i).get(j));\n }else{\n Stack stk = new Stack<>();\n stk.push(nums.get(i).get(j));\n map.put(z , stk);\n }\n }\n }\n ArrayList arr = new ArrayList<>();\n int k = 0;\n while(true){\n if(map.containsKey(k)){\n int size = map.get(k).size();\n while(size-- > 0){\n arr.add(map.get(k).pop());\n }\n k++;\n }else{\n break;\n }\n }\n int[] res = new int[arr.size()];\n for(int i = 0 ; i < res.length ; i++){\n res[i] = arr.get(i);\n }\n \n return res;\n}}", "solution_c": "class Solution {\npublic:\n vector findDiagonalOrder(vector>& nums) {\n int n = nums.size();\n int m = 0;\n for(vector &v : nums)\n {\n int y = v.size();\n m = max(m, y);\n }\n vector D2[n+m-1];\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < nums[i].size(); j++)\n {\n D2[i+j].push_back(nums[i][j]);\n }\n }\n vector ans;\n for(int i = 0; i < n+m-1; i++)\n {\n int x = D2[i].size();\n while(x--)\n {\n ans.push_back(D2[i][x]);\n D2[i].pop_back();\n }\n }\n return ans;\n }\n};" }, { "title": "Add Binary", "algo_input": "Given two binary strings a and b, return their sum as a binary string.\n\n \nExample 1:\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\nExample 2:\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n\n \nConstraints:\n\n\n\t1 <= a.length, b.length <= 104\n\ta and b consist only of '0' or '1' characters.\n\tEach string does not contain leading zeros except for the zero itself.\n\n", "solution_py": "class Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n\n return str(bin(int(a, base = 2)+int(b, base = 2)))[2:]", "solution_js": "var addBinary = function(a, b) {\n let i = a.length-1, j = b.length-1, carry = 0\n let s =[]\n while(i >= 0 || j >= 0){\n let sum = carry\n if(i >= 0) sum += a[i--].charCodeAt() - 48\n if(j >= 0) sum += b[j--].charCodeAt() - 48\n s.unshift(sum % 2)\n carry = ~~(sum/2)\n }\n return carry > 0 ? \"1\" + s.join(\"\") : s.join(\"\")\n};", "solution_java": "class Solution {\n public String addBinary(String a, String b) {\n StringBuilder sb = new StringBuilder();\n int carry = 0;\n int i= a.length() -1;\n int j= b.length() -1;\n while(i>=0 || j>=0){\n int sum = carry;\n if(i>=0)\n sum+=a.charAt(i--)-'0'; // -'0' is just to convert char in integer\n if(j>=0)\n sum+=b.charAt(j--)-'0';\n sb.append(sum%2); // If we have sum = 1 1 then = 2 % 2 = 0 and 0 1 = 1 % 2 = 1\n carry = sum /2;\n }\n if(carry>0)\n sb.append(carry);\n return sb.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string addBinary(string a, string b) {\n string ans;\n int i=a.length()-1,j=b.length()-1;\n int carry=0;\n while(carry||i>=0||j>=0){\n if(i>=0){\n carry+=a[i]-'0';\n i--;\n }\n if(j>=0){\n carry+=b[j]-'0';\n j--;\n }\n ans+=carry%2+'0';\n carry=carry/2;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n};" }, { "title": "Longest Uncommon Subsequence I", "algo_input": "Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1.\n\nAn uncommon subsequence between two strings is a string that is a subsequence of one but not the other.\n\nA subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n\n\n\tFor example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"aebdc\" to get \"abc\". Other subsequences of \"aebdc\" include \"aebdc\", \"aeb\", and \"\" (empty string).\n\n\n \nExample 1:\n\nInput: a = \"aba\", b = \"cdc\"\nOutput: 3\nExplanation: One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.\n\n\nExample 2:\n\nInput: a = \"aaa\", b = \"bbb\"\nOutput: 3\nExplanation: The longest uncommon subsequences are \"aaa\" and \"bbb\".\n\n\nExample 3:\n\nInput: a = \"aaa\", b = \"aaa\"\nOutput: -1\nExplanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.\n\n\n \nConstraints:\n\n\n\t1 <= a.length, b.length <= 100\n\ta and b consist of lower-case English letters.\n\n", "solution_py": "class Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a == b:\n return -1\n\n else:\n return max(len(a), len(b))", "solution_js": "var findLUSlength = function(a, b) {\n if (a===b) return -1\n return Math.max(a.length,b.length)\n\n};", "solution_java": "class Solution {\n public int findLUSlength(String a, String b) {\n if(a.equals(b)) return -1;\n return Math.max(a.length(),b.length());\n }\n}", "solution_c": "class Solution {\npublic:\n int findLUSlength(string a, string b) {\n if(a==b){\n return -1;\n }\n if(a.size()>=b.size()){\n return a.size();\n }\n return b.size();\n }\n};" }, { "title": "Queue Reconstruction by Height", "algo_input": "You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.\n\nReconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).\n\n \nExample 1:\n\nInput: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:\nPerson 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\n\n\nExample 2:\n\nInput: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n\n\n \nConstraints:\n\n\n\t1 <= people.length <= 2000\n\t0 <= hi <= 106\n\t0 <= ki < people.length\n\tIt is guaranteed that the queue can be reconstructed.\n\n", "solution_py": "class Solution:\n\tdef reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n\t\tn = len(people)\n\t\tpeople.sort()\n\t\tans = [[]]*n\n\t\ti = 0\n\t\twhile people:\n\t\t\th,p = people.pop(0)\n\t\t\tcount= p\n\t\t\tfor i in range(n):\n\t\t\t\tif count== 0 and ans[i] == []:\n\t\t\t\t\tans[i] = [h,p]\n\t\t\t\t\tbreak\n\n\t\t\t\telif not ans[i] or (ans[i] and ans[i][0] >= h ):\n\t\t\t\t\tcount -= 1\n\t\treturn ans", "solution_js": "var reconstructQueue = function(people) {\n var queue = new Array(people.length);\n people = people.sort((a,b) => (a[0]-b[0]));\n for(let i =0;i= people[i][0]){\n count++;\n }\n }\n }\n return queue;\n};", "solution_java": "class Solution {\n public int[][] reconstructQueue(int[][] people) {\n List result = new ArrayList<>(); //return value\n\n Arrays.sort(people, (a, b) -> {\n int x = Integer.compare(b[0], a[0]);\n if(x == 0) return Integer.compare(a[1], b[1]);\n else return x; });\n\n for(int[] p: people)\n result.add(p[1], p);\n\n return result.toArray(new int[people.length][2]);\n }\n}", "solution_c": "#include \n\nusing namespace std;\nstruct node {\n int h, k;\n node *next;\n node(int h, int k) : h(h), k(k), next(nullptr){}\n};\n\nbool cmp(vector& p1, vector& p2) {\n return (p1[0] != p2[0]) ? (p1[0] > p2[0]) : (p1[1] < p2[1]);\n}\n\nvoid insert(vector& p, node **target) {\n node *new_p = new node(p[0], p[1]);\n new_p->next = (*target)->next;\n (*target)->next = new_p;\n}\n\nclass Solution {\n public:\n vector> reconstructQueue(vector>& people) {\n sort(people.begin(), people.end(), cmp);\n vector& first = people[0];\n node *head = new node(0, 0);//pseu\n node **target;\n int step;\n for (int i = 0; i < people.size(); i++) {\n vector& p = people[i];\n for (target = &head, step=p[1]; step > 0; target=&((*target)->next), step--);\n insert(p, target);\n }\n vector> ans;\n ans.resize(people.size());\n int i = 0;\n for(node *cur = head->next; cur != nullptr; cur = cur->next)\n ans[i++] = vector({cur->h, cur->k});\n //formally, we should free the list later.\n return ans;\n }\n};" }, { "title": "Longest Univalue Path", "algo_input": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.\n\nThe length of the path between two nodes is represented by the number of edges between them.\n\n \nExample 1:\n\nInput: root = [5,4,5,1,1,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 5).\n\n\nExample 2:\n\nInput: root = [1,4,5,4,4,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 4).\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-1000 <= Node.val <= 1000\n\tThe depth of the tree will not exceed 1000.\n\n", "solution_py": "class Solution:\n\tmax_path=0\n\tdef longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n\t\tself.dfs(root);\n\t\treturn self.max_path\n\n\tdef dfs(self,root):\n\t\tif root is None:return 0\n\t\tleft=self.dfs(root.left)\n\t\tright=self.dfs(root.right)\n\n\t\tif root.left and root.left.val == root.val:\n\t\t\tleftPath=left+1\n\t\telse:\n\t\t\tleftPath=0\n\n\t\tif root.right and root.right.val == root.val:\n\t\t\trightPath=right+1\n\t\telse:\n\t\t\trightPath=0\n\n\t\tself.max_path = max(self.max_path, leftPath + rightPath)\n\t\treturn max(leftPath, rightPath)", "solution_js": "var longestUnivaluePath = function(root) {\n\tlet max = 0;\n\tconst dfs = (node = root, parentVal) => {\n\t\tif (!node) return 0;\n\t\tconst { val, left, right } = node;\n\t\tconst leftPath = dfs(left, val);\n\t\tconst rightPath = dfs(right, val);\n\n\t\tmax = Math.max(max, leftPath + rightPath);\n\t\treturn val === parentVal \n\t\t\t? Math.max(leftPath, rightPath) + 1\n\t\t\t: 0;\n\t};\n\n\tdfs();\n\treturn max;\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 int maxLen = 0;\n public int longestUnivaluePath(TreeNode root) {\n lup(root);\n return maxLen;\n }\n public int lup(TreeNode root) {\n if (root == null) {\n return 0;\n }\n int left = lup(root.left);\n int right = lup(root.right);\n int leftMax = 0;\n int rightMax = 0;\n if (root.left != null && root.val == root.left.val) {\n leftMax = left + 1;\n }\n if (root.right != null && root.val == root.right.val) {\n rightMax = right + 1;\n }\n maxLen = Math.max(maxLen, leftMax + rightMax);\n return Math.max(leftMax, rightMax);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxlen=0;\n pair util(TreeNode* root,int val ){\n if(!root)\n return {0,-1001};\n\n // in pair we will the first part will return the no nodes ,\n //and in the second part we will return the value associated with it\n\n pair l=util(root->left,root->val);\n pair r=util(root->right,root->val);\n\n /* now we will check whether the value coming from\n the left subtree or(&) right subtree is equal to the\n value of the current node\n\n if equal to both the left && right subtree, then the length returned\n will be max of the left & right subtree , becuase ATQ, we have to\n return the longest path where each node in the path has the same\n value , therefore from the current node we can travel to either the\n left or right subtree , but the maxlength can be l.first+r.first+1 ,\n because we can travel from the leftmost node through the current\n node to the rightmost node , which will be a valid path , therefore\n we will compare this with the maxlength\n\n */\n if(l.second==root->val && r.second==root->val){\n maxlen=max(maxlen,l.first+r.first+1);\n return {max(l.first,r.first)+1,root->val};\n\n }\n\n // now similary checking for all the other nodes:\n\n else if(l.second==root->val){\n maxlen=max(maxlen,l.first+1);\n return {l.first+1,root->val};\n }\n else if(r.second==root->val){\n maxlen=max(maxlen,r.first+1);\n return {r.first+1,root->val};\n }\n else{\n return {1,root->val};\n }\n\n }\n int longestUnivaluePath(TreeNode* root) {\n if(!root)\n return 0;\n util(root,root->val);\n return max(maxlen-1,0);\n\n }\n};" }, { "title": "Form Largest Integer With Digits That Add up to Target", "algo_input": "Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:\n\n\n\tThe cost of painting a digit (i + 1) is given by cost[i] (0-indexed).\n\tThe total cost used must be equal to target.\n\tThe integer does not have 0 digits.\n\n\nSince the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\".\n\n \nExample 1:\n\nInput: cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput: \"7772\"\nExplanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\nDigit cost\n 1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5\n\n\nExample 2:\n\nInput: cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput: \"85\"\nExplanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n\n\nExample 3:\n\nInput: cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput: \"0\"\nExplanation: It is impossible to paint any integer with total cost equal to target.\n\n\n \nConstraints:\n\n\n\tcost.length == 9\n\t1 <= cost[i], target <= 5000\n\n", "solution_py": "from functools import lru_cache\nclass Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n @lru_cache(None)\n def dfs(t):\n if t == 0: return 0\n res = float('-inf')\n for digit in range(1,10):\n if t - cost[digit-1] >= 0:\n res = max(res, dfs(t - cost[digit-1])*10+digit)\n return res\n res = dfs(target)\n return \"0\" if res == float('-inf') else str(res)", "solution_js": "var largestNumber = function(cost, target) {\n const arr = new Array(target+1).fill('#');\n arr[0] = '';\n \n for (let i = 0; i < 9; i++) {\n for (let j = cost[i]; j <= target; j++) {\n if (arr[j-cost[i]] !== '#' && arr[j-cost[i]].length + 1 >= arr[j].length) {\n arr[j] = (i+1).toString().concat(arr[j-cost[i]]);\n }\n }\n }\n \n return arr[target] == '#' ? '0' : arr[target];\n};", "solution_java": "// Space Complexity = O(N*M) (N == length of cost array and M == target )\n// Time Complexity = O(N*M)\n\nclass Solution {\n Map map = new HashMap<>();\n String[][] memo;\n public String largestNumber(int[] cost, int target) {\n memo = new String[cost.length+1][target+1];\n \n for( int i = 0;i<=cost.length;i++ ){\n for(int j = 0;j<=target;j++) memo[i][j] = \"0\";\n }\n \n String res = helper(cost,cost.length-1,target);\n \n return res == \"-1\" ? \"0\" : res; \n \n }\n \n public String helper( int[] cost , int index , int target){\n if(target == 0) {\n return \"\";\n }\n \n if(target < 0) return \"-1\";\n \n if(index < 0) return \"-1\";\n \n if( memo[index][target] != \"0\") return memo[index][target];\n \n String str1 = (index+1) + helper(cost,cost.length-1,target-cost[index]) ;\n String str2 = helper(cost,index-1,target);\n \n String res = getBigger(str1,str2);\n \n memo[index][target] = res;\n \n return res;\n }\n \n public String getBigger(String num1 , String num2){\n if( num1.contains(\"-1\") ) return num2;\n if( num2.contains(\"-1\") ) return num1;\n if( num1.length() > num2.length() ) return num1;\n if( num2.length() > num1.length() ) return num2;\n return Double.parseDouble( num1 ) < Double.parseDouble( num2 ) ? num2 : num1;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> dp ;\n string largestNumber(vector& cost, int target) {\n dp.resize(10,vector(target+1,\"-1\"));\n return solve(cost,0,target) ;\n }\n \n string solve(vector& cost,int idx,int target){\n if(!target) return \"\";\n if(target < 0 || idx >= size(cost)) return \"0\"; \n \n if(dp[idx][target]!=\"-1\") return dp[idx][target];\n \n string a = to_string(idx+1) + solve(cost,0,target-cost[idx]);\n string b = solve(cost,idx+1,target);\n \n return dp[idx][target] = a.back() == '0' ? b : b.back() == '0' ? a : size(a) == size(b) ? max(a,b) : size(a) > size(b) ? a : b ;\n }\n};" }, { "title": "Minimum Operations to Make the Array Increasing", "algo_input": "You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.\n\n\n\tFor example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].\n\n\nReturn the minimum number of operations needed to make nums strictly increasing.\n\nAn array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.\n\n \nExample 1:\n\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].\n\n\nExample 2:\n\nInput: nums = [1,5,2,4,1]\nOutput: 14\n\n\nExample 3:\n\nInput: nums = [8]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5000\n\t1 <= nums[i] <= 104\n", "solution_py": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n sol = 0\n last = nums[0]\n\n for i in range(len(nums) - 1):\n if last >= nums[i + 1]:\n sol += last - nums[i + 1] + 1\n last = last + 1\n else:\n last = nums[i + 1]\n \n return sol", "solution_js": "var minOperations = function(nums) {\n if(nums.length < 2) return 0;\n let count = 0;\n for(let i = 1; i nums[i]) {\n num++;\n count += num - nums[i];\n } else {\n num = nums[i];\n }\n }\n \n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int minOperations(vector& nums) {\n int output=0;\n for(int i=0;i int:\n min_possible = sum(min(row) for row in mat)\n if min_possible >= target: return min_possible - target\n curs = {0}\n for row in mat:\n curs = {x + y for x in row for y in curs if x + y <= 2*target}\n return min(abs(target - x) for x in curs)", "solution_js": "var minimizeTheDifference = function(mat, target) {\n const MAX = Number.MAX_SAFE_INTEGER;\n \n const m = mat.length;\n const n = mat[0].length;\n \n const memo = [];\n \n for (let i = 0; i < m; ++i) {\n memo[i] = new Array(4901).fill(MAX);\n }\n \n return topDown(0, 0);\n \n function topDown(row, sum) {\n if (row === m) return Math.abs(target - sum);\n if (memo[row][sum] != MAX) return memo[row][sum];\n \n let min = MAX;\n \n mat[row].sort((a, b) => a - b); \n \n const set = new Set(mat[row]);\n \n for (const num of set) {\n const res = topDown(row + 1, sum + num);\n \n if (res > min) break;\n min = res;\n }\n \n memo[row][sum] = min;\n \n return min;\n }\n};", "solution_java": "class Solution {\n public int minimizeTheDifference(int[][] mat, int target) {\n Integer[][] dp = new Integer[mat.length][5001];\n return minDiff(mat, 0, target,0, dp);\n }\n\n public int minDiff(int[][] mat,int index,int target, int val, Integer[][] dp){\n if(index == mat.length){\n return Math.abs(val - target);\n }\n if(dp[index][val] != null){\n return dp[index][val];\n }\n\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < mat[0].length; i++){\n res = Math.min(res, minDiff(mat, index + 1, target, val + mat[index][i], dp));\n }\n\n return dp[index][val] = res;\n }\n}", "solution_c": "class Solution \n{\npublic:\n int dp[8000][71];\n int n,m;\n int find(vector>&mat,int r,int sum,int &target)\n {\n if(r>=n)\n {\n return abs(sum-target);\n }\n if(dp[sum][r]!=-1)\n {\n return dp[sum][r];\n }\n int ans=INT_MAX;\n for(int i=0;i>& mat, int target) \n {\n memset(dp,-1,sizeof(dp));\n n=mat.size();\n m=mat[0].size();\n return find(mat,0,0,target);\n }\n};" }, { "title": "Count Prefixes of a Given String", "algo_input": "You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.\n\nReturn the number of strings in words that are a prefix of s.\n\nA prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\nOutput: 3\nExplanation:\nThe strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.\n\nExample 2:\n\nInput: words = [\"a\",\"a\"], s = \"aa\"\nOutput: 2\nExplanation:\nBoth of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.\n\n \nConstraints:\n\n\n\t1 <= words.length <= 1000\n\t1 <= words[i].length, s.length <= 10\n\twords[i] and s consist of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n return len([i for i in words if s.startswith(i)])", "solution_js": "var countPrefixes = function(words, s) {\n \n let cont = 0;\n \n for(i = 0; i < words.length; i++){\n for(j = 1; j <= s.length; j++){\n if(words[i] == s.slice(0, j)){\n cont++;\n }\n } \n }\n return cont;\n \n};", "solution_java": "class Solution {\n public int countPrefixes(String[] words, String s) {\n int i = 0;\n int j = 0;\n int count = 0;\n for(int k = 0; k < words.length; k++){\n if(words[k].length() > s.length()){\n continue;\n }\n \n while(i < words[k].length() && words[k].charAt(i) == s.charAt(j)){\n i++;\n j++;\n }\n if(i == words[k].length()){\n count++;\n }\n i = 0;\n j = 0;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countPrefixes(vector& words, string s) {\n int res = words.size();\n\n for (auto && word : words) {\n for (int i = 0; i < word.size(); i++) {\n if (s[i] != word[i]) {\n res--;\n break;\n }\n }\n }\n return res;\n }\n};" }, { "title": "Number of Strings That Appear as Substrings in Word", "algo_input": "Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\nOutput: 3\nExplanation:\n- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.\n\n\nExample 2:\n\nInput: patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\nOutput: 2\nExplanation:\n- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.\n\n\nExample 3:\n\nInput: patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\nOutput: 3\nExplanation: Each of the patterns appears as a substring in word \"ab\".\n\n\n \nConstraints:\n\n\n\t1 <= patterns.length <= 100\n\t1 <= patterns[i].length <= 100\n\t1 <= word.length <= 100\n\tpatterns[i] and word consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n return sum([pattern in word for pattern in patterns])\n\n ", "solution_js": "/**\n * @param {string[]} patterns\n * @param {string} word\n * @return {number}\n */\nvar numOfStrings = function(patterns, word) {\n let result = 0; \n \n for(let char of patterns){\n if(word.includes(char)){\n result++;\n } else{\n result += 0;\n }\n }\n \n return result;\n};", "solution_java": "class Solution {\n public int numOfStrings(String[] patterns, String word) {\n int count = 0;\n for(int i=0;i& patterns, string word) {\n int count=0;\n for(int i=0;i Optional[TreeNode]:\n\t\tif not nums:\n\t\t\treturn None\n\t\tm = max(nums)\n\t\tidx = nums.index(m)\n\t\troot = TreeNode(m)\n\t\troot.left = self.constructMaximumBinaryTree(nums[:idx])\n\t\troot.right = self.constructMaximumBinaryTree(nums[idx+1:])\n\t\treturn root", "solution_js": "var constructMaximumBinaryTree = function(nums) {\n if (nums.length === 0) return null;\n let max = Math.max(...nums);\n let index = nums.indexOf(max);\n let left = nums.slice(0, index);\n let right = nums.slice(index + 1);\n let root = new TreeNode(max);\n root.left = constructMaximumBinaryTree(left);\n root.right = constructMaximumBinaryTree(right);\n return root;\n};", "solution_java": "class Solution {\n public TreeNode constructMaximumBinaryTree(int[] nums) {\n TreeNode root = construct(nums,0,nums.length-1);\n return root;\n }\n \n private TreeNode construct(int []nums, int start, int end) {\n if(start > end)\n return null;\n if(start == end)\n return new TreeNode(nums[start]);\n \n int maxIdx = findMax(nums,start,end);\n TreeNode root = new TreeNode(nums[maxIdx]);\n \n root.left = construct(nums,start,maxIdx-1);\n root.right = construct(nums,maxIdx+1,end);\n \n return root;\n }\n \n private int findMax(int []arr, int low, int high) {\n int idx = -1, max = Integer.MIN_VALUE;\n for(int i=low;i<=high;++i) \n if(arr[i]>max) {\n max = arr[i];\n idx = i;\n }\n return idx;\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 TreeNode* constructMaximumBinaryTree(vector& nums) \n {\n return recur(0, nums.size() - 1, nums);\n }\n \n TreeNode* recur(int st, int en, vector &ar)\n {\n if(st > en)\n {\n return NULL;\n }\n TreeNode* cur = new TreeNode();\n int maxm = -1, ind;\n for(int i = st; i <= en; i++)\n {\n if(maxm < ar[i])\n {\n maxm = ar[i];\n ind = i;\n }\n }\n \n cur->val = ar[ind];\n cur->left = recur(st, ind-1, ar);\n cur->right = recur(ind+1, en, ar);\n \n return cur;\n }\n};" }, { "title": "Encode and Decode TinyURL", "algo_input": "Note: This is a companion problem to the System Design problem: Design TinyURL.\n\nTinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.\n\nThere is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.\n\nImplement the Solution class:\n\n\n\tSolution() Initializes the object of the system.\n\tString encode(String longUrl) Returns a tiny URL for the given longUrl.\n\tString decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.\n\n\n \nExample 1:\n\nInput: url = \"https://leetcode.com/problems/design-tinyurl\"\nOutput: \"https://leetcode.com/problems/design-tinyurl\"\n\nExplanation:\nSolution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after deconding it.\n\n\n \nConstraints:\n\n\n\t1 <= url.length <= 104\n\turl is guranteed to be a valid URL.\n\n", "solution_py": "class Codec:\n\n def encode(self, longUrl):\n return longUrl\n\n def decode(self, shortUrl):\n return shortUrl", "solution_js": "let arr = new Array();\nlet size = 0;\n\nvar encode = function(longUrl) {\n arr.push(longUrl)\n let i = longUrl.indexOf('/',11);\n longUrl.slice(i);\n longUrl += this.size;\n arr.push(longUrl);\n size += 2;\n return longUrl;\n};\n\nvar decode = function(shortUrl) {\n let i = 0;\n while(arr[i] !== shortUrl && i hash;\n string server = \"http://tinyurl.com/\";\n string all = \"0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\";\n\npublic:\n\n // Encodes a URL to a shortened URL.\n string encode(string longUrl) {\n srand(time(NULL));\n string add = \"\";\n int ran = rand() % 10;\n int strsize = all.size();\n while(ran){\n int index = rand() % strsize;\n add += all[index];\n ran--;\n }\n\n hash[(server+add)] = longUrl;\n\n return (server + add);\n }\n\n // Decodes a shortened URL to its original URL.\n string decode(string shortUrl) {\n return hash[shortUrl];\n }\n};\n\n// Your Solution object will be instantiated and called as such:\n// Solution solution;\n// solution.decode(solution.encode(url));" }, { "title": "Symmetric Tree", "algo_input": "Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).\n\n \nExample 1:\n\nInput: root = [1,2,2,3,4,4,3]\nOutput: true\n\n\nExample 2:\n\nInput: root = [1,2,2,null,3,null,3]\nOutput: false\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t-100 <= Node.val <= 100\n\n\n \nFollow up: Could you solve it both recursively and iteratively?", "solution_py": "class Solution:\n def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n return root is None or self.findSymmetric(root.left, root.right)\n\n def findSymmetric(self, left, right):\n if (left is None or right is None):\n return left == right\n\n if (left.val != right.val):\n return False\n\n return self.findSymmetric(left.left, right.right) and self.findSymmetric(left.right, right.left)", "solution_js": "var isSymmetric = function(root) {\n return helper(root.left, root.right);\n\n function helper(left, right){\n if(!left && !right) return true;\n if((!left && right) || (left && !right) || (left.val !== right.val)) return false;\n return helper(left.left, right.right) && helper(left.right, right.left)\n }\n};", "solution_java": "class Solution {\n public boolean isSymmetric(TreeNode root) {\n return isSymmetric(root.left,root.right);\n }\n\n public boolean isSymmetric(TreeNode rootLeft, TreeNode rootRight) {\n if(rootLeft == null && rootRight == null) {return true;}\n if(rootLeft == null || rootRight == null) {return false;}\n if (rootLeft.val != rootRight.val) {return false;}\n else\n return isSymmetric(rootLeft.right, rootRight.left) && isSymmetric(rootLeft.left, rootRight.right);\n }\n}", "solution_c": "class Solution {\npublic:\n\n bool mirror(TreeNode* root1, TreeNode* root2){\n if(root1==NULL and root2==NULL) return true;\n if(root1==NULL or root2==NULL) return false;\n\n if(root1->val!=root2->val) return false;\n\n return mirror(root1->left, root2->right) and mirror(root1->right,root2->left);\n }\n\n bool isSymmetric(TreeNode* root) {\n if(root==NULL) return true;\n\n return mirror(root->left,root->right);\n }\n};" }, { "title": "Find the Middle Index in Array", "algo_input": "Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).\n\nA middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].\n\nIf middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.\n\nReturn the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.\n\n \nExample 1:\n\nInput: nums = [2,3,-1,8,4]\nOutput: 3\nExplanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4\n\n\nExample 2:\n\nInput: nums = [1,-1,4]\nOutput: 2\nExplanation: The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\n\n\nExample 3:\n\nInput: nums = [2,5]\nOutput: -1\nExplanation: There is no valid middleIndex.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t-1000 <= nums[i] <= 1000\n\n\n \nNote: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/\n", "solution_py": "class Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n A = [0] + list(accumulate(nums)) + [0]\n total, n = sum(nums), len(nums)\n for i in range(n):\n if A[i] == total - A[i] - nums[i]:\n return i\n return -1 ", "solution_js": "var findMiddleIndex = function(nums) {\n for (let i = 0; i < nums.length; i++) {\n let leftNums = nums.slice(0, i).reduce((a, b) => a + b, 0);\n let rightNums = nums.slice(i + 1).reduce((a, b) => a + b, 0);\n if (leftNums === rightNums) {\n return i;\n }\n }\n return -1;\n};", "solution_java": "class Solution {\n public int findMiddleIndex(int[] nums) {\n\n for(int i=0;i& nums) \n {\n int n=nums.size();\n int left_sum=0;\n int right_sum=0;\n for(int i=0;i int:\n e = defaultdict(list)\n m = len(beginWord)\n for word in wordList + [beginWord]:\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n e[w].append(word)\n q = deque([beginWord])\n used = set([beginWord])\n d = 0\n while q:\n d += 1\n for _ in range(len(q)):\n word = q.popleft()\n for i in range(m):\n w = word[:i] + \"*\" + word[i + 1:]\n if w in e:\n for v in e[w]:\n if v == endWord:\n return d + 1\n if v not in used:\n q.append(v)\n used.add(v)\n e.pop(w)\n return 0", "solution_js": "/**\n * @param {string} beginWord\n * @param {string} endWord\n * @param {string[]} wordList\n * @return {number}\n */\n\n// Logic is same as One direction, just from both side tword mid, much faster.\n// One Direction solution is here ->\n// https://leetcode.com/problems/word-ladder/discuss/2372376/Easy-Fast-Simple-83.95-235-ms-50.4-MB-One-Direction\n\nvar ladderLength = function(beginWord, endWord, wordList) {\n const charMap = buildCharMap()\n const wordSet = new Set(wordList)\n if (!wordSet.has(endWord)) return 0\n\n let leftSet = new Set([beginWord]), rightSet = new Set([endWord]), level = 1\n \n const helper = (set1, set2) => {\n const setArr = Array.from(set1)\n for (let i = 0; i < setArr.length; i++) {\n const word = setArr[i]\n for (let i = 0; i < word.length; i++) {\n for (const c of charMap) {\n const newWord = word.slice(0, i) + c + word.slice(i + 1)\n\n if (set2.has(newWord)) return true\n if (wordSet.has(newWord)) { \n set1.add(newWord)\n wordSet.delete(newWord)\n }\n }\n }\n set1.delete(word)\n }\n }\n \n while (leftSet.size && rightSet.size) {\n level++\n if (helper(leftSet, rightSet)) return level\n \n level++\n if (helper(rightSet, leftSet)) return level\n }\n \n return 0\n};\n\nconst buildCharMap = () => {\n const map = []\n \n for (let i = 0; i < 26; i++) {\n map.push(String.fromCharCode(i + 97))\n }\n \n return map\n}", "solution_java": "class Solution {\n public int ladderLength(String beginWord, String endWord, List wordList) {\n int count = 1;\n Set words = new HashSet<>(wordList);\n Queue q = new LinkedList();\n q.add(beginWord);\n \n while(!q.isEmpty()) {\n int size = q.size();\n \n while(size-- > 0) {\n String word = q.poll();\n char[] chList = word.toCharArray();\n \n for(int i=0; i& wordList)\n {\n // 1. Create a set and insert all wordList to the set to have\n // easy search of O(1)\n unordered_set wordSet;\n bool isEndWordPresent = false;\n for (string s:wordList)\n {\n // Check if the destination string even present in the wordList\n // If not then there is no point in even trying to find the\n // route from source string to destination string\n if (!isEndWordPresent && s.compare(endWord) == 0)\n {\n isEndWordPresent = true;\n }\n wordSet.insert(s);\n }\n\n // 2. If endWord is not present in the wordList return\n if (!isEndWordPresent)\n {\n return 0;\n }\n\n // 3. Create a queue for BST insert the elements of currentlevel to the queue\n // currentLevel is defined as all the strings that can be reached from\n // all the strings of the previous string by just replacing one character\n // and the one-char-replaced-string is present in the wordSet / wordList\n queue q;\n q.push(beginWord);\n int level = 0; // every time all the strings at this level are processed increment it\n\n // 4. Loop through all the elements in the queue\n while (!q.empty())\n {\n level++;\n int numStringsInCurLevel = q.size();\n // loop through all the strings in this current level\n // and find out if destination can be reached before\n // jumping to the next level of strings added to the queue\n while (numStringsInCurLevel--)\n {\n string curStr = q.front();\n q.pop();\n\n for (int i=0; i int:\n st = []\n ans = 0\n for i in nums:\n t = 0\n while st and st[-1][0] <= i:\n t = max(t, st.pop()[1])\n x = 0 \n if st: \n x = t+1 \n st.append([i, x])\n ans = max(ans, x)\n return ans", "solution_js": "var totalSteps = function(nums) {\n let stack = [],\n dp = new Array(nums.length).fill(0),\n max = 0\n\n for (let i = nums.length - 1; i >= 0; i--) {\n while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {\n dp[i] = Math.max(++dp[i], dp[stack.pop()])\n max = Math.max(dp[i], max)\n }\n stack.push(i)\n }\n return max\n};", "solution_java": "class Solution {\n \n \n \n public int totalSteps(int[] nums) {\n \n int n = nums.length;\n int ans = 0;\n \n Stack> st = new Stack();\n \n st.push(new Pair(nums[n-1],0));\n \n \n for(int i=n-2;i>=0;i--)\n {\n int count = 0;\n \n while(!st.isEmpty() && nums[i] > st.peek().getKey())\n {\n count = Math.max(count+1 , st.peek().getValue() );\n st.pop();\n }\n \n ans = Math.max(ans , count);\n st.push(new Pair(nums[i],count));\n }\n \n return ans;\n \n }\n}", "solution_c": "class Solution {\npublic:\n using pi = pair;\n int totalSteps(vector& nums) {\n int N = nums.size();\n map mp;\n vector del; // stores pairs of (previous id, toDelete id)\n for (int i = 0; i < N; ++i) {\n mp[i] = nums[i];\n if (i+1 < N && nums[i] > nums[i+1])\n del.emplace_back(i, i+1);\n }\n\n int ans = 0; // number of rounds\n while (!del.empty()) {\n ++ans;\n vector nxt; // pairs to delete in the next round\n for (auto [i,j] : del) mp.erase(j); // first, get rid of the required deletions\n for (auto [i,j] : del) {\n auto it = mp.find(i);\n if ( it == end(mp) || next(it) == end(mp) ) // if it's not in the map anymore,\n continue; // OR if it's the last element, skip it\n auto itn = next(it); // now compare against next element in the ordering\n if (it->second > itn->second) \n nxt.emplace_back(it->first, itn->first); // add the (current id, toDelete id)\n }\n swap(nxt, del); // nxt is the new del\n }\n return ans;\n\n }\n};" }, { "title": "Maximum Students Taking Exam", "algo_input": "Given a m * n matrix seats  that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.\n\nStudents can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..\n\nStudents must be placed in seats in good condition.\n\n \nExample 1:\n\nInput: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n  [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n  [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\nOutput: 4\nExplanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n\n\nExample 2:\n\nInput: seats = [[\".\",\"#\"],\n  [\"#\",\"#\"],\n  [\"#\",\".\"],\n  [\"#\",\"#\"],\n  [\".\",\"#\"]]\nOutput: 3\nExplanation: Place all students in available seats. \n\n\n\nExample 3:\n\nInput: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\".\",\".\",\"#\",\".\",\".\"],\n  [\".\",\"#\",\".\",\"#\",\".\"],\n  [\"#\",\".\",\".\",\".\",\"#\"]]\nOutput: 10\nExplanation: Place students in available seats in column 1, 3 and 5.\n\n\n \nConstraints:\n\n\n\tseats contains only characters '.' and'#'.\n\tm == seats.length\n\tn == seats[i].length\n\t1 <= m <= 8\n\t1 <= n <= 8\n\n", "solution_py": "class Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n m, n = len(seats), len(seats[0])\n match = [[-1]*n for _ in range(m)]\n def dfs(i, j, visited):\n for x, y in [(i-1,j-1),(i-1,j+1),(i,j-1),(i,j+1),(i+1,j-1),(i+1,j+1)]:\n if 0 <= x < m and 0 <= y < n and seats[x][y] == \".\" and (x, y) not in visited:\n visited.add((x, y))\n if match[x][y] == -1 or dfs(*match[x][y], visited):\n match[x][y] = (i, j)\n match[i][j] = (x, y)\n return True\n return False\n def max_matching():\n cnt = 0\n for i in range(m):\n for j in range(0,n,2):\n if seats[i][j] == '.' and match[i][j] == -1:\n visited = set()\n cnt += dfs(i, j, visited)\n return cnt\n\t\t#returns the number of elements of the maximum independent set in the bipartite set\n return sum(seats[i][j]=='.' for i in range(m) for j in range(n)) - max_matching()", "solution_js": "var maxStudents = function(seats) {\n if (!seats.length) return 0;\n \n\t// precalculate the seat that will be off the matrix\n const lastPos = 1 << seats[0].length;\n\t// encode the classroom into binary where 1 will be an available seat and 0 will be a broken seat\n const classroom = seats.map((row) => (\n row.reduce((a,c,i) => c === '#' ? a : (a | (1 << i)), 0))\n );\n\t\n\t// create a store to store the max seating for each row arrangment\n\t// each row will be off +1 of seats rows\n const dp = new Array(seats.length + 1).fill(null).map(() => new Map());\n\t// since no one can sit at row=-1 set the max number of no one sitting on that row as 0\n dp[0].set(0,0); \n\t\n\t// iterate through every row in seats matrix\n\t// remember that dp's rows are +1 of seats rows\n for (let row = 0; row < seats.length; row++) {\n\t\n\t // start with no one sitting on the row\n let queue = [0];\n\t\t// this will count the number of students sitting on this row\n\t\t// we will increment this up as we add students to the row\n let numStudents = 0;\n\t\t\n while (queue.length > 0) {\n \n\t\t\t// this will store all the different arrangments possible when we add 1 more student from the previous\n const next = [];\n\t\t\t\n\t\t\t// iterate through all the previous arrangements\n\t\t\t// calculate the maximum number of students that can sit on current and all previous rows\n\t\t\t// try adding a student to all possible available seats meeting the rules of the game\n for (let arrangement of queue) {\n\t\t\t\n \t\t\t // this calculates the maximum number of students that can sit with this row arrangment\n\t\t\t\t// if the arrangement doesn't allow any students to sit in the previous row this will be handled\n\t\t\t\t// by the 0 case in the previous row\n\t\t\t\t// *see helper function that checks to see if the arrangement conflicts with the previous arrangment\n let max = 0;\n for (let [prevArrang, count] of dp[row]) {\n if (conflicts(prevArrang, arrangement)) continue; \n max = Math.max(max, count + numStudents);\n }\n dp[row + 1].set(arrangement, max);\n \n\t\t\t\t// try adding an additional student to all elements in the row checking if it conflicts\n\t\t\t\t// arrangement | i => adds the student to the arrangement\n for (let i = 1; i < lastPos; i <<= 1) {\n if (canSit(classroom[row], arrangement, i)) next.push(arrangement | i);\n }\n } \n \n queue = next;\n numStudents++;\n }\n }\n \n\t// return the maximum value from the last row\n\t// the last row holds the maximum number of students for each arrangment\n return Math.max(...dp[seats.length].values());\n};\n\n// this checks if the there are any students to the left or right of current arrangment\n// curr << 1 => checks if there are any students to the left\n// curr >> 1 => check if there are any students to the right\nfunction conflicts(prev, curr) {\n return (prev & (curr << 1)) || (prev & (curr >> 1));\n}\n\n// this checks if we can place the new student in this spot\n// row & newStudent => checks if the classroom's row's seat is not broken\n// arrangment & newStudent => will return truthy if there is a student sitting in that position (so we ! it because we don't want anyone sitting there)\n// arrangement & (newStudent << 1) => will return truthy if there is a student sitting to the left of that position (so we ! it because we don't want anyone sitting there)\n// arrangement & (newStudent >> 1) => will return truthy if there is a student sitting to the right of that position (so we ! it because we don't want anyone sitting there)\nfunction canSit(row, arrangement, newStudent) {\n return row & newStudent && !(arrangement & newStudent) && !(arrangement & (newStudent << 1)) && !(arrangement & (newStudent >> 1));\n}", "solution_java": "class Solution {\n private Integer[][] f;\n private int n;\n private int[] ss;\n\n public int maxStudents(char[][] seats) {\n int m = seats.length;\n n = seats[0].length;\n ss = new int[m];\n f = new Integer[1 << n][m];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (seats[i][j] == '.') {\n ss[i] |= 1 << j;\n }\n }\n }\n return dfs(ss[0], 0);\n }\n\n private int dfs(int seat, int i) {\n if (f[seat][i] != null) {\n return f[seat][i];\n }\n int ans = 0;\n for (int mask = 0; mask < 1 << n; ++mask) {\n if ((seat | mask) != seat || (mask & (mask << 1)) != 0) {\n continue;\n }\n int cnt = Integer.bitCount(mask);\n if (i == ss.length - 1) {\n ans = Math.max(ans, cnt);\n } else {\n int nxt = ss[i + 1];\n nxt &= ~(mask << 1);\n nxt &= ~(mask >> 1);\n ans = Math.max(ans, cnt + dfs(nxt, i + 1));\n }\n }\n return f[seat][i] = ans;\n }\n}", "solution_c": "class Solution {\n public:\n int dp[8][(1 << 8) - 1];\n int maxStudents(vector>& seats) {\n memset(dp, -1, sizeof(dp));\n return helper(seats, 0, 0);\n }\n int helper(vector>& seats, int prevAllocation, int idx) {\n if (idx == seats.size()) return 0;\n int sz = seats[0].size(), masks = ((1 << sz) - 1), maxi = 0;\n // masks is for iterating over all subsets\n if (dp[idx][prevAllocation] != -1) return dp[idx][prevAllocation];\n while (masks >= 0) {\n int curAllocation = 0, cnt = 0;\n for (int i = 0; i < sz; i++) {\n if (seats[idx][i] != '#' && masks >> i & 1) {\n int ul = i - 1, ur = i + 1;\n bool canPlace = true;\n if (ul >= 0)\n if (prevAllocation >> ul & 1 || curAllocation >> ul & 1)\n canPlace = false;\n if (ur < sz)\n if (prevAllocation >> ur & 1 || curAllocation >> ur & 1)\n canPlace = false;\n if (canPlace) {\n curAllocation |= 1 << i;\n cnt++;\n }\n }\n }\n maxi = max(maxi, cnt + helper(seats, curAllocation, idx + 1));\n masks--;\n }\n dp[idx][prevAllocation] = maxi;\n return maxi;\n }\n};" }, { "title": "Nth Digit", "algo_input": "Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].\n\n \nExample 1:\n\nInput: n = 3\nOutput: 3\n\n\nExample 2:\n\nInput: n = 11\nOutput: 0\nExplanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def findNthDigit(self, n: int) -> int:\n low, high = 1, 0\n place = 1\n \n sum_ = 0\n \n while True:\n high = 10**place -1\n digits_sum = (high - low +1 ) * place\n \n if sum_<= n <= digits_sum + sum_:\n break\n else:\n low = high+1\n sum_+= digits_sum\n place += 1\n \n remaining_digits = n - sum_\n \n position = (remaining_digits-1)//place \n index_ = remaining_digits - position*place -1\n \n \n number = low + position\n # return str(number)[index_]\n count = 0\n index_ = place - 1 - index_\n l = []\n # \n while number:\n if count == index_:\n return number%10\n number = number//10\n count+=1", "solution_js": "var findNthDigit = function(n) {\n var len = 1;\n var range = 9;\n var base = 1;\n while(n>len*range)\n {\n n -= len *range;\n range *= 10;\n base *= 10;\n len++;\n }\n // [100, 101, 102,...]\n // 100 should have offset 0, use (n-1) to make the counting index from 0-based.\n var num = base + Math.floor((n-1)/len);\n var s = num.toString();\n return parseInt(s[(n-1)%len]);\n};", "solution_java": "class Solution {\n public int findNthDigit(int n) {\n\n if(n < 10)\n return n;\n\n long currDigitIndex = 10;\n int tillNextIncrease = 90;\n int currNumberSize = 2;\n int currNumber = 10;\n int next = tillNextIncrease;\n\n while(currDigitIndex < n) {\n\n currNumber++;\n currDigitIndex += currNumberSize;\n next--;\n\n if(next == 0) {\n currNumberSize++;\n tillNextIncrease *= 10;\n next = tillNextIncrease;\n }\n }\n\n int nthDigit = currNumber % 10;\n if(currDigitIndex == n) {\n while(currNumber != 0) {\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n } else if(currDigitIndex > n) {\n\n currNumber--;\n\n while(currDigitIndex > n) {\n currDigitIndex--;\n nthDigit = currNumber % 10;\n currNumber /= 10;\n }\n }\n\n return nthDigit;\n }\n}", "solution_c": "class Solution {\npublic:\n #define ll long long \n int findNthDigit(int n) {\n if(n<=9) return n;\n ll i=1;\n ll sum=0;\n while(true){\n ll a=(9*pow(10,i-1))*i;\n if(n-a<0){\n break;\n } \n else{\n sum+=9*pow(10,i-1);\n n-=a;\n }\n i++;\n }\n \n ll x=0; \n ll mod=n%i;\n n=(n/i);\n n+=sum;\n if(mod==0) return n%10;\n else{\n n++;\n ll x=i-mod;\n while(x--){\n n/=10;\n }\n }\n return n%10;\n }\n};" }, { "title": "Nearest Exit from Entrance in Maze", "algo_input": "You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.\n\nIn one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.\n\nReturn the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.\n\n \nExample 1:\n\nInput: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\n\n\nExample 2:\n\nInput: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\n\n\nExample 3:\n\nInput: maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n\n\n \nConstraints:\n\n\n\tmaze.length == m\n\tmaze[i].length == n\n\t1 <= m, n <= 100\n\tmaze[i][j] is either '.' or '+'.\n\tentrance.length == 2\n\t0 <= entrancerow < m\n\t0 <= entrancecol < n\n\tentrance will always be an empty cell.\n\n", "solution_py": "class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n x, y = entrance\n m, n, infi = len(maze), len(maze[0]), int(1e5)\n reached = lambda p, q: (not p==x or not q==y) and (p==0 or q==0 or p==m-1 or q==n-1)\n @lru_cache(None)\n def dfs(i, j):\n if i<0 or j<0 or i==m or j==n or maze[i][j]=='+':\n return infi\n if reached(i, j):\n return 0\n maze[i][j] = '+'\n ans = 1+min(dfs(i+1, j), dfs(i-1, j), dfs(i, j+1), dfs(i, j-1))\n maze[i][j] = '.'\n return ans\n ans = dfs(x, y)\n return -1 if ans>=infi else ans", "solution_js": "function nearestExit(maze, entrance) {\n const queue = []; // queue for bfs\n const empty = \".\";\n const [height, width] = [maze.length, maze[0].length];\n const tried = [...Array(height)].map(() => Array(width).fill(false));\n const tryStep = (steps, row, col) => {\n // don't reuse once it's already been tried\n if (tried[row][col]) return;\n tried[row][col] = true;\n if (maze[row][col] !== empty) return; // blocked? i.e. can't step\n queue.push([steps, row, col]);\n };\n const edges = { right: width - 1, bottom: height - 1, left: 0, top: 0 };\n const trySteppableDirs = (steps, row, col) => {\n // try steppable directions\n if (col < edges.right) tryStep(steps, row, col + 1);\n if (row < edges.bottom) tryStep(steps, row + 1, col);\n if (col > edges.left) tryStep(steps, row, col - 1);\n if (row > edges.top) tryStep(steps, row - 1, col);\n };\n let steps = 1, [row, col] = entrance;\n tried[row][col] = true; // don't reuse the entrance\n trySteppableDirs(steps, row, col);\n while (queue.length > 0) { // bfs\n [steps, row, col] = queue.shift();\n // path to the edge found?\n if (col === edges.left || col === edges.right) return steps;\n if (row === edges.top || row === edges.bottom) return steps;\n trySteppableDirs(steps + 1, row, col);\n }\n // NO path to the edge found\n return -1;\n}", "solution_java": "class Solution {\n public int nearestExit(char[][] maze, int[] entrance) {\n int rows = maze.length, cols = maze[0].length, queueSize;\n Queue queue = new LinkedList<>();\n boolean[][] visited = new boolean[rows][cols];\n int[] curr;\n int[][] dirs = {{0,1},{0,-1},{1,0},{-1,0}};\n int x, y, steps = 0;\n\n queue.offer(entrance);\n visited[entrance[0]][entrance[1]] = true;\n\n while (!queue.isEmpty()) {\n queueSize = queue.size();\n steps++;\n\n for (int i=0;i=rows||y<0||y>=cols) continue;\n if (visited[x][y] || maze[x][y] == '+') continue;\n\n // check if we have reached boundary\n if (x==0||x==rows-1||y==0||y==cols-1) return steps;\n\n queue.offer(new int[]{x, y});\n visited[x][y] = true;\n }\n }\n }\n\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n //checks if the coordinates of the cell are that of an unvisited valid empty cell\n bool isValid(int x,int y,int n,int m, vector>& maze,vector>& visited){\n if(x>=0 && x=0 && y< m && maze[x][y]!='+' && visited[x][y]!=1){\n return true;\n }\n return false;\n }\n\n //checks if the cell is a valid exit point\n bool isExit(int x,int y,int startX,int startY, vector>& maze,vector>& visited){\n if(x==startX && y==startY) return false;\n if( (x==0 || x==maze.size()-1 || y==0 || y==maze[0].size()-1)\n && maze[x][y]!='+')\n {\n return true;\n }\n return false;\n }\n\n //main BFS function\n int bfsHelper(vector>& maze,vector>& visited,int startX,int startY){\n queue>Queue;\n Queue.push({startX,startY,0});\n while(!Queue.empty()){\n int x = Queue.front()[0];\n int y = Queue.front()[1];\n int steps = Queue.front()[2];\n Queue.pop();\n //if you reach a valid exit, return the number of steps\n if(isExit(x,y,startX,startY,maze,visited)) return steps;\n int dx[4] = {0,-1,0,1};\n int dy[4] = {-1,0,1,0};\n //check in the 4 directions that you can travel\n for(int i=0;i<4;i++){\n int newX = x+dx[i] , newY = y+dy[i];\n //if the coordinates of the cell are that of\n //an unvisited valid empty cell, add it to the queue\n //and mark it as visited.\n if(isValid(newX,newY,maze.size(),maze[0].size(),maze,visited)){\n Queue.push({newX,newY,steps+1});\n visited[newX][newY] = 1;\n }\n }\n }\n //if you could not find a valid exit point, return -1\n return -1;\n }\n\n int nearestExit(vector>& maze, vector& entrance) {\n int n = maze.size();\n int m = maze[0].size();\n //create a 2d matrix and mark all the cells as -1,\n //denoting that they have not been visited yet.\n vector>visited(n,vector(m,-1));\n return bfsHelper(maze,visited,entrance[0],entrance[1]);\n }\n};" }, { "title": "Shuffle an Array", "algo_input": "Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.\n\nImplement the Solution class:\n\n\n\tSolution(int[] nums) Initializes the object with the integer array nums.\n\tint[] reset() Resets the array to its original configuration and returns it.\n\tint[] shuffle() Returns a random shuffling of the array.\n\n\n \nExample 1:\n\nInput\n[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n[[[1, 2, 3]], [], [], []]\nOutput\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle(); // Shuffle the array [1,2,3] and return its result.\n // Any permutation of [1,2,3] must be equally likely to be returned.\n // Example: return [3, 1, 2]\nsolution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 50\n\t-106 <= nums[i] <= 106\n\tAll the elements of nums are unique.\n\tAt most 104 calls in total will be made to reset and shuffle.\n\n", "solution_py": "import random \n\nclass Solution:\n\n def __init__(self, nums: List[int]):\n self.nums = nums\n\n def reset(self) -> List[int]: \n return self.nums\n\n def shuffle(self) -> List[int]:\n shuffled_array = self.nums.copy()\n # randomly generates the idx of the element that'll be the ith element of the array \n for i in range(len(self.nums) - 1, 0, -1):\n idx = random.randint(0, i)\n shuffled_array[i], shuffled_array[idx] = shuffled_array[idx], shuffled_array[i]\n return shuffled_array", "solution_js": "var Solution = function(nums) {\n this.nums = nums;\n this.resetArray = [...nums];\n};\n\nSolution.prototype.reset = function() {\n return this.resetArray;\n};\n\nSolution.prototype.shuffle = function() {\n\n const n = this.nums.length;\n const numsArray = this.nums;\n\n for (let i = 0; i < n; i++) {\n const j = Math.floor(Math.random() * (n - i)) + i;\n const tmp = numsArray[i];\n numsArray[i] = numsArray[j];\n numsArray[j] = tmp;\n }\n\n return numsArray;\n};", "solution_java": "class Solution {\n\n int a[];\n int b[];\n public Solution(int[] nums) {\n a=nums.clone();\n b=nums.clone();\n }\n\n public int[] reset() {\n a=b.clone();\n return a;\n }\n\n public int[] shuffle() {\n\n for(int i=0;i ans;\n vector res;\n Solution(vector& nums) {\n ans=nums;\n res=nums;\n }\n \n vector reset() {\n return res;\n }\n \n vector shuffle() {\n next_permutation(ans.begin(),ans.end());\n return ans;\n }\n};" }, { "title": "Maximal Rectangle", "algo_input": "Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.\n\n \nExample 1:\n\nInput: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput: 6\nExplanation: The maximal rectangle is shown in the above picture.\n\n\nExample 2:\n\nInput: matrix = [[\"0\"]]\nOutput: 0\n\n\nExample 3:\n\nInput: matrix = [[\"1\"]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\trows == matrix.length\n\tcols == matrix[i].length\n\t1 <= row, cols <= 200\n\tmatrix[i][j] is '0' or '1'.\n\n", "solution_py": "class Solution:\n def maxArea(self,arr: List[List[int]]) -> int:\n maxA = 0 #local max variable to return max area of a 1D array\n stack = [-1] #initializing with minimum value so we can avoid using loop for remaining element in the stack after whole traversing\n arr.append(-1) # value for stack index -1 and one extra iteration to empty the stack\n for i in range(len(arr)): # traversing for stack from left to right\n arr[i] = int(arr[i]) # we are getting str value from matrix\n while stack and arr[stack[-1]] >= int(arr[i]): #stack is non empty and stack top is greater or equal to current element\n index = stack.pop() #pop greater element from stack and finds its area\n width = i - stack[-1] - 1 if stack else i # for empty stack width is len of 1D arr, and after poping if we have element in stack then it becomes left boundary and current index as right boundary\n maxA = max(maxA, width * arr[index]) # geting max area (L * B)\n stack.append(int(i)) # inserting each element in stack\n return maxA # return the max area\n \"\"\"Below is the code for adding each row one by one and passing it to above function to get the max area for each row\"\"\"\n # r1 - 1 0 1 0 0\n # r2 - 1 0 1 1 1\n # r = 2 0 2 1 1 This is for else condition\n\n # r1 - 1 1 1 0 1\n # r2 - 1 0 1 1 0\n # r = 2 0 2 1 0 This is for if condition\n\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n result = [0] * len(matrix[0])\n maxReact = 0\n maxReact = self.maxArea(result)\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n matrix[i][j] = int(matrix[i][j])\n if matrix[i][j] == 0:\n result[j] = 0\n else:\n result[j] = result[j] + matrix[i][j]\n maxReact = max(maxReact,self.maxArea(result)) #after getting max area for 1D arr we are getting max value from those 1D arr for the 2D arr\n return maxReact", "solution_js": "var maximalRectangle = function(matrix) {\n const m = matrix.length;\n const n = matrix[m - 1].length;\n\n const prefixSum = new Array(m).fill().map(() => new Array(n).fill(0));\n for(let i = 0; i < m; i += 1) {\n for(let j = 0; j < n; j += 1) {\n prefixSum[i][j] = parseInt(matrix[i][j]);\n if(i > 0 && prefixSum[i][j] > 0) {\n prefixSum[i][j] += prefixSum[i - 1][j];\n }\n }\n }\n\n const getArea = (currentRow) => {\n let max = 0;\n for(let i = 0; i < n; i += 1) {\n const height = currentRow[i];\n\n let leftBoundary = i;\n while(leftBoundary >= 0 && currentRow[leftBoundary] >= currentRow[i]) {\n leftBoundary -= 1;\n }\n\n let rightBoundary = i;\n while(rightBoundary < n && currentRow[rightBoundary] >= currentRow[i]) {\n rightBoundary += 1;\n }\n\n const width = rightBoundary - leftBoundary - 1;\n max = Math.max(max, height * width);\n }\n\n return max;\n }\n\n let max = 0;\n for(let i = 0; i < m; i += 1) {\n max = Math.max(max, getArea(prefixSum[i]));\n }\n\n return max;\n};", "solution_java": "class Solution {\n public int maximalRectangle(char[][] matrix) {\n ArrayList list = new ArrayList<>();\n int n = matrix[0].length;\n for(int i=0; i heights) {\n Stack stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.size();\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n\n for(int i=0; i= heights.get(i))\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n\n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights.get(stack2.peek()) >= heights.get(i))\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n\n for(int i=0; i nextSmallerElement(int *arr , int n){\n stack st;\n st.push(-1);\n vector ans(n);\n \n for(int i = n - 1 ; i >= 0 ; i--){\n int curr = arr[i];\n \n while(st.top() != -1 && arr[st.top()] >= curr){\n st.pop();\n }\n \n ans[i] = st.top();\n st.push(i);\n }\n return ans;\n }\n \n vector prevSmallerElement(int *arr , int n){\n stack st;\n st.push(-1);\n vector ans(n);\n \n for(int i = 0; i < n ; i++){\n int curr = arr[i];\n \n while(st.top() != -1 && arr[st.top()] >= curr){\n st.pop();\n }\n \n ans[i] = st.top();\n st.push(i);\n }\n return ans;\n }\n \n int largestRectangleArea(int * heights , int n){\n int area = INT_MIN;\n \n vector next(n);\n next = nextSmallerElement(heights , n);\n \n vector prev(n);\n prev = prevSmallerElement(heights , n);\n \n for(int i = 0 ; i < n ; i++){\n int length = heights[i];\n \n if(next[i] == -1)\n next[i] = n;\n \n int breadth = next[i] - prev[i] - 1;\n int newArea = length * breadth;\n area = max(area , newArea);\n }\n return area;\n }\n \npublic:\n int maximalRectangle(vector>& matrix) {\n \n int n = matrix.size();\n int m = matrix[0].size();\n int M[n][m];\n \n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n M[i][j] = matrix[i][j] - '0';\n }\n }\n \n //step 1 : compute area of 1st row\n int area = largestRectangleArea(M[0] , m);\n \n for(int i = 1 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n \n //step 2 : add upar wala element if it is 1\n if(M[i][j] != 0)\n M[i][j] = M[i][j] + M[i-1][j];\n \n else\n M[i][j] = 0;\n }\n \n area = max(area , largestRectangleArea(M[i] , m));\n }\n return area;\n }\n};" }, { "title": "Walking Robot Simulation II", "algo_input": "A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions (\"North\", \"East\", \"South\", and \"West\"). A robot is initially at cell (0, 0) facing direction \"East\".\n\nThe robot can be instructed to move for a specific number of steps. For each step, it does the following.\n\n\n\tAttempts to move forward one cell in the direction it is facing.\n\tIf the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.\n\n\nAfter the robot finishes moving the number of steps required, it stops and awaits the next instruction.\n\nImplement the Robot class:\n\n\n\tRobot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\".\n\tvoid step(int num) Instructs the robot to move forward num steps.\n\tint[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].\n\tString getDir() Returns the current direction of the robot, \"North\", \"East\", \"South\", or \"West\".\n\n\n \nExample 1:\n\nInput\n[\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]\nOutput\n[null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]\n\nExplanation\nRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return \"East\"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and faces North (not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return \"West\"\n\n\n\n \nConstraints:\n\n\n\t2 <= width, height <= 100\n\t1 <= num <= 105\n\tAt most 104 calls in total will be made to step, getPos, and getDir.\n\n", "solution_py": "class Robot:\n\n def __init__(self, width: int, height: int):\n self.perimeter = 2*width + 2*(height - 2)\n self.pos = 0\n self.atStart = True\n\n self.bottomRight = width - 1\n self.topRight = self.bottomRight + (height - 1)\n self.topLeft = self.topRight + (width - 1)\n\n def step(self, num: int) -> None:\n self.atStart = False\n self.pos = (self.pos + num) % self.perimeter\n\n def getPos(self) -> List[int]:\n if 0 <= self.pos <= self.bottomRight:\n return [self.pos, 0]\n\n if self.bottomRight < self.pos <= self.topRight:\n return [self.bottomRight, self.pos - self.bottomRight]\n\n if self.topRight < self.pos <= self.topLeft:\n return [self.bottomRight - (self.pos - self.topRight), self.topRight - self.bottomRight]\n \n return [0, self.topRight - self.bottomRight - (self.pos - self.topLeft)]\n\n def getDir(self) -> str:\n if self.atStart or 0 < self.pos <= self.bottomRight:\n return 'East'\n\n if self.bottomRight < self.pos <= self.topRight:\n return 'North'\n\n if self.topRight < self.pos <= self.topLeft:\n return 'West'\n \n return 'Sout", "solution_js": "const EAST = \"East\";\nconst NORTH = \"North\";\nconst WEST = \"West\";\nconst SOUTH = \"South\";\n\nconst DIRECTIONS = [EAST, NORTH, WEST, SOUTH];\nconst ORIGIN = [0,0];\n\n/**\n * @param {number} width\n * @param {number} height\n */\nvar Robot = function(width, height) {\n this.width = width;\n this.height = height;\n\n this.path = []; // circular buffer of entire path of robot\n this.dirAtSquare = []; // dir robot is facing at each square\n this.currentPos = -1;\n\n this.preprocess();\n};\n\n/**\n * Loop around the map once and store the path into a circular buffer.\n *\n * (0,0) is set to face SOUTH. The only time it is EAST is at the beginning\n * if the robot didn't move at all.\n *\n * @return {void}\n */\nRobot.prototype.preprocess = function() {\n // go right\n for (let i = 1; i < this.width; i++) {\n this.path.push([i, 0]);\n this.dirAtSquare.push(0);\n }\n\n // go up\n const xMax = this.width - 1;\n for (let i = 1; i < this.height; i++) {\n this.path.push([xMax, i]);\n this.dirAtSquare.push(1);\n }\n\n // go left\n const yMax = this.height - 1;\n for (let i = xMax - 1; i >= 0; i--) {\n this.path.push([i, yMax]);\n this.dirAtSquare.push(2);\n }\n\n // go down\n const xMin = 0;\n for (let i = yMax - 1; i >= 0; i--) {\n this.path.push([xMin, i]);\n this.dirAtSquare.push(3);\n }\n}\n\n/**\n * @param {number} num\n * @return {void}\n */\nRobot.prototype.step = function(num) {\n this.currentPos += num;\n};\n\n/**\n * @return {number[]}\n */\nRobot.prototype.getPos = function() {\n return this.currentPos === -1\n ? ORIGIN // we haven't moved\n : this.path[this.currentPos % this.path.length];\n};\n\n/**\n * @return {string}\n */\nRobot.prototype.getDir = function() {\n return this.currentPos === -1\n ? DIRECTIONS[0] // we haven't moved\n : DIRECTIONS[this.dirAtSquare[this.currentPos % this.dirAtSquare.length]];\n};\n\n/**\n * Your Robot object will be instantiated and called as such:\n * var obj = new Robot(width, height)\n * obj.step(num)\n * var param_2 = obj.getPos()\n * var param_3 = obj.getDir()\n */", "solution_java": "class Robot {\n\n int p;\n int w;\n int h;\n public Robot(int width, int height) {\n w = width - 1;\n h = height - 1;\n p = 0;\n }\n\n public void step(int num) {\n p += num;\n }\n\n public int[] getPos() {\n int remain = p % (2 * (w + h));\n if (remain <= w)\n return new int[]{remain, 0};\n remain -= w;\n if (remain <= h)\n return new int[]{w, remain};\n remain -= h;\n if (remain <= w)\n return new int[]{w - remain, h};\n remain -= w;\n return new int[]{0, h - remain};\n }\n\n public String getDir() {\n int[] pos = getPos();\n if (p == 0 || pos[1] == 0 && pos[0] > 0)\n return \"East\";\n else if (pos[0] == w && pos[1] > 0)\n return \"North\";\n else if (pos[1] == h && pos[0] < w)\n return \"West\";\n else\n return \"South\";\n }\n}", "solution_c": "class Robot {\nprivate:\n int width, height, perimeter;\n int dir = 0;\n int x = 0, y = 0;\n map mp = {{0, \"East\"}, {1, \"North\"}, {2, \"West\"}, {3, \"South\"}};\n\npublic:\n Robot(int width, int height) {\n this->width = width;\n this->height = height;\n this->perimeter = 2 * (height + width) - 4;\n }\n \n void step(int num) {\n\t\tif(!num) return;\n num = num % perimeter;\n if(x == 0 && y == 0 && num == 0) dir = 3;\n while(num--){\n if(x == 0 && y == 0) dir = 0;\n else if(x == width-1 && y == 0) dir = 1;\n else if(x == width-1 && y == height-1) dir = 2;\n else if(x == 0 && y == height-1) dir = 3;\n \n if(dir == 0) x += 1; \n if(dir == 1) y += 1;\n if(dir == 2) x -= 1;\n if(dir == 3) y -= 1;\n }\n \n }\n \n vector getPos() {\n return {x, y};\n }\n \n string getDir() {\n return mp[dir];\n }\n};" }, { "title": "Apply Discount Every n Orders", "algo_input": "There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].\n\nWhen a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product).\n\nThe supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100).\n\nImplement the Cashier class:\n\n\n\tCashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices.\n\tdouble getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.\n\n\n \nExample 1:\n\nInput\n[\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]\nOutput\n[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]\nExplanation\nCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6th customer, no discount.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\t0 <= discount <= 100\n\t1 <= products.length <= 200\n\tprices.length == products.length\n\t1 <= products[i] <= 200\n\t1 <= prices[i] <= 1000\n\tThe elements in products are unique.\n\t1 <= product.length <= products.length\n\tamount.length == product.length\n\tproduct[j] exists in products.\n\t1 <= amount[j] <= 1000\n\tThe elements of product are unique.\n\tAt most 1000 calls will be made to getBill.\n\tAnswers within 10-5 of the actual value will be accepted.\n\n", "solution_py": "class Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n \n self.n = n \n self.discount = discount \n self.price = { }\n self.customer = 0 \n \n for i in range(len(products)) : \n self.price[products[i]] = prices[i]\n\n def getBill(self, product: List[int], amount: List[int]) -> float:\n \n self.customer += 1\n \n bill = 0 \n \n for i in range(len(product)) : \n bill += amount[i] * self.price[product[i]]\n \n \n if self.customer == self.n : \n bill = bill * (1 - self.discount / 100)\n self.customer = 0 \n \n \n return bill\n \n \n\n\n# Your Cashier object will be instantiated and called as such:\n# obj = Cashier(n, discount, products, prices)\n# param_1 = obj.getBill(product,amount)", "solution_js": "var Cashier = function(n, discount, products, prices) {\n this.n = n;\n this.cc = 0;\n this.discount = (100 - discount) / 100;\n this.products = new Map();\n const len = products.length;\n for(let i = 0; i < len; i++) {\n this.products.set(products[i], prices[i]);\n }\n};\n\nCashier.prototype.getBill = function(product, amount) {\n let total = 0, len = product.length;\n for(let i = 0; i < len; i++) {\n total += amount[i] * this.products.get(product[i]);\n }\n this.cc++;\n if(this.cc % this.n == 0) {\n total = total * this.discount;\n this.cc = 0;\n }\n return total;\n};", "solution_java": "class Cashier {\n private Map catalogue;\n \n private int n;\n private double discount;\n private int orderNumber;\n \n public Cashier(int n, int discount, int[] products, int[] prices) {\n this.catalogue = new HashMap<>();\n \n for (int i = 0; i < prices.length; i++) {\n this.catalogue.put(products[i], prices[i]);\n }\n \n this.n = n;\n this.discount = ((double) 100 - discount)/100;\n this.orderNumber = 0;\n }\n \n public double getBill(int[] product, int[] amount) {\n this.orderNumber++;\n \n double bill = 0.0;\n for (int i = 0; i < amount.length; i++) {\n int p = product[i];\n int price = this.catalogue.get(p);\n bill += price*amount[i];\n }\n \n if (this.orderNumber % n == 0)\n bill *= this.discount;\n \n return bill;\n }\n}\n\n/**\n * Your Cashier object will be instantiated and called as such:\n * Cashier obj = new Cashier(n, discount, products, prices);\n * double param_1 = obj.getBill(product,amount);\n */", "solution_c": "class Cashier {\npublic:\n int nn = 0;\n double dis = 0;\n vector pro;\n vector pri;\n int currCustomer = 0; //Declaring these variables here to use it in other fxns as well\n \n Cashier(int n, int discount, vector& products, vector& prices) {\n nn = n;\n dis = discount;\n pro = products;\n pri = prices; //Assigning given values to our created variables\n }\n \n double getBill(vector product, vector amount) {\n currCustomer++; //Increasing customer count\n double bill = 0; //Bill anount set to 0\n for(int i = 0; i < product.size(); i++){ //Iterating over every product\n int proId = 0; \n \n while(pro[proId] != product[i]) proId++; //Finding product ID index\n \n bill = bill + (amount[i]*pri[proId]); //Adding total amount to bill\n }\n \n if(currCustomer == nn){ //Checking if the customer is eligible for discount\n bill = bill * (1 - dis/100); //Giving discount\n currCustomer = 0; //Setting customer count to 0 so next third person can have discount\n }\n return bill; //Returning final bill amount\n }\n};" }, { "title": "Combination Sum", "algo_input": "Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.\n\nThe same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.\n\nIt is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.\n\n \nExample 1:\n\nInput: candidates = [2,3,6,7], target = 7\nOutput: [[2,2,3],[7]]\nExplanation:\n2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.\n\n\nExample 2:\n\nInput: candidates = [2,3,5], target = 8\nOutput: [[2,2,2,2],[2,3,3],[3,5]]\n\n\nExample 3:\n\nInput: candidates = [2], target = 1\nOutput: []\n\n\n \nConstraints:\n\n\n\t1 <= candidates.length <= 30\n\t1 <= candidates[i] <= 200\n\tAll elements of candidates are distinct.\n\t1 <= target <= 500\n\n", "solution_py": "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n\n path = []\n answer = []\n def dp(idx, total):\n if total == target:\n answer.append(path[:])\n return\n if total > target:\n return\n\n for i in range(idx, len(candidates)):\n path.append(candidates[i])\n dp(i, total + candidates[i])\n path.pop()\n\n dp(0, 0)\n return answer", "solution_js": "function recursion(index, list, target, res, arr){\n if(index == arr.length){\n if(target == 0){\n res.push([...list]);\n }\n return;\n }\n\n if(arr[index] <= target){\n\n list.push(arr[index]);\n\n recursion(index, list, target - arr[index], res, arr);\n\n list.pop();\n\n }\n\n recursion(index + 1, list, target, res, arr);\n\n}\nvar combinationSum = function(candidates, target) {\n let res = [];\n recursion(0, [], target, res, candidates);\n return res;\n};", "solution_java": "class Solution {\n public List> combinationSum(int[] candidates, int target) {\n List cur = new ArrayList<>();\n List> result = new ArrayList<>();\n Arrays.sort(candidates);\n dfs(0, candidates, target, 0, cur, result);\n return result;\n }\n public void dfs(int start, int[] candidates, int target, int sum, List cur, List> result){\n if(sum == target){\n result.add(new ArrayList<>(cur));\n return;\n }\n for(int i = start; i < candidates.length; i++) {\n if(sum + candidates[i] <= target) {\n cur.add(candidates[i]);\n dfs(i, candidates, target, sum + candidates[i], cur, result);\n cur.remove((cur.size()- 1));\n }\n }\n return;\n }\n}", "solution_c": "class Solution {\n void combination(vector& candidates, int target, vector currComb, int currSum, int currIndex, vector>& ans){\n if(currSum>target) return; //backtrack\n if(currSum==target){\n ans.push_back(currComb); //store the solution and backtrack\n return;\n }\n\n for(int i=currIndex; i> combinationSum(vector& candidates, int target) {\n vector> ans;\n vector currComb;\n combination(candidates, target, currComb, 0, 0, ans);\n return ans;\n }\n};" }, { "title": "Maximum Matrix Sum", "algo_input": "You are given an n x n integer matrix. You can do the following operation any number of times:\n\n\n\tChoose any two adjacent elements of matrix and multiply each of them by -1.\n\n\nTwo elements are considered adjacent if and only if they share a border.\n\nYour goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.\n\n \nExample 1:\n\nInput: matrix = [[1,-1],[-1,1]]\nOutput: 4\nExplanation: We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.\n\n\nExample 2:\n\nInput: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput: 16\nExplanation: We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.\n\n\n \nConstraints:\n\n\n\tn == matrix.length == matrix[i].length\n\t2 <= n <= 250\n\t-105 <= matrix[i][j] <= 105\n\n", "solution_py": "class Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n # count -'s\n count = 0\n for row in matrix:\n for col_num in row:\n if col_num < 0:\n count += 1\n tot_sum = sum([sum([abs(x) for x in row])\n for row in matrix])\n if count % 2 == 0:\n return tot_sum\n else:\n min_val = min([min([abs(x) for x in row])\n for row in matrix])\n return tot_sum - 2 * min_val", "solution_js": "var maxMatrixSum = function(matrix) {\n const MAX= Number.MAX_SAFE_INTEGER;\n\n const m = matrix.length;\n const n = matrix[0].length;\n\n let negs = 0;\n\n let totAbsSum = 0;\n let minAbsNum = MAX;\n\n for (let i = 0; i < n; ++i) {\n for (let j = 0; j < n; ++j) {\n if (matrix[i][j] < 0) ++negs;\n\n totAbsSum += Math.abs(matrix[i][j]);\n minAbsNum = Math.min(minAbsNum, Math.abs(matrix[i][j]));\n }\n }\n\n if (negs % 2 === 1) totAbsSum -= (2 * minAbsNum);\n\n return totAbsSum;\n};", "solution_java": "class Solution {\n public long maxMatrixSum(int[][] matrix) {\n long ans = 0;\n int neg = 0;\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < matrix.length; i++){\n for(int j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] < 0) {\n neg++;\n }\n ans += Math.abs(matrix[i][j]);\n if(min > Math.abs(matrix[i][j]))\n \tmin = Math.abs(matrix[i][j]);\n }\n }\n if(neg % 2 == 0)\n \treturn ans;\n else\n \treturn ans - 2*min;\n }\n}", "solution_c": "/**\n * @author : archit\n * @GitHub : archit-1997\n * @Email : architsingh456@gmail.com\n * @file : maximumMatrixSum.cpp\n * @created : Saturday Aug 21, 2021 20:11:56 IST\n */\n\n#include \nusing namespace std;\n\nclass Solution {\npublic:\n long long maxMatrixSum(vector>& matrix) {\n int r=matrix.size(),c=matrix[0].size();\n\n //we need to find the min number in the matrix and also count of negative numbers in the matrix\n int small=INT_MAX,count=0;\n long long int sum=0;\n\n for(int i=0;i int:\n m,n=len(grid),len(grid[0])\n queue=deque([])\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1:\n queue.append((i,j))\n c=-1\n while queue:\n # print(queue)\n temp=len(queue)\n for _ in range(temp):\n (i,j)=queue.popleft()\n for (x,y) in ((i-1,j),(i+1,j),(i,j-1),(i,j+1)):\n if x < 0 or x >= m or y < 0 or y >= n or grid[x][y]==1:\n continue\n grid[x][y]=1\n queue.append((x,y))\n c+=1\n return c if c!=0 else -1", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nconst DIR = [\n [0,1],\n [0,-1],\n [1,0],\n [-1,0]\n];\nvar maxDistance = function(grid) {\n const ROWS = grid.length;\n const COLS = grid[0].length;\n const cost = new Array(ROWS).fill().map(()=>new Array(COLS).fill(Infinity));\n const que = [];\n for(let row=0; row= ROWS || newCol >= COLS) continue;\n if(cost[newRow][newCol] > cost[row][col] + 1) {\n cost[newRow][newCol] = cost[row][col] + 1;\n que.push([newRow, newCol]);\n }\n }\n }\n let max = 0;\n for(const row of cost) {\n max = Math.max(max, ...row);\n }\n return max;\n};", "solution_java": "class Solution {\n class Point {\n int x, y;\n public Point(int x, int y){\n this.x=x;\n this.y=y;\n }\n }\n int[][] dist;\n int n,ans;\n int[] dx={0, 0, +1, -1};\n int[] dy={+1, -1, 0, 0};\n public int maxDistance(int[][] grid) {\n n=grid.length;\n dist = new int[n][n];\n Queue q = new LinkedList<>();\n for (int i=0;idist[x][y]+1){\n dist[r][c]=dist[x][y]+1;\n Point newP = new Point(r,c);\n q.add(newP);\n }\n }\n }\n for (int i=0;i=0&&c>=0&&r dr = {0,0,1,-1};\n vector dc = {1,-1,0,0};\npublic:\n bool isPos(int r,int c,int n){\n return ( r>=0 && c>=0 && r>& grid) {\n int n = grid.size();\n vector< vector > dist(n,vector(n,-1));\n queue< vector > pq;\n for(int i=0 ; i vect = pq.front();\n pq.pop();\n int r = vect[0];\n int c = vect[1];\n if( 0==grid[r][c] ){\n ans = max(ans,dist[r][c]);\n }\n for(int i=0 ; i<4 ; i++){\n int nr = r+dr[i];\n int nc = c+dc[i];\n if( isPos(nr,nc,n) && -1==dist[nr][nc] ){\n dist[nr][nc] = dist[r][c]+1;\n pq.push({nr,nc});\n }\n }\n }\n return (ans==0 ? -1 : ans);\n }\n};" }, { "title": "Grid Illumination", "algo_input": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.\n\nYou are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.\n\nWhen a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\n\nYou are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].\n\nReturn an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.\n\n \nExample 1:\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput: [1,0]\nExplanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n\n\n\nExample 2:\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput: [1,1]\n\n\nExample 3:\n\nInput: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput: [1,1,0]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\t0 <= lamps.length <= 20000\n\t0 <= queries.length <= 20000\n\tlamps[i].length == 2\n\t0 <= rowi, coli < n\n\tqueries[j].length == 2\n\t0 <= rowj, colj < n\n\n", "solution_py": "class Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n rows = collections.Counter()\n cols = collections.Counter()\n diags1 = collections.Counter()\n diags2 = collections.Counter()\n lamps = {tuple(lamp) for lamp in lamps}\n \n for i, j in lamps:\n rows[i] += 1\n cols[j] += 1\n diags1[i + j] += 1\n diags2[i - j] += 1\n \n ans = []\n directions = ((-1, -1), (-1, 0), (-1, 1),\n (0, -1), (0, 0), (0, 1),\n (1, -1), (1, 0), (1, 1))\n \n for i, j in queries:\n if rows[i] or cols[j] or diags1[i + j] or diags2[i - j]:\n ans.append(1)\n else:\n ans.append(0)\n \n for di, dj in directions:\n newI, newJ = i + di, j + dj\n if (newI, newJ) not in lamps:\n continue\n lamps.remove((newI, newJ))\n rows[newI] -= 1\n cols[newJ] -= 1\n diags1[newI + newJ] -= 1\n diags2[newI - newJ] -= 1\n \n return ans", "solution_js": "var gridIllumination = function(n, lamps, queries) {\n const directions = [[0,0], [-1,-1], [-1,0], [-1,1], [0,-1], [0,1], [1,-1], [1,0], [1,1]];\n const lampCoord = new Map(); \n const rowHash = {}, colHash = {}, leftDiag = {}, rightDiag = {};\n \n // First, illuminate the lamps\n for (let [r, c] of lamps) {\n if (lampCoord.has(`${r}-${c}`)) continue;\n lampCoord.set(`${r}-${c}`);\n rowHash[r] = rowHash[r] + 1 || 1;\n colHash[c] = colHash[c] + 1 || 1;\n leftDiag[r + c] = leftDiag[r + c] + 1 || 1;\n rightDiag[c - r] = rightDiag[c - r] + 1 || 1;\n }\n \n // Second, query the lamps\n let output = [];\n for (let [row, col] of queries) query(row, col);\n return output;\n\n function query(row, col) {\n if (rowHash[row] || colHash[col] || leftDiag[row + col] || rightDiag[col - row]) {\n output.push(1);\n\t\t\t// Check 8 adjacent cells\n for (let [r, c] of directions) {\n let newR = row + r, newC = col + c;\n if (newR < 0 || newC < 0 || newR >= n || newC >= n) continue;\n // If the coordinate is a lamp, un-illuminate the lamp\n if (lampCoord.has(`${newR}-${newC}`)) {\n rowHash[newR]--, colHash[newC]--, leftDiag[newR + newC]--, rightDiag[newC - newR]--;\n lampCoord.delete(`${newR}-${newC}`);\n }\n } \n } else output.push(0);\n } \n};", "solution_java": "class Solution {\n public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {\n //we take 5 hashmap\n //1st hashmap for row\n HashMap row = new HashMap<>();\n //2nd hashmap for column\n HashMap col = new HashMap<>();\n //3rd hashmap for lower diagonal\n HashMap d1 = new HashMap<>();\n //4th diagonal for upper diagonal\n HashMap d2 = new HashMap<>();\n //5th diagonal for cell no meaning lamp is present at this spot\n HashMap cellno = new HashMap<>();\n \n for(int i = 0;i gridIllumination(int n, vector>& lamps, vector>& queries) {\n\n vectorans;\n unordered_maprow,col,mainDiag,antiDiag;\n set>s;\n\n for(auto &l : lamps){\n int x = l[0],y=l[1];\n // Even if the same lamp is listed more than once, it is turned on.\n // To prevent duplicate entries\n if(s.find({x,y}) == s.end())\n {\n row[x]++;\n col[y]++;\n antiDiag[x+y]++;\n mainDiag[x-y]++;\n s.insert({x,y}); // This helps us to get the lamp in O(1)\n }\n }\n\n for(auto &q : queries)\n {\n // For every query {x,y} do 2 things :\n // 1. Check whether grid[x][y] is illuminated or not, accordingly set answer either to '1' OR '0'\n // 2. if grid is illuminated, turn off the lamps at {x,y} and 8 adjacent lamps = 9 lamps\n\n int x = q[0],y = q[1];\n if(row[x]>0 or col[y]>0 or antiDiag[x+y]>0 or mainDiag[x-y]>0)\n {\n // illumination\n ans.push_back(1);\n\n // Turn off the 9 lamps = 1 center and 8 adjacent lamps\n for(int i=-1;i<=1;i++){\n for(int j=-1;j<=1;j++){\n\n int nx = x+i;\n int ny = y+j;\n // NxN board, check boundaries condition\n if(nx >= 0 and nx < n and ny >=0 and ny < n and s.find({nx,ny})!=s.end())\n {\n row[nx]--;\n col[ny]--;\n antiDiag[nx+ny]--;\n mainDiag[nx-ny]--;\n s.erase({nx,ny});\n }\n }\n }\n }\n else // No illumination\n ans.push_back(0);\n }\n return ans;\n }\n};" }, { "title": "Maximum Gap", "algo_input": "Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.\n\nYou must write an algorithm that runs in linear time and uses linear extra space.\n\n \nExample 1:\n\nInput: nums = [3,6,9,1]\nOutput: 3\nExplanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n\n\nExample 2:\n\nInput: nums = [10]\nOutput: 0\nExplanation: The array contains less than 2 elements, therefore return 0.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def maximumGap(self, nums: List[int]) -> int:\n if len(nums)<2: return 0\n \n #radix sort\n #N = length of nums\n #find number of digits in largest number - O(K) where K = length of largest number\n longest = 0\n for i in nums:\n longest = max(longest,len(str(i)))\n \n #normalize so that all numbers have same number of digits by adding 0s at the start of shorter numbers - O(N*K)\n for i in range(len(nums)):\n if len(str(nums[i]))!=longest:\n nums[i] = '0'*(longest-len(str(nums[i]))) + str(nums[i])\n else:\n nums[i] = str(nums[i])\n \n #apply counting sort starting with each digit from the end of the last digits - O(K*N)\n for digit in range(longest-1,-1,-1):\n vals = [[] for k in range(10)]\n for num in nums:\n vals[int(num[digit])] += [num]\n\t\t\t#join list sorted by that digit position together:\n new = []\n for i in vals:\n new += i\n nums = new.copy()\n \n #find the largest difference in the now sorted nums - O(N)\n best_diff = 0\n for i in range(1,len(nums)):\n best_diff = max(best_diff,int(nums[i])-int(nums[i-1]))\n return best_diff\n \n#Overall complexity is O(N*K) but K is at most 10 so O(10*N) = O(N) so linear\n#Please correct me if I am wrong!", "solution_js": "/**\n * The buckets solution.\n *\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n *\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumGap = function(nums) {\n const n = nums.length\n\n if (n < 2) {\n return 0\n }\n\n if (n < 3) {\n return Math.abs(nums[0] - nums[1])\n }\n\n let maxNum = -Infinity\n let minNum = +Infinity\n\n for (let i = 0; i < n; i++) {\n maxNum = Math.max(maxNum, nums[i])\n minNum = Math.min(minNum, nums[i])\n }\n\n if (maxNum === minNum) {\n return 0\n }\n\n const k = n - 1\n const averageGap = (maxNum - minNum) / k\n\n const minBuckets = new Array(k)\n const maxBuckets = new Array(k)\n\n minBuckets[0] = minNum\n maxBuckets[0] = minNum\n\n minBuckets[k - 1] = maxNum\n maxBuckets[k - 1] = maxNum\n\n for (let i = 0; i < n; i++) {\n if (minNum === nums[i] || nums[i] === maxNum) {\n continue\n }\n\n const j = Math.floor((nums[i] - minNum) / averageGap)\n\n minBuckets[j] = minBuckets[j] ? Math.min(minBuckets[j], nums[i]) : nums[i]\n maxBuckets[j] = maxBuckets[j] ? Math.max(maxBuckets[j], nums[i]) : nums[i]\n }\n\n let largestGap = 0\n let prevMaxIndex = 0\n\n for (let i = 1; i < n - 1; i++) {\n if (minBuckets[i]) {\n largestGap = Math.max(largestGap, minBuckets[i] - maxBuckets[prevMaxIndex])\n }\n\n if (maxBuckets[i]) {\n prevMaxIndex = i\n }\n }\n\n return largestGap\n}", "solution_java": "class Solution {\n public int maximumGap(int[] nums) {\n Arrays.sort(nums);\n int res=0;\n if(nums.length==0){\n return 0;\n }\n for (int i =0;i& nums) {\n sort(nums.begin(),nums.end());\n int res;\n int maxx=INT_MIN;\n map m;\n if(nums.size()==1)\n return 0;\n for(int i =0;imaxx)\n {\n maxx=it.second;\n }\n }\n return maxx;\n }\n};" }, { "title": "Minimum Rounds to Complete All Tasks", "algo_input": "You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.\n\nReturn the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.\n\n \nExample 1:\n\nInput: tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput: 4\nExplanation: To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.\n\n\nExample 2:\n\nInput: tasks = [2,3,3]\nOutput: -1\nExplanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.\n\n\n \nConstraints:\n\n\n\t1 <= tasks.length <= 105\n\t1 <= tasks[i] <= 109\n\n", "solution_py": "class Solution:\n def minimumRounds(self, tasks: List[int]) -> int:\n dic={}\n c=0\n for i in tasks:\n if i in dic.keys():\n dic[i]+=1\n else:\n dic[i]=1\n for i in dic.keys():\n if dic[i]==1:\n return -1\n while dic[i]>=2:\n if dic[i]-3>1:\n dic[i]-=3\n c+=1\n else:\n dic[i]-=2\n c+=1\n return c", "solution_js": "var minimumRounds = function(tasks) {\n const hash = {};\n let minRounds = 0;\n\n for (const task of tasks) {\n hash[task] = hash[task] + 1 || 1;\n }\n\n for (const count of Object.values(hash)) {\n if (count < 2) return -1;\n minRounds += Math.ceil(count / 3);\n }\n\n return minRounds;\n};", "solution_java": "/**\n\tEach round, we can complete either 2 or 3 tasks of the same difficulty level\n Time: O(n)\n Space: O(n)\n*/\nclass Solution {\n public int minimumRounds(int[] tasks) {\n int round = 0;\n Map taskMap = new HashMap<>(); // map of \n for (int i = 0; i < tasks.length; i++) {\n taskMap.put(tasks[i], taskMap.getOrDefault(tasks[i], 0) + 1);\n }\n \n for (Map.Entry entry : taskMap.entrySet()) {\n if (entry.getValue() == 1) {\n return -1; // we cannot complete if there is only 1 task\n }\n\t\t\t// try to take as many 3's as possible\n round += entry.getValue() / 3; \n\t\t\t\n /*\n\t\t\t\tWe can have 1 or 2 tasks remaining. We're not supposed to take task of count 1, but we can 'borrow' 1 from the previous\n\t\t\t\tex. [5,5,5,5,5,5,5] -> [5,5,5][5,5,5][5]\n\t\t\t\tIn this example, treat the last [5,5,5], [5] as [5,5], [5,5]\n */\n if (entry.getValue() % 3 != 0) { \n round++; \n }\n }\n return round;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumRounds(vector& tasks) {\n map hm;\n for(int i=0;i= A[j]: break #Pruning for illegal Ai\n if i is not None and i < j:\n cur_len = dp[j, k] = dp[i, j] + 1\n ans = max(ans, cur_len)\n \n return ans # ans is either 0 or >=3 for SURE", "solution_js": "var lenLongestFibSubseq = function(arr) {\n let ans = 2;\n const set = new Set(arr);\n const len = arr.length\n for(let i = 0; i < len; i++) {\n for(let j = i + 1; j < len; j++) {\n let a = arr[i], b = arr[j], len = 2;\n while(set.has(a + b)) {\n len++;\n let temp = a + b;\n a = b;\n b = temp;\n }\n ans = Math.max(len, ans);\n }\n }\n return ans == 2 ? 0 : ans;\n};", "solution_java": "class Solution {\n /*\n * dp[i][j] is the max length of fibbonacci series whose last two elements\n * are A[i] & A[j]\n * for any integer A[k] we need to find two number A[i] & A[j] such that\n * i < j < k and A[i] + A[j] == A[k], we can find such pairs in O(n) time\n * complexity.\n * if there exist i,j,k such that i < j < k and A[i] + A[j] == A[k] then\n * dp[k][j] = dp[i][j] + 1 (A[k], A[j] are last two elements of fibbonacc series)\n */\n public int lenLongestFibSubseq(int[] A) {\n int n = A.length;\n int[][] dp = new int[n][n];\n int result = 0;\n for (int k = 2; k < n; k++) {\n int i = 0, j = k-1;\n while(i < j) {\n int sum = A[i] + A[j] - A[k];\n if (sum < 0) {\n i++;\n } else if (sum > 0) {\n j--;\n } else {\n // ith, jth kth element are fibbonaci sequence\n dp[j][k] = dp[i][j] + 1; // since numbers are unique\n result = Math.max(result, dp[j][k]);\n i++;\n j--;\n }\n }\n }\n return result + 2 >= 3? result + 2: 0;\n }\n}", "solution_c": "class Solution {\npublic:\n\n int help(int i,int j, unordered_map &mp,vector &nums , vector> &dp){\n\n if(dp[i][j]!=-1)\n return dp[i][j];\n\n int x=nums[i]+nums[j];\n\n if(mp.find(x)!=mp.end())\n {\n dp[i][j]=help(j,mp[x],mp,nums,dp);\n return 1+dp[i][j];\n }\n\n return 1;\n }\n\n int solve(int idx ,int n, unordered_map &mp,vector &nums , vector> &dp)\n {\n int maxi=INT_MIN;\n\n for(int i=idx;i& arr) {\n\n unordered_map mp;\n int n=arr.size();\n vector> dp(n,vector (n,-1));\n\n for(int i=0;i str:\n if len(s) < 3:\n return s\n ans = ''\n ans += s[0]\n ans += s[1]\n for i in range(2,len(s)):\n if s[i] != ans[-1] or s[i] != ans[-2]:\n ans += s[i]\n return ans", "solution_js": "var makeFancyString = function(s) {\n let res = '';\n let currCount = 0;\n \n for (let i = 0; i < s.length; i++) {\n if (currCount === 2 && s[i] === s[i - 1]) continue;\n \n else if (s[i] === s[i - 1]) {\n currCount++;\n res += s[i];\n }\n \n else {\n currCount = 1;\n res += s[i]\n }\n }\n \n return res;\n};", "solution_java": "class Solution {\n public String makeFancyString(String s) {\n char prev = s.charAt (0);\n int freq = 1;\n StringBuilder res = new StringBuilder ();\n res.append (s.charAt (0));\n for (int i = 1; i < s.length (); i++) {\n if (s.charAt (i) == prev)\n freq++;\n else {\n prev = s.charAt (i);\n freq = 1;\n }\n if (freq < 3)\n res.append (s.charAt (i));\n }\n return res.toString ();\n }\n}", "solution_c": "class Solution {\npublic:\n string makeFancyString(string s) {\n int cnt=1;\n string ans=\"\"; ans.push_back(s[0]);\n\t\t\n for(int i=1;i bool:\n n = len(grid)\n for i in range(n):\n for j in range(n):\n if i==j or (i+j) ==n-1:\n if grid[i][j] == 0:\n return False\n elif grid[i][j] != 0: \n return False\n return True;", "solution_js": "var checkXMatrix = function(grid) {\n for (let i=0; i>& grid) {\n int n = grid.size();\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n if(i == j or i == n - j - 1){\n if(!grid[i][j])\n return false;\n }else if(grid[i][j])\n return false; \n }\n }\n \n return true;\n }\n};" }, { "title": "Lowest Common Ancestor of a Binary Tree", "algo_input": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”\n\n \nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of nodes 5 and 1 is 3.\n\n\nExample 2:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n\n\nExample 3:\n\nInput: root = [1,2], p = 1, q = 2\nOutput: 1\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 105].\n\t-109 <= Node.val <= 109\n\tAll Node.val are unique.\n\tp != q\n\tp and q will exist in the tree.\n\n", "solution_py": "class Solution:\n # @param {TreeNode} root\n # @param {TreeNode} p\n # @param {TreeNode} q\n # @return {TreeNode}\n def lowestCommonAncestor(self, root, p, q):\n # escape condition\n if (not root) or (root == p) or (root == q):\n return root\n # search left and right subtree\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if left and right:\n # both found, root is the LCA\n return root\n return left or right", "solution_js": "var lowestCommonAncestor = function(root, p, q) {\n if(!root || root.val == p.val || root.val == q.val) return root;\n\n let left = lowestCommonAncestor(root.left, p, q);\n let right = lowestCommonAncestor(root.right, p, q);\n\n return (left && right) ? root : left || right;\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(int x) { val = x; }\n * }\n */\nclass Solution {\n public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n List path_to_p= new ArrayList<>();\n List path_to_q= new ArrayList<>();\n getPath(root,p,path_to_p);\n getPath(root,q,path_to_q);\n int n=path_to_q.size()>path_to_p.size()?path_to_p.size():path_to_q.size();\n TreeNode anscesstor=root;\n for(int i=0;i list){\n if(root==null) return false;\n list.add(root);\n if(root==target) return true;\n if(getPath(root.left,target,list) || getPath(root.right,target,list)){\n return true;\n }\n list.remove(list.size()-1);\n return false;\n }\n}", "solution_c": "class Solution\n{\npublic:\n TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)\n {\n if(!root)\n {\n return NULL;\n }\n if(root==p or root == q)\n {\n return root;\n }\n TreeNode *left=lowestCommonAncestor(root->left,p,q);\n TreeNode *right=lowestCommonAncestor(root->right,p,q);\n if(left and right) return root;\n if(left) return left;\n else return right;\n\n }\n};" }, { "title": "Rings and Rods", "algo_input": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.\n\nYou are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:\n\n\n\tThe first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').\n\tThe second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').\n\n\nFor example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.\n\nReturn the number of rods that have all three colors of rings on them.\n\n \nExample 1:\n\nInput: rings = \"B0B6G0R6R0R6G9\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.\n\n\nExample 2:\n\nInput: rings = \"B0R0G0R9R0B0G0\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.\n\n\nExample 3:\n\nInput: rings = \"G4\"\nOutput: 0\nExplanation: \nOnly one ring is given. Thus, no rods have all three colors.\n\n\n \nConstraints:\n\n\n\trings.length == 2 * n\n\t1 <= n <= 100\n\trings[i] where i is even is either 'R', 'G', or 'B' (0-indexed).\n\trings[i] where i is odd is a digit from '0' to '9' (0-indexed).\n\n", "solution_py": "class Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if 'R'+i in r and 'G'+i in r and 'B'+i in r:\n ans += 1\n return ans", "solution_js": "/**\n * @param {string} rings\n * @return {number}\n */\nvar countPoints = function(rings) {\n let rods = Array(10).fill(\"\");\n for(let i = 0; i < rings.length; i += 2){\n if(!(rods[rings[i+1]].includes(rings[i]))) rods[rings[i+1]] += rings[i]\n }\n return rods.filter(rod => rod.length > 2).length\n};", "solution_java": "class Solution {\n public int countPoints(String rings) {\n Map> m=new HashMap<>();\n for(int i=0;i x=m.get(index);\n x.add(c);\n m.put(index,x);\n }else{\n Set x=new HashSet<>();\n x.add(c);\n m.put(index,x);\n }\n }\n int count=0;\n for(Set k : m.values()){\n if(k.size()==3) count++;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countPoints(string rings) {\n\n int n=rings.length();\n //It is given that number of rod is 10 0 to 9 so we have to place ring any of these\n vectorvp(10,0);//store the no of rings\n for(int i=0;i int:\n return sorted(list(sum(matrix, [])))[k-1]", "solution_js": "var kthSmallest = function(matrix, k) {\n let arr = matrix.flat()\n arr.sort((a,b)=>a-b)\n return arr[k-1]\n};", "solution_java": "/**\n * Using PriorityQueue\n *\n * Time Complexity:\n * O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.\n * If we were adding all elements in one go, then the complexity would be O(min(N,K))\n * Refer: https://stackoverflow.com/a/34697891\n * O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.\n * Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))\n *\n * Space Complexity: O(min(N, K))\n *\n * N = Length of one side of the matrix. K = input value k.\n */\nclass Solution {\n public int kthSmallest(int[][] matrix, int k) {\n if (matrix == null || k <= 0) {\n throw new IllegalArgumentException(\"Input is invalid\");\n }\n\n int n = matrix.length;\n if (k > n * n) {\n throw new NoSuchElementException(\"k is greater than number of elements in matrix\");\n }\n if (k == 1) {\n return matrix[0][0];\n }\n if (k == n * n) {\n return matrix[n - 1][n - 1];\n }\n\n PriorityQueue queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));\n\n for (int i = 0; i < Math.min(n, k); i++) {\n queue.offer(new int[] { i, 0 });\n }\n while (k > 1) {\n int[] cur = queue.poll();\n if (cur[1] < n - 1) {\n cur[1]++;\n queue.offer(cur);\n }\n k--;\n }\n\n return matrix[queue.peek()[0]][queue.peek()[1]];\n }\n}", "solution_c": "class Solution {\npublic:\n int kthSmallest(vector>& matrix, int k) {\n int n = matrix.size(), start = matrix[0][0], end = matrix[n-1][n-1];\n unordered_mapmp;\n for(int i = 0; i < n; i++)\n for(int j = 0; j < n; j++)\n mp[matrix[i][j]]++;\n \n for(int i = start; i <= end; i++)\n if(mp.find(i) != mp.end()){\n for(int j = 0; j < mp[i]; j++){\n k--;\n if(k == 0) return i;\n }\n }\n return -1; \n }\n};" }, { "title": "Flipping an Image", "algo_input": "Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.\n\nTo flip an image horizontally means that each row of the image is reversed.\n\n\n\tFor example, flipping [1,1,0] horizontally results in [0,1,1].\n\n\nTo invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.\n\n\n\tFor example, inverting [0,1,1] results in [1,0,0].\n\n\n \nExample 1:\n\nInput: image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n\n\nExample 2:\n\nInput: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n\n\n \nConstraints:\n\n\n\tn == image.length\n\tn == image[i].length\n\t1 <= n <= 20\n\timages[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n return [[(1 - i) for i in row[::-1]] for row in image]", "solution_js": "var flipAndInvertImage = function(image) {\n const resversedArr = []\n for(let i=0; i> flipAndInvertImage(vector>& image) {\n int n = image.size();\n vectorans;\n for(int i=0;i int:\n stack = []\n min_index = len(nums)\n max_index = 0\n max_pop = float('-inf')\n for i in range(len(nums)):\n while stack and nums[i] < stack[-1][0]:\n\n p = stack.pop()\n if p[0] > max_pop:\n max_pop = p[0]\n if p[1] < min_index:\n min_index = p[1]\n if p[1] > max_index:\n max_index = p[1]\n stack.append([nums[i], i])\n max_r = max_index\n for st in stack:\n if st[0] < max_pop:\n max_r = st[1]\n if min_index == len(nums):\n return 0\n return max_r - min_index +1", "solution_js": "var findUnsortedSubarray = function(nums) {\n let left = 0;\n let right = nums.length - 1;\n const target = [...nums].sort((a, b) => a - b);\n\n while (left < right && nums[left] === target[left]) left += 1;\n while (right > left && nums[right] === target[right]) right -= 1;\n const result = right - left;\n\n return result === 0 ? 0 : result + 1;\n};", "solution_java": "class Solution {\n public int findUnsortedSubarray(int[] nums) {\n int[] numsClone = nums.clone();\n Arrays.sort(nums);\n\n int s = Integer.MAX_VALUE;\n int e = Integer.MIN_VALUE;\n\n for(int i = 0; i& nums) {\n\t\t// max_list refers to: the max value on the left side of the current element\n\t\t// min_list refers to: the min value on the right side of the current element\n vector max_list(nums.size(), 0);\n vector min_list(nums.size(), 0);\n min_list[nums.size()-1] = max_value;\n max_list[0] = min_value;\n \n // init two lists\n for(int i=nums.size()-2; i>=0; i--)\n min_list[i] = min(min_list[i+1], nums[i+1]);\n \n for(int i=1; i= nums[left])\n left++;\n \n // get right bound\n int right = nums.size() - 1;\n while(right >= 0 && max_list[right] <= nums[right])\n right--;\n \n if (left == nums.size()) // monotonic ascending array\n return 0;\n else\n return (right-left+1);\n }\n};" }, { "title": "Number of Pairs of Interchangeable Rectangles", "algo_input": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.\n\nTwo rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).\n\nReturn the number of pairs of interchangeable rectangles in rectangles.\n\n \nExample 1:\n\nInput: rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput: 6\nExplanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.\n\n\nExample 2:\n\nInput: rectangles = [[4,5],[7,8]]\nOutput: 0\nExplanation: There are no interchangeable pairs of rectangles.\n\n\n \nConstraints:\n\n\n\tn == rectangles.length\n\t1 <= n <= 105\n\trectangles[i].length == 2\n\t1 <= widthi, heighti <= 105\n\n", "solution_py": "class Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n ratios = defaultdict(int)\n for x, y in rectangles:\n ratios[x/y] += 1\n res = 0\n for val in ratios.values():\n res += (val*(val-1)//2)\n return res", "solution_js": "/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nvar interchangeableRectangles = function(rectangles) {\n let map = new Map();\n for (let i = 0; i < rectangles.length; i++) {\n let [a, b] = rectangles[i];\n let val = a / b;\n if (!map.get(val)) map.set(val, [0, 0]);\n else {\n const [count, total] = map.get(val);\n map.set(val, [count + 1, total + count + 1]);\n }\n }\n \n return [...map.entries()].reduce((prev, [key, [count, total]]) => {\n if (count < 1) return prev;\n return prev + total;\n }, 0);\n};", "solution_java": "class Solution {\n \n public long interchangeableRectangles(int[][] rectangles) {\n Map hash = new HashMap<>();\n \n for (int i = 0; i < rectangles.length; i++) {\n Double tmp = (double) (rectangles[i][0] / (double) rectangles[i][1]);\n \n hash.put(tmp, hash.getOrDefault(tmp, 0L) + 1);\n }\n \n long ans = 0;\n for (Map.Entry entry : hash.entrySet()) {\n if (entry.getValue() > 1) {\n Long n = entry.getValue();\n ans += (n * (n - 1)) / 2;\n }\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n long long interchangeableRectangles(vector>& rectangles) {\n int n = rectangles.size();\n unordered_map mp;\n for(int i = 0;i List[int]:\n arr = []\n hashmap = {char: arr1.count(char) for char in arr1}\n [arr.extend([char] * hashmap.pop(char)) for char in arr2]\n return arr + sorted([int(key) * hashmap[key] for key in hashmap]", "solution_js": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number[]}\n */\nvar relativeSortArray = function(arr1, arr2) {\n const indices = new Map();\n arr2.forEach(indices.set, indices);\n\n return arr1.sort((a, b) => {\n if (indices.has(a)) {\n return indices.has(b) ? indices.get(a) - indices.get(b) : -1;\n }\n if (indices.has(b)) {\n return 1;\n }\n return a - b;\n });\n};", "solution_java": "class Solution {\n public int[] relativeSortArray(int[] arr1, int[] arr2) {\n Map map = new TreeMap();\n for(int i = 0; i relativeSortArray(vector& arr1, vector& arr2) {\n mapsk;\n vectorres;\n for(auto i:arr1){\n sk[i]++;\n }\n for(auto j:arr2){\n for(auto z:sk){\n if(z.first==j){\n int x=z.second;\n for(int l=0;l& arr) {\n \n sort(arr.begin(), arr.end());\n \n int i =0;\n int j = 1;\n int n = arr.size();\n while(iarr[j])j++;\n else if(i==j && arr[i]==0){\n i++;\n j++;\n }\n \n else return true;\n \n }\n return false;\n \n }\n};" }, { "title": "Group the People Given the Group Size They Belong To", "algo_input": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.\n\nYou are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.\n\nReturn a list of groups such that each person i is in a group of size groupSizes[i].\n\nEach person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.\n\n \nExample 1:\n\nInput: groupSizes = [3,3,3,3,3,1,3]\nOutput: [[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\n\n\nExample 2:\n\nInput: groupSizes = [2,1,3,3,3,2]\nOutput: [[1],[0,5],[2,3,4]]\n\n\n \nConstraints:\n\n\n\tgroupSizes.length == n\n\t1 <= n <= 500\n\t1 <= groupSizes[i] <= n\n\n", "solution_py": "class Solution(object):\n def groupThePeople(self, groupSizes):\n \"\"\"\n :type groupSizes: List[int]\n :rtype: List[List[int]]\n \"\"\"\n dict_group={}\n for i in range(len(groupSizes)):\n if groupSizes[i] not in dict_group:\n dict_group[groupSizes[i]]=[i]\n else:\n dict_group[groupSizes[i]].append(i)\n return_list=[]\n for i in dict_group:\n num_list=dict_group[i]\n for j in range(0,len(num_list),i):\n return_list.append(num_list[j:j+i])\n return return_list", "solution_js": "/**\n * @param {number[]} groupSizes\n * @return {number[][]}\n */\nvar groupThePeople = function(groupSizes) {\n let indices = [], result = [];\n groupSizes.forEach((x, idx) => {\n if (indices[x]) indices[x].push(idx);\n else indices[x] = [idx];\n if (indices[x].length === x) {\n result.push(indices[x]);\n indices[x] = undefined;\n }\n });\n return result;\n};", "solution_java": "class Solution {\n public List> groupThePeople(int[] groupSizes) {\n\n List> temp = new ArrayList>();\n List> result = new ArrayList>();\n for(int i = 0; itemp.get(j).get(1)){\n result.get(j).add(i);\n temp.get(j).set(1,temp.get(j).get(1)+1);\n flag=false;\n break;\n }\n }\n if(flag){\n // comment 1\n // We create a list with index and put it to result\n List res = new ArrayList();\n res.add(i);\n result.add(res);\n // comment 2\n // we create a new list recording max value can stored and currently filled\n List tempRes = new ArrayList();\n tempRes.add(k);\n tempRes.add(1);\n temp.add(tempRes);\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> groupThePeople(vector& groupSizes) {\n vector>ans;\n unordered_map> store;\n \n for(int i=0;i List[int]:\n m = len(nums1)\n n = len(nums2)\n dp = {}\n \n # get the max number string with \"length\" from index \"i\" in nums1 and index \"j\" in nums2\n # using number string to easy to compare\n def getMaxNumberString(i, j, length):\n if length == 0:\n return \"\"\n \n # using memoization to optimize for the overlapping subproblems\n key = (i, j, length)\n if key in dp:\n return dp[key]\n \n # greedy to find the possible max digit from nums1 and nums2\n # 1) bigger digit in the higher position of the number will get bigger number\n # 2) at the same time, we need to ensure that we still have enough digits to form a number with \"length\" digits\n \n # try to find the possible max digit from index i in nums1\n index1 = None\n for ii in range(i, m):\n if (m - ii + n - j) < length:\n break\n if index1 is None or nums1[index1] < nums1[ii]:\n index1 = ii\n \n # try to find the possible max digit from index j in nums2\n index2 = None\n for jj in range(j, n):\n if (m - i + n - jj) < length:\n break\n if index2 is None or nums2[index2] < nums2[jj]:\n index2 = jj\n \n maxNumberStr = None\n if index1 is not None and index2 is not None:\n if nums1[index1] > nums2[index2]:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif nums1[index1] < nums2[index2]:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n else:\n # get the same digit from nums1 and nums2, so need to try two cases and get the max one \n maxNumberStr = max(str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1), str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1))\n elif index1 is not None:\n maxNumberStr = str(nums1[index1]) + getMaxNumberString(index1 + 1, j, length - 1)\n elif index2 is not None:\n maxNumberStr = str(nums2[index2]) + getMaxNumberString(i, index2 + 1, length - 1)\n \n dp[key] = maxNumberStr\n return maxNumberStr\n\n result_str = getMaxNumberString(0, 0, k)\n \n # number string to digit array\n result = []\n for c in result_str:\n result.append(int(c))\n \n return result", "solution_js": "const maxNumber = (a, b, k) => {\n let m = a.length, n = b.length;\n let res = [];\n for (let i = Math.max(0, k - n); i <= Math.min(k, m); i++) {\n let maxA = maxArray(a, i), maxB = maxArray(b, k - i);\n let merge = mergeArray(maxA, maxB);\n if (merge > res) res = merge;\n }\n return res;\n};\n\nconst maxArray = (a, k) => {\n let drop = a.length - k, res = [];\n for (const x of a) {\n while (drop > 0 && res.length && res[res.length - 1] < x) {\n res.pop();\n drop--;\n }\n res.push(x);\n }\n if (res.length >= k) {\n res = res.slice(0, k);\n } else {\n res = res.concat(Array(k - res.length).fill(0));\n }\n return res;\n};\n\nconst mergeArray = (a, b) => {\n let res = [];\n while (a.length + b.length) res.push(a > b ? a.shift() : b.shift())\n return res;\n};", "solution_java": "class Solution {\n public int[] maxNumber(int[] nums1, int[] nums2, int k) {\n String ans=\"\";\n for (int i = Math.max(0, k-nums2.length); i <= Math.min(nums1.length, k); i++){ // try all possible lengths from each seq\n String one = solve(nums1, i); // find the best seq matching len of i\n String two = solve(nums2, k-i); // len of k-i\n StringBuilder sb = new StringBuilder();\n int a = 0, b = 0;\n while(a < i || b < k-i){ // merge it to the max\n sb.append(one.substring(a).compareTo(two.substring(b))>=0?one.charAt(a++):two.charAt(b++));\n }\n if (sb.toString().compareTo(ans)>0){ // if better, we replace.\n ans=sb.toString();\n }\n }\n int[] res = new int[k];\n for (int i = 0; i < k;++i){\n res[i]=ans.charAt(i)-'0';\n }\n return res;\n }\n\n private String solve(int[] arr, int k){\n Deque stack = new ArrayDeque<>();\n for (int i = 0;ik&&stack.peek() maxArray(vector&nums,int k){\n int n=nums.size();\n stackseen;\n for(int i=0;i=k)seen.pop();\n if(seen.size()res(k,0);\n for(int i=res.size()-1;i>=0;i--){\n res[i]=seen.top();\n seen.pop();\n }\n return res;\n }\n bool greater(vector&arr1,int i,vector&arr2,int j){\n for(;iarr2[j];\n }\n return i!=arr1.size();\n }\n vector merge(vector&arr1,vector&arr2){\n vectorres(arr1.size()+arr2.size());\n for(int ind=0,i=0,j=0;ind maxNumber(vector& nums1, vector& nums2, int k) {\n int m=nums1.size(),n=nums2.size();\n vectorans;\n for(int len1=max(0,k-n);len1<=min(m,k);len1++){\n int len2 = k-len1;\n vector arr1 = maxArray(nums1,len1);\n vector arr2 = maxArray(nums2,len2);\n vector temp_res = merge(arr1,arr2);\n if(greater(temp_res,0,ans,0)){\n ans.resize(temp_res.size());\n for(int i=0;i bool:\n return Counter(s) == Counter(t)", "solution_js": "var isAnagram = function(s, t) {\n if(s.length !== t.length) return false\n \n let charFreq = {}\n \n for(let char of s){\n charFreq[char] ? charFreq[char] +=1 : charFreq[char] = 1\n }\n \n for(let char of t){\n if(!(charFreq[char])) return false\n charFreq[char] -= 1\n }\n return true\n};", "solution_java": "class Solution {\n public boolean isAnagram(String s, String t) {\n if (s.length() != t.length()) return false;\n int[] haha1 = new int[26];//26 because input contains of only lower english letters\n int[] haha2 = new int[26];\n for (int i = 0; i < s.length(); ++i) {\n haha1[(int)s.charAt(i)-97] += 1;//omitting 97 because 'a' is 97, it will be 0 now\n haha2[(int)t.charAt(i)-97] += 1;\n }\n for (int i = 0; i < haha1.length; ++i) {\n if (haha1[i] != haha2[i]) return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isAnagram(string s, string t) {\n sort(s.begin(), s.end());\n sort(t.begin(), t.end());\n\n if(s != t)\n return false;\n\n return true;\n }\n};" }, { "title": "Integer Break", "algo_input": "Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.\n\nReturn the maximum product you can get.\n\n \nExample 1:\n\nInput: n = 2\nOutput: 1\nExplanation: 2 = 1 + 1, 1 × 1 = 1.\n\n\nExample 2:\n\nInput: n = 10\nOutput: 36\nExplanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 58\n\n", "solution_py": "class Solution:\n def integerBreak(self, n: int) -> int:\n dp = [0 for _ in range(n+1)]\n dp[1] = 1\n for i in range(2, n+1):\n for j in range(1, i//2+1):\n dp[i] = max(j * (i-j), j * dp[i-j], dp[i])\n return dp[-1]", "solution_js": "var integerBreak = function(n) {\n\n if(n == 2) return 1;\n if(n == 3) return 2;\n if(n == 4) return 4;\n\n let c = ~~(n/3);\n let d = n % 3;\n\n if(d === 0){\n return 3 ** c;\n }\n\n if(d === 1){\n return 3 ** (c-1) * 4;\n }\n\n if(d === 2){\n return 3 ** (c) * 2;\n }\n\n};", "solution_java": "class Solution {\n public int integerBreak(int n) {\n //dp array: maximum product of splitling int i\n int[] dp = new int[n + 1];\n \n // traverse\n for (int i = 2; i <= n; i++) {\n for (int j = 1; j <= i / 2; j++) {\n dp[i] = Math.max(Math.max(j * (i - j), j * dp[i - j]), dp[i]);\n }\n }\n return dp[n];\n }\n}", "solution_c": "class Solution\n{\npublic:\n int integerBreak(int n)\n {\n if (n == 2)\n return 1;\n if (n == 3)\n return 2;\n if (n == 4)\n return 4;\n int k = n / 3;\n int m = n % 3;\n int ans;\n if (m == 0)\n ans = pow(3, k);\n else if (m == 1)\n ans = pow(3, k - 1) * 4;\n else if (m == 2)\n ans = pow(3, k) * m;\n return ans;\n }\n};" }, { "title": "Minimum Number of Arrows to Burst Balloons", "algo_input": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.\n\nArrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.\n\nGiven the array points, return the minimum number of arrows that must be shot to burst all balloons.\n\n \nExample 1:\n\nInput: points = [[10,16],[2,8],[1,6],[7,12]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].\n\n\nExample 2:\n\nInput: points = [[1,2],[3,4],[5,6],[7,8]]\nOutput: 4\nExplanation: One arrow needs to be shot for each balloon for a total of 4 arrows.\n\n\nExample 3:\n\nInput: points = [[1,2],[2,3],[3,4],[4,5]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].\n\n\n \nConstraints:\n\n\n\t1 <= points.length <= 105\n\tpoints[i].length == 2\n\t-231 <= xstart < xend <= 231 - 1\n\n", "solution_py": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points.sort()\n \n ans=[points[0]]\n for i in points[1:]:\n if(i[0]<=ans[-1][1]):\n ans[-1]=[ans[-1][0],min(ans[-1][1],i[1])]\n else:\n ans.append(i)\n return len(ans)\n ", "solution_js": "var findMinArrowShots = function(points) {\n points.sort((a, b) => a[0] - b[0])\n\n let merged = [points[0]];\n\n let earliestEnd = points[0][1];\n\n for (let i = 1; i < points.length; i++) {\n let lastEnd = merged[merged.length - 1][1];\n let currStart = points[i][0];\n let currEnd = points[i][1];\n\n if (lastEnd >= currStart && currStart <= earliestEnd) {\n merged[merged.length - 1][1] = Math.max(lastEnd, currEnd)\n earliestEnd = Math.min(earliestEnd, points[i][1]);\n }\n else {\n merged.push(points[i])\n earliestEnd = points[i][1]\n }\n }\n\n return merged.length\n};", "solution_java": "class Solution {\n public int findMinArrowShots(int[][] points) {\n \n int minNumArrows = 1;\n Arrays.sort(points, new Comparator(){\n @Override\n public int compare(int[] i1, int[] i2)\n {\n if(i1[0] < i2[0])\n return -1;\n else if (i1[0] > i2[0])\n return 1;\n return 0;\n }\n });\n \n // This is where they will trip you up ( at the merge stage )\n // Wait ... do we actually have to merge here? The intervals have been sorted already\n // No you must merge\n // See if they can be merged\n // If mergeable - overwrite OR write into a new subintervals code ( new ArrayList ) \n // Ok ... so first we compare (a1,a2) and then next step compare (a2,a3)\n // Now if (a1,a2) had an overlap -> why not make the next a2 = merged(a1,a2)? \n // That would do a carry over effect then\n int n = points.length;\n int[] candid = new int[2]; // always first interval anyways\n candid[0] = points[0][0];\n candid[1] = points[0][1];\n for(int i = 1; i < n; i++)\n {\n // System.out.printf(\"Current set = (%d,%d)\\n\", candid[0], candid[1]);\n int[] next = points[i];\n if(hasOverlap(candid,next))\n {\n int[] merged = mergeInterval(candid,next);\n candid[0] = merged[0];\n candid[1] = merged[1];\n }\n else\n {\n candid[0] = next[0];\n candid[1] = next[1]; \n minNumArrows++;\n }\n }\n \n return minNumArrows;\n }\n \n public boolean hasOverlap(int[] i1, int[] i2)\n {\n boolean hasOverlap = false;\n if(i1[0] <= i2[0] && i2[0] <= i1[1])\n hasOverlap = true;\n if(i2[0] <= i1[0] && i1[0] <= i2[1])\n hasOverlap = true;\n return hasOverlap;\n }\n \n public int[] mergeInterval(int[] i1, int[] i2)\n {\n int[] merged = new int[2];\n merged[0] = Math.max(i1[0],i2[0]);\n merged[1] = Math.min(i1[1],i2[1]);\n return merged;\n }\n}", "solution_c": "class Solution {\npublic:\n static bool cmp(vector&a,vector&b)\n {\n return a[1]>& points) {\n sort(points.begin(),points.end(),cmp);\n //burst the first ballon at least\n int arrow=1;\n int end=points[0][1];\n for(int i=1;iend)\n {\n arrow++;\n end=points[i][1];\n }\n }\n return arrow;\n }\n};" }, { "title": "Kth Largest Element in a Stream", "algo_input": "Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n\nImplement KthLargest class:\n\n\n\tKthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.\n\tint add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.\n\n\n \nExample 1:\n\nInput\n[\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]\nOutput\n[null, 4, 5, 5, 8, 8]\n\nExplanation\nKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3); // return 4\nkthLargest.add(5); // return 5\nkthLargest.add(10); // return 5\nkthLargest.add(9); // return 8\nkthLargest.add(4); // return 8\n\n\n \nConstraints:\n\n\n\t1 <= k <= 104\n\t0 <= nums.length <= 104\n\t-104 <= nums[i] <= 104\n\t-104 <= val <= 104\n\tAt most 104 calls will be made to add.\n\tIt is guaranteed that there will be at least k elements in the array when you search for the kth element.\n\n", "solution_py": "class KthLargest:\n def __init__(self, k: int, nums: List[int]):\n self.k = k\n self.hp = []\n for x in nums:\n self.add(x)\n\n return None\n\n def add(self, val: int) -> int:\n heapq.heappush(self.hp, (val))\n if len(self.hp) > self.k:\n heapq.heappop(self.hp)\n\n return self.get_kth_largest()\n\n def get_kth_largest(self):\n return self.hp[0]", "solution_js": "var KthLargest = function(k, nums) {\n // sort ascending because I am familiar with it\n // when applying my binary search algorithm\n this.nums = nums.sort((a,b) => a - b); \n this.k = k; \n};\n\nKthLargest.prototype.add = function(val) {\n // search a place to push val\n // using binary search\n let left = 0; right = this.nums.length - 1;\n while (left < right) {\n let mid = left + Math.floor((right + 1 - left)/2);\n \n if (val < this.nums[mid]) {\n right = mid - 1;\n } else {\n left = mid\n }\n } \n \n // push val into the nums\n this.nums.splice(left+(this.nums[left] < val ? 1 : 0), 0, val); \n\n // because our nums is sorted\n // so kth largest element is easy to be returned\n return this.nums[this.nums.length-this.k]\n};", "solution_java": "class KthLargest {\n PriorityQueue queue=new PriorityQueue();\n int k=0;\n public KthLargest(int k, int[] nums) {\n this.k=k;\n for(int i:nums)\n add(i);\n }\n \n public int add(int val) {\n if(k>queue.size())\n queue.add(val);\n else\n if(val>queue.peek())\n {\n queue.poll();\n queue.add(val);\n }\n return queue.peek();\n }\n}", "solution_c": "class KthLargest {\n \n int k;\n priority_queue, greater> minheap;\n int n;\n \npublic:\n KthLargest(int k, vector& nums) {\n this->k=k;\n this->n=nums.size();\n \n// push the initial elements in the heap\n for(auto x : nums){\n minheap.push(x);\n }\n \n// if the no. of elements are greater than k then remove them\n while(n>k){\n minheap.pop();\n n--;\n }\n } \n \n int add(int val) {\n \n// if heap is empty or no. of elements are less than k then add the input\n if(minheap.empty() || nn=n+1;\n }\n// else compare it with top\n else{\n int minn=minheap.top();\n// if the input is greater than top\n if(minnadd(val);\n */" }, { "title": "Degree of an Array", "algo_input": "Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.\n\nYour task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.\n\n \nExample 1:\n\nInput: nums = [1,2,2,3,1]\nOutput: 2\nExplanation: \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\n\n\nExample 2:\n\nInput: nums = [1,2,2,3,1,4,2]\nOutput: 6\nExplanation: \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n\n\n \nConstraints:\n\n\n\tnums.length will be between 1 and 50,000.\n\tnums[i] will be an integer between 0 and 49,999.\n\n", "solution_py": "class Solution:\n def findShortestSubArray(self, nums):\n # Group indexes by element type\n d = defaultdict(list)\n for i,x in enumerate(nums):\n d[x].append(i)\n #\n # Find highest Degree\n m = max([ len(v) for v in d.values() ])\n #\n # Find shortest span for max. degree\n best = len(nums)\n for v in d.values():\n if len(v)==m:\n best = min(best,v[-1]-v[0]+1)\n return best", "solution_js": "/**\n * 1. compute all positions for each number\n * 2. filter arrays of max length\n * 3. select minimum difference between its first and last elems\n */\nvar findShortestSubArray = function(nums) {\n const numPositions = {};\n for (let i=0; i maxLen) {\n maxLen = curLen;\n maxPos = [positions]\n }\n }\n\n let minDist = Number.MAX_SAFE_INTEGER;\n for (const positions of maxPos) {\n minDist = Math.min(minDist, positions[positions.length-1] - positions[0] + 1);\n }\n return minDist;\n};", "solution_java": "class Solution {\n public int findShortestSubArray(int[] nums) {\n int ans = Integer.MAX_VALUE;\n Map count = new HashMap<>();\n Map startIndex = new HashMap<>();\n Map endIndex = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n count.put(nums[i], count.getOrDefault(nums[i], 0) + 1);\n }\n\n for (int i = 0; i < nums.length; i++) {\n int no = nums[i];\n if (!startIndex.containsKey(no)) {\n startIndex.put(no, i);\n }\n endIndex.put(no, i);\n }\n\n int degree = Integer.MIN_VALUE;\n for (Integer key : count.keySet()) {\n degree = Math.max(degree, count.get(key));\n }\n\n for (Integer key : count.keySet()) {\n if (count.get(key) == degree) {\n int arraySize = endIndex.get(key) - startIndex.get(key) + 1;\n ans = Math.min(ans, arraySize);\n }\n }\n\n return ans; \n }\n}", "solution_c": "class Solution {\npublic:\n int findShortestSubArray(vector& nums)\n {\n unordered_map cnt,first;\n int deg=0,ans=0;\n for(int i=0;ideg)\n {\n ans=i-first[nums[i]]+1;\n deg=cnt[nums[i]];\n }\n else if(cnt[nums[i]]==deg)\n {\n ans=min(ans,i-first[nums[i]]+1);\n }\n\n }\n return ans;\n\n }\n};\n//if you like the solution plz upvote." }, { "title": "Min Cost to Connect All Points", "algo_input": "You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].\n\nThe cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.\n\nReturn the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.\n\n \nExample 1:\n\nInput: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput: 20\nExplanation: \n\nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\n\n\nExample 2:\n\nInput: points = [[3,12],[-2,5],[-4,1]]\nOutput: 18\n\n\n \nConstraints:\n\n\n\t1 <= points.length <= 1000\n\t-106 <= xi, yi <= 106\n\tAll pairs (xi, yi) are distinct.\n\n", "solution_py": "class Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n\n cost = 0\n heap = []\n\n #set to store past points to prevent cycle\n visited = set([0])\n\n #i == the index of current point\n i = 0\n\n while len(visited) < len(points):\n #Add all costs from current point to unreached points to min heap\n for j in range(len(points)):\n if j == i or j in visited:\n continue\n distance = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])\n heapq.heappush(heap, (distance, j))\n\n #Add new min cost edge\n while True:\n dist, point = heapq.heappop(heap)\n if point not in visited:\n cost += dist\n #Add point to visited to prevent cycle\n visited.add(point)\n #Update point\n i = point\n break\n\n return cost", "solution_js": "/**\n * @param {number[][]} points\n * @return {number}\n */\n//By Kruskal Approach\nlet union_find,mapping_arr,count,maxCost,rank\nconst find=(root)=>{\n if(union_find[root]===root)return root;\n return union_find[root]= find(union_find[root]);\n}\nconst union=([src,dst,d])=>{\n let rootX=find(src);\n let rootY=find(dst);\n if(rootX!=rootY){\n if(rank[rootX]rank[rootY]){\n union_find[rootY]=rootX;\n }else{\n union_find[rootY]=rootX;\n rank[rootX]++;\n }\n count--;\n maxCost+=d;\n }\n \n \n}\nvar minCostConnectPoints = function(points) {\n let edges=[];\n union_find=[];\n rank=[];\n maxCost=0;\n count=points.length;\n for(let i=0;ia[2]-b[2])\n for(let i=0;i1)\n union(edges[i]);\n }\n\n return maxCost;\n \n};", "solution_java": "class Solution {\n\tpublic int minCostConnectPoints(int[][] points) {\n\t\tint n = points.length;\n\t\tPriorityQueue pq = new PriorityQueue<>((a,b)->a[0]-b[0]);\n\t\tfor(int i = 0; i < n; i++) {\n\t\t\tfor(int j = i + 1; j < n; j++) {\n\t\t\t\tpq.add(new int[]{calDis(points,i,j),i,j});\n\t\t\t}\n\t\t}\n\t\tint c = 0, ans = 0;\n\t\tUnionFind uf = new UnionFind(n);\n\t\twhile(c < n-1){\n\t\t\tint[] cur = pq.poll();\n\t\t\tif(uf.find(cur[1]) != uf.find(cur[2])) {\n\t\t\t\tans += cur[0];\n\t\t\t\tuf.union(cur[1],cur[2]);\n\t\t\t\tc++;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\tprivate int calDis(int[][] points, int a, int b) {\n\t\treturn Math.abs(points[a][0] - points[b][0]) + Math.abs(points[a][1] - points[b][1]);\n\t}\n\tclass UnionFind{\n\t\tint[] parent;\n\t\tUnionFind(int n){\n\t\t\tthis.parent = new int[n];\n\t\t\tfor(int i=0;i>& points) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n int n = points.size();\n priority_queue> q;\n unordered_set vis;\n int ans = 0;\n q.push({0,0,0});\n vector cur;\n while(!q.empty() && vis.size() List[int]:\n\n items.sort()\n dic = dict()\n res = []\n gmax = 0\n for p,b in items:\n gmax = max(b,gmax)\n dic[p] = gmax\n\n keys = sorted(dic.keys())\n for q in queries:\n ind = bisect.bisect_left(keys,q)\n if ind a[0]-b[0]);\n const n = items.length;\n \n \n let mx = items[0][1];\n \n for (let i = 0; i (a[0] - b[0]));\n int maxBeautySoFar = Integer.MIN_VALUE;\n int[] maxBeauty = new int[items.length];\n \n for(int i = 0; i < items.length; i++) {\n if(maxBeautySoFar < items[i][1]) maxBeautySoFar = items[i][1];\n maxBeauty[i] = maxBeautySoFar;\n }\n \n for(int i = 0; i < queries.length; i++) {\n int idx = findLargestIdxWithPriceLessThan(items, queries[i]);\n if(idx != Integer.MIN_VALUE) ans[i] = maxBeauty[idx];\n }\n return ans;\n }\n \n public int findLargestIdxWithPriceLessThan(int[][] items, int price) {\n int l = 0;\n int r = items.length - 1;\n int maxIdxLessThanEqualToPrice = Integer.MIN_VALUE; \n while(l <= r) {\n int mid = (l + r)/2;\n if(items[mid][0] > price) {\n r = mid - 1;\n } else {\n maxIdxLessThanEqualToPrice = Math.max(maxIdxLessThanEqualToPrice, mid);\n l = mid + 1;\n }\n }\n return maxIdxLessThanEqualToPrice;\n }\n}", "solution_c": "class Solution {\npublic:\n vector maximumBeauty(vector>& items, vector& queries) {\n vector> v;\n int n = queries.size();\n for(int i = 0; i < n; i++){\n v.push_back({queries[i],i});\n }\n sort(v.begin(),v.end());\n sort(items.begin(),items.end());\n vector ans(n);\n int j=0;\n n = items.size();\n int mx = 0;\n for(auto &i: v){\n while(j {\n\t\tif (!node) return;\n\t\tif (currentDep === depth - 1) {\n\t\t\tconst { left, right } = node;\n\t\t\tnode.left = new TreeNode(val, left);\n\t\t\tnode.right = new TreeNode(val, null, right);\n\t\t}\n\t\trefactor(node.left, currentDep + 1);\n\t\trefactor(node.right, currentDep + 1);\n\t};\n\trefactor();\n\treturn root;\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 TreeNode addOneRow(TreeNode root, int val, int depth) {\n findAndAdd(root, val, depth, 1);\n return root; \n }\n\n public void findAndAdd(TreeNode root, int val, int depth, int currDepth){\n if(depth == 1 && currDepth == 1){\n root.left = new TreeNode(root.val, root.left, root.right);\n root.right = null;\n root.val = val;\n return;\n }\n if(root == null)\n return;\n if(currDepth == depth - 1){\n root.left = new TreeNode(val, root.left, null);\n root.right = new TreeNode(val, null, root.right);\n }else{\n findAndAdd(root.left, val, depth, currDepth + 1);\n findAndAdd(root.right, val, depth, currDepth + 1);\n }\n return;\n }\n}", "solution_c": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# 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\n\n\nclass Solution:\n\n def Solve(\n self,\n root,\n val,\n depth,\n curr,\n ):\n if root == None:\n return None\n if depth == 1:\n return TreeNode(val, root)\n if curr == depth - 1:\n (left, right) = (root.left, root.right)\n (root.left, root.right) = (TreeNode(val, left),\n TreeNode(val, None, right))\n return root\n self.Solve(root.left, val, depth, curr + 1)\n self.Solve(root.right, val, depth, curr + 1)\n return root\n\n def addOneRow(\n self,\n root,\n val,\n depth,\n ):\n return self.Solve(root, val, depth, 1)" }, { "title": "Find Right Interval", "algo_input": "You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.\n\nThe right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.\n\nReturn an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.\n\n \nExample 1:\n\nInput: intervals = [[1,2]]\nOutput: [-1]\nExplanation: There is only one interval in the collection, so it outputs -1.\n\n\nExample 2:\n\nInput: intervals = [[3,4],[2,3],[1,2]]\nOutput: [-1,0,1]\nExplanation: There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.\n\n\nExample 3:\n\nInput: intervals = [[1,4],[2,3],[3,4]]\nOutput: [-1,2,-1]\nExplanation: There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.\n\n\n \nConstraints:\n\n\n\t1 <= intervals.length <= 2 * 104\n\tintervals[i].length == 2\n\t-106 <= starti <= endi <= 106\n\tThe start point of each interval is unique.\n\n", "solution_py": "class Solution:\n def findRightInterval(self, A: List[List[int]]) -> List[int]:\n n = len(A)\n ans = [-1] * n\n\n for i in range(n):\n A[i].append(i)\n\n A.sort()\n heap = []\n\n for i in range(n):\n if A[i][0] == A[i][1]:\n ans[A[i][2]] = A[i][2]\n else:\n while heap and heap[0][0] <= A[i][0]:\n ans[heapq.heappop(heap)[1]] = A[i][2]\n \n heapq.heappush(heap, [A[i][1], A[i][2]])\n\n return ans", "solution_js": "var findRightInterval = function(intervals) {\n const data = intervals\n .map((interval, i) => ({ interval, i }))\n .sort((a, b) => a.interval[0] - b.interval[0]);\n\n const res = Array(intervals.length).fill(-1);\n\n for (let pos = 0; pos < data.length; pos++) {\n let left = pos;\n let right = data.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n\n if (data[pos].interval[1] <= data[mid].interval[0]) {\n right = mid - 1;\n } else {\n left = mid + 1; \n }\n }\n\n if (left < data.length) {\n res[data[pos].i] = data[left].i;\n }\n }\n \n return res;\n};", "solution_java": "/*\n- Time: O(N*log(N))\nLoop through the array with n elements and run binary search with log(N) time for each of them.\n\n- Space: O(N)\nUsed a hashmap map of size N to store the original indeces of intervals\n */\nclass Solution {\n public int[] findRightInterval(int[][] intervals) {\n int n = intervals.length;\n int[] res = new int[n];\n Map map = new HashMap<>();\n for (int i = 0; i < n; i++) {\n map.put(intervals[i], i);\n }\n\n Arrays.sort(intervals, (a, b) -> a[0] - b[0]);\n for (int i = 0; i < n; i++) {\n int[] interval = binarySearch(intervals, intervals[i][1], i);\n res[map.get(intervals[i])] = interval == null ? -1 : map.get(interval);\n }\n \n return res;\n }\n\n private int[] binarySearch(int[][] intervals, int target, int start) {\n int l = start, r = intervals.length - 1;\n \n while (l <= r) {\n int m = l + (r - l) / 2;\n if (intervals[m][0] >= target) {\n // keep moving the right boundary to the left to get the first\n // element bigger than target\n r = m - 1;\n } else {\n // if the element we get is bigger than the target, we move the \n // left boundary to look at right part of the array\n l = m + 1;\n }\n }\n return l == intervals.length ? null : intervals[l];\n }\n}", "solution_c": "class Solution {\npublic:\n vector findRightInterval(vector>& intervals) {\n\n map mp;\n int n = intervals.size();\n\n for(int i = 0; i < n; i++)\n mp[intervals[i][0]] = i;\n\n vector ans;\n for(auto &i : intervals)\n {\n auto it = mp.lower_bound(i[1]);\n ans.push_back(it == mp.end() ? -1 : it->second);\n }\n\n return ans;\n }\n};" }, { "title": "Letter Tile Possibilities", "algo_input": "You have n  tiles, where each tile has one letter tiles[i] printed on it.\n\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n\n \nExample 1:\n\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n\n\nExample 2:\n\nInput: tiles = \"AAABBC\"\nOutput: 188\n\n\nExample 3:\n\nInput: tiles = \"V\"\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= tiles.length <= 7\n\ttiles consists of uppercase English letters.\n\n", "solution_py": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n n= len(tiles)\n tiles=list(tiles)\n s1=set()\n for i in range(1,n+1):\n s1.update(permutations(tiles,i))\n return len(s1)", "solution_js": "//\"\"This solution isn`t the best way but it`s simple\"\"\n var numTilePossibilities = function(tiles) {\n return search(tiles);\n};\n// this function takes a state and check if it`s valid or !\n// valid state is not null state and unique\n// e.g [\"\",\"A\",\"A\"]=>is not valid state because is has null state and repeated\n// values by contrast [\"A\"] is valid state\n// !!state below is to check if state not null\nconst isValidState=(state=\"\",res=[])=>!!state&&!res.includes(state);\n// this function permutes tiles by backtracking\nconst search=(tiles=\"\",state='',result=[])=>{\n if(isValidState(state,result))//check if the current state valid\n result.push(state)\n //loop through tiles and every time you push letter to state\n // the remaining tiles will decreased by one\n /**\n * ---e.g--\n * level 1 tiles=AAB state=\"\"\n * it will loop through the tiles ;\n * now I am in index 0 push tiles[0] to state now state=A\n * by making this operation number of option tiles will be\n * decreased to newTiles=\"AB\"\n * ...\n * ..\n * .\n * */\n for(let i=0;i map = new HashMap<>();\n for(char c:tiles.toCharArray()){\n map.put(c,map.getOrDefault(c,0)+1);\n }\n find(map);\n return result-1;\n }\n public void find(Map map){\n result++;\n for(Map.Entry m:map.entrySet()){\n char c=m.getKey();\n int val =m.getValue();\n if(val>0){\n map.put(c,val-1);\n find(map);\n map.put(c,val);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void recur(vector &ans, string tiles, int index, int &res)\n {\n res++;\n\n for(int i=index; i ans;\n sort(tiles.begin(), tiles.end());\n int res = 0;\n recur(ans, tiles, 0, res);\n return res - 1;\n }\n};" }, { "title": "Maximum Number of Weeks for Which You Can Work", "algo_input": "There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.\n\nYou can work on the projects following these two rules:\n\n\n\tEvery week, you will finish exactly one milestone of one project. You must work every week.\n\tYou cannot work on two milestones from the same project for two consecutive weeks.\n\n\nOnce all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.\n\nReturn the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.\n\n \nExample 1:\n\nInput: milestones = [1,2,3]\nOutput: 6\nExplanation: One possible scenario is:\n​​​​- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 2.\n- During the 3rd week, you will work on a milestone of project 1.\n- During the 4th week, you will work on a milestone of project 2.\n- During the 5th week, you will work on a milestone of project 1.\n- During the 6th week, you will work on a milestone of project 2.\nThe total number of weeks is 6.\n\n\nExample 2:\n\nInput: milestones = [5,2,1]\nOutput: 7\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 1.\n- During the 3rd week, you will work on a milestone of project 0.\n- During the 4th week, you will work on a milestone of project 1.\n- During the 5th week, you will work on a milestone of project 0.\n- During the 6th week, you will work on a milestone of project 2.\n- During the 7th week, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.\n\n\n \nConstraints:\n\n\n\tn == milestones.length\n\t1 <= n <= 105\n\t1 <= milestones[i] <= 109\n\n", "solution_py": "class Solution:\n def numberOfWeeks(self, m: List[int]) -> int:\n return min(sum(m), 2 * (sum(m) - max(m)) + 1)", "solution_js": "var numberOfWeeks = function(milestones) {\n let maxElement = 0,arraySum = 0;\n\n for(let milestone of milestones){\n arraySum += milestone;\n maxElement = Math.max(maxElement,milestone);\n }\n\n let rest = arraySum - maxElement;\n let difference = maxElement - rest;\n\n if(difference <= 1) return arraySum;\n\n return (arraySum - difference) + 1;\n};", "solution_java": "class Solution {\n public long numberOfWeeks(int[] milestones) {\n \n \tint i,j,max=-1,n=milestones.length;\n \n \tlong sum=0;\n \tfor(i=0;i1)\n \t\treturn sum-(max-x-1);\n \treturn sum;\n \t\n }\n}", "solution_c": "class Solution {\npublic:\n long long numberOfWeeks(vector& milestones) {\n long long unsigned int maxel = *max_element(milestones.begin(), milestones.end());\n long long unsigned int sum = 0;\n for (auto& m : milestones) sum += m;\n if (sum - maxel >= maxel) return sum;\n return (sum - maxel) * 2 + 1;\n }\n};" }, { "title": "Range Sum of BST", "algo_input": "Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].\n\n \nExample 1:\n\nInput: root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n\n\nExample 2:\n\nInput: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 2 * 104].\n\t1 <= Node.val <= 105\n\t1 <= low <= high <= 105\n\tAll Node.val are unique.\n\n", "solution_py": "class Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n \n res = 0\n \n def dfs(node):\n nonlocal res\n \n if not node:\n return\n \n if node.val >= low and node.val <= high:\n \n res += node.val\n \n dfs(node.left)\n dfs(node.right)\n \n dfs(root)\n \n return res", "solution_js": "var rangeSumBST = function(root, low, high) {\n let sum = 0;\n const summer = (root) => {\n if(!root) {\n return;\n }\n\n sum = root.val >= low && root.val <= high ? root.val + sum : sum;\n\n summer(root.left)\n summer(root.right)\n }\n\n summer(root);\n\n return sum;\n};", "solution_java": "class Solution {\n private int sum = 0;\n public int rangeSumBST(TreeNode root, int low, int high) {\n dfs(root, low, high);\n return sum;\n }\n \n public void dfs(TreeNode root, int low, int high){\n if(root == null) return;\n \n if(root.val < low) dfs(root.right, low, high);\n else if(root.val > high) dfs(root.left, low, high);\n \n if(root.val >= low && root.val <= high) {\n sum += root.val;\n dfs(root.left, low, high);\n dfs(root.right, low, high);\n }\n \n }\n}", "solution_c": "class Solution {\npublic:\n\n int solve(TreeNode* root, int low, int high){\n if(root == NULL)\n return 0;\n\n int sum = 0;\n if(low <= root->val && root->val <= high){\n sum = root->val;\n }\n\n return sum + solve(root->left, low, high) + solve(root->right, low, high);\n }\n\n int rangeSumBST(TreeNode* root, int low, int high) {\n\n return solve(root, low, high);\n }\n};" }, { "title": "Plus One", "algo_input": "You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.\n\nIncrement the large integer by one and return the resulting array of digits.\n\n \nExample 1:\n\nInput: digits = [1,2,3]\nOutput: [1,2,4]\nExplanation: The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].\n\n\nExample 2:\n\nInput: digits = [4,3,2,1]\nOutput: [4,3,2,2]\nExplanation: The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].\n\n\nExample 3:\n\nInput: digits = [9]\nOutput: [1,0]\nExplanation: The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].\n\n\n \nConstraints:\n\n\n\t1 <= digits.length <= 100\n\t0 <= digits[i] <= 9\n\tdigits does not contain any leading 0's.\n\n", "solution_py": "class Solution(object):\n def plusOne(self, digits):\n for i in range(len(digits)-1, -1, -1):\n if digits[i] == 9:\n digits[i] = 0\n else:\n digits[i] += 1\n return digits\n return [1] + digits", "solution_js": "var plusOne = function(digits) {\n for(let i=digits.length-1; i>=0; i--){\n if(digits[i] === 9){\n digits[i] = 0\n }else{\n digits[i] += 1\n return digits\n }\n }\n digits.unshift(1)\n return digits\n};", "solution_java": "class Solution {\n public int[] plusOne(int[] digits) {\n\n int len = digits.length;\n\n //last digit not a 9, just add 1 to it\n if(digits[len - 1] != 9){\n digits[len - 1] = digits[len - 1] + 1;\n return digits;\n }\n\n //last digit is a 9, find the closest digit that is not a 9\n else{\n int i = len - 1;\n while(i >= 0 && digits[i] == 9){\n digits[i] = 0;\n i--;\n }\n if(i == -1){\n int[] ret = new int[len + 1];\n for(int j = 0; j < len; j++){\n ret[j+1] = digits[j];\n }\n ret[0] = 1;\n return ret;\n }\n digits[i] = digits[i] + 1;\n }\n\n return digits;\n }\n}", "solution_c": "class Solution {\npublic:\n vector plusOne(vector& digits) {\n int len = digits.size(), carry = 0, temp = 0;\n \n vector arr;\n \n for(int i=len-1; i>=0; i--) { // traverse from back to front\n temp = digits[i] + carry;\n \n if(i == len-1) {\n temp++;\n }\n \n arr.push_back(temp % 10);\n carry = temp/10;\n }\n \n if(carry) {\n arr.push_back(carry);\n }\n \n reverse(arr.begin(), arr.end());\n return arr;\n }\n};" }, { "title": "Matrix Block Sum", "algo_input": "Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:\n\n\n\ti - k <= r <= i + k,\n\tj - k <= c <= j + k, and\n\t(r, c) is a valid position in the matrix.\n\n\n \nExample 1:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[12,21,16],[27,45,33],[24,39,28]]\n\n\nExample 2:\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput: [[45,45,45],[45,45,45],[45,45,45]]\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n, k <= 100\n\t1 <= mat[i][j] <= 100\n\n", "solution_py": "class Solution:\n def matrixBlockSum(self, matrix: List[List[int]], k: int) -> List[List[int]]:\n ROWS, COLS = len(matrix), len(matrix[0])\n\n prefix_sums = [[0] * (COLS + 1) for _ in range(ROWS + 1)]\n\n for r in range(1, ROWS + 1):\n for c in range(1, COLS + 1):\n prefix_sums[r][c] = prefix_sums[r - 1][c] + prefix_sums[r][c - 1] + \\\n matrix[r - 1][c - 1] - prefix_sums[r - 1][c - 1]\n\n res = [[0] * COLS for _ in range(ROWS)]\n for r in range(ROWS):\n for c in range(COLS):\n res[r][c] = prefix_sums[min(r + k + 1, ROWS)][min(c + k + 1, COLS)] - \\\n prefix_sums[max(r - k, 0)][min(c + k + 1, COLS)] - \\\n prefix_sums[min(r + k + 1, ROWS)][max(c - k, 0)] + \\\n prefix_sums[max(r - k, 0)][max(c - k, 0)]\n\n return res", "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number[][]}\n */\nvar matrixBlockSum = function(mat, k) {\n let sum = 0;\n let dp = Array(mat.length + 1);\n dp[0] = Array(mat[0].length).fill(0);\n\n // sum of row el\n for (let i = 0; i < mat.length; i++){\n dp[i + 1] = Array(mat[0].length).fill(0);\n for (let j = 0; j < mat[0].length; j++){\n dp[i + 1][j] += mat[i][j] + sum;\n sum = dp[i + 1][j];\n }\n sum = 0;\n }\n\n // sum of col el\n for (let j = 0; j < mat[0].length; j++){\n for (let i = 0; i < mat.length; i++){\n dp[i + 1][j] += sum;\n sum = dp[i + 1][j];\n }\n sum = 0;\n }\n\n dp = dp.slice(1);\n\n // cal sum of blocks\n for (let i = 0; i < mat.length; i++){\n let r1 = Math.max(0, i - k);\n let r2 = Math.min(mat.length - 1, i + k);\n for (let j = 0; j < mat[0].length; j++){\n let c1 = Math.max(0, j - k);\n let c2 = Math.min(mat[0].length - 1, j + k);\n\n let value = dp[r2][c2];\n\n if (r1 - 1 >= 0){\n value -= dp[r1 - 1][c2];\n }\n if (c1 - 1 >= 0){\n value -= dp[r2][c1 - 1]\n }\n if (r1 - 1 >= 0 && c1 - 1 >= 0){\n value += dp[r1 - 1][c1 - 1];\n }\n mat[i][j] = value;\n }\n }\n\n return mat;\n\n};", "solution_java": "class Solution {\n public int[][] matrixBlockSum(int[][] mat, int k) {\n int m = mat.length,n = mat[0].length;\n int[][] answer = new int[m][n];\n for(int i=0;i> matrixBlockSum(vector>& mat, int k) {\n int n = mat.size(), m = mat[0].size();\n vector> pref(n+1, vector(m+1, 0));\n // Calculating prefix sum\n for(int i = 1; i <= n; i++){\n for(int j = 1; j <= m; j++){\n // note that while counting for [i-1][j] and [i][j-1];\n // pref[i-1][j-1] will be added twice. So we reduce it once.\n pref[i][j] = mat[i-1][j-1] + pref[i-1][j] + pref[i][j-1] - pref[i-1][j-1];\n }\n }\n\n // Find the sum of the elements specified in the K-block\n vector> res(n, vector(m, 0));\n for(int i = 0; i < n; i++){\n for(int j = 0; j < m; j++){\n // checking for all pairs to be in bounds.\n int r1 = max(0, i-k);\n int c1 = max(0, j-k);\n int r2 = min(n-1, i+k);\n int c2 = min(m-1, j+k);\n // finding res[i][j] = bottom right - bottom left - top right + top left\n res[i][j] = pref[r2+1][c2+1] - pref[r2+1][c1] - pref[r1][c2+1] + pref[r1][c1];\n }\n }\n\n return res;\n\n }\n};" }, { "title": "Target Sum", "algo_input": "You are given an integer array nums and an integer target.\n\nYou want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.\n\n\n\tFor example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression \"+2-1\".\n\n\nReturn the number of different expressions that you can build, which evaluates to target.\n\n \nExample 1:\n\nInput: nums = [1,1,1,1,1], target = 3\nOutput: 5\nExplanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n\n\nExample 2:\n\nInput: nums = [1], target = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 20\n\t0 <= nums[i] <= 1000\n\t0 <= sum(nums[i]) <= 1000\n\t-1000 <= target <= 1000\n\n", "solution_py": "class Solution:\n def findTargetSumWays(self, nums: List[int], target: int) -> int:\n @cache\n def dfs(i, sum_):\n if i == len(nums):\n if sum_ == target: return 1\n else: return 0\n return dfs(i+1, sum_+nums[i]) + dfs(i+1, sum_-nums[i])\n if abs(target) > sum(nums): return 0\n return dfs(0, 0)", "solution_js": "var findTargetSumWays = function(nums, target) {\n const memo = new Map()\n return backtrack(0, 0)\n \n function backtrack(i, cur){\n const key = `${i} ${cur}`\n if(i == nums.length) return cur == target ? 1 : 0\n if(!memo.has(key)) memo.set(key, backtrack(i + 1, -nums[i] + cur) + backtrack(i + 1, nums[i] + cur))\n return memo.get(key)\n }\n};", "solution_java": "class Solution {\n public int findTargetSumWays(int[] nums, int target) {\n int sum = 0;\n for(int i:nums){\n sum += i;\n }\n if(target>sum || target<-sum || ((target+sum)&1)!=0) return 0;\n return subsetSum(nums,(target+sum)/2);\n }\n private int subsetSum(int[] nums,int target){\n int[][] dp = new int[nums.length+1][target+1];\n dp[0][0] = 1;\n \n for(int i=1;i& nums, int target, int idx, unordered_map &dp) {\n if(idx == nums.size()) {\n if(target == 0) {\n return 1;\n }\n return 0;\n }\n string key = to_string(idx) + \" \" + to_string(target);\n if(dp.find(key) != dp.end()) {\n return dp[key];\n }\n // +\n int x = solve(nums, target - nums[idx], idx+1, dp);\n // -\n int y = solve(nums, target + nums[idx], idx+1, dp);\n // sum\n return dp[key] = x+y;\n }\n int findTargetSumWays(vector& nums, int target) {\n unordered_map dp;\n return solve(nums, target, 0, dp);\n }\n};" }, { "title": "Minimum Cost Tree From Leaf Values", "algo_input": "Given an array arr of positive integers, consider all binary trees such that:\n\n\n\tEach node has either 0 or 2 children;\n\tThe values of arr correspond to the values of each leaf in an in-order traversal of the tree.\n\tThe value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.\n\n\nAmong all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.\n\nA node is a leaf if and only if it has zero children.\n\n \nExample 1:\n\nInput: arr = [6,2,4]\nOutput: 32\nExplanation: There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.\n\n\nExample 2:\n\nInput: arr = [4,11]\nOutput: 44\n\n\n \nConstraints:\n\n\n\t2 <= arr.length <= 40\n\t1 <= arr[i] <= 15\n\tIt is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 231).\n\n", "solution_py": "class Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n n = len(arr)\n d = {}\n def findMax(start,end):\n if (start,end) in d: return d[(start,end)]\n maxx = start\n for i in range(start+1,end+1):\n if arr[maxx] < arr[i] : maxx = i\n d[(start,end)] = arr[maxx]\n return arr[maxx]\n\n dp = [[float('inf') for i in range(n)] for j in range(n)]\n for gap in range(n):\n for row in range(n - gap):\n col = row + gap\n if gap == 0:\n dp[row][col] = 0\n elif gap == 1:\n dp[row][col] = arr[row] * arr[col]\n else:\n for k in range(row,col):\n val = dp[row][k] + findMax(row,k) * findMax(k+1,col) + dp[k+1][col]\n if val < dp[row][col]: dp[row][col] = val\n\n return dp[0][-1]", "solution_js": "var mctFromLeafValues = function(arr) {\n const dp = [];\n\n for (let i = 0; i < arr.length; i++) {\n dp[i] = [];\n }\n\n return treeBuilder(0, arr.length - 1);\n\n function treeBuilder(start, end) {\n\n if (start == end) {\n return 0;\n }\n\n if (dp[start][end]) {\n return dp[start][end];\n }\n\n let min = Number.MAX_VALUE;\n\n for (let i = start; i < end; i++) {\n const left = treeBuilder(start, i);\n const right = treeBuilder(i + 1, end);\n\n const maxLeft = Math.max(...arr.slice(start, i + 1));\n const maxRight = Math.max(...arr.slice(i + 1, end + 1));\n\n const rootVal = maxLeft * maxRight;\n\n min = Math.min(min, rootVal + left + right);\n\n }\n\n dp[start][end] = min;\n return min;\n }\n};", "solution_java": "class Solution {\n public int mctFromLeafValues(int[] arr) {\n \n int sum = 0;\n Stack stack = new Stack<>();\n for (int num: arr) {\n sum += cleanUpStack(num, stack);\n }\n sum += cleanUpStack(17, stack);\n \n return sum;\n }\n \n private int cleanUpStack(int target, Stack stack) {\n int last = 0;\n int sum = 0;\n while (!stack.isEmpty() && stack.peek() <= target) {\n int cur = stack.pop();\n sum += last * cur;\n last = cur;\n }\n if (target != 17) {\n sum += target * last;\n stack.push(target);\n }\n return sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[40][40]={0};\n int solve(vector arr,int start,int end)\n {\n if(start==end)\n return 0;\n if(dp[start][end]!=0)\n return dp[start][end];\n int mn=INT_MAX;\n for(int i=start;i<=end-1;i++)\n {\n int left=solve(arr,start,i);\n int right=solve(arr,i+1,end);\n int temp=left+right+*max_element(arr.begin()+start,arr.begin()+i+1) * *max_element(arr.begin()+i+1,arr.begin()+end+1);\n mn=min(mn,temp);\n \n }\n return dp[start][end]=mn;\n }\n int mctFromLeafValues(vector& arr)\n {\n return solve(arr,0,arr.size()-1);\n }\n};\n//if you like the solution plz upvote." }, { "title": "Longer Contiguous Segments of Ones than Zeros", "algo_input": "Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.\n\n\n\tFor example, in s = \"110100010\" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.\n\n\nNote that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.\n\n \nExample 1:\n\nInput: s = \"1101\"\nOutput: true\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.\n\n\nExample 2:\n\nInput: s = \"111000\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.\n\n\nExample 3:\n\nInput: s = \"110100010\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\n def checkZeroOnes(self, s: str) -> bool:\n s1 = s.split('0')\n s0 = s.split('1')\n r1 = max([len(i) for i in s1])\n r0 = max([len(i) for i in s0])\n return r1>r0", "solution_js": "var checkZeroOnes = function(s) {\n let longest1 = 0;\n let longest0 = 0;\n\n let count1 = 0;\n let count0 = 0;\n\n for (let i = 0; i < s.length; i++) {\n const bit = s.charAt(i);\n\n if (bit === \"1\") count1++;\n else count1 = 0;\n\n if (bit === \"0\") count0++;\n else count0 = 0;\n\n longest1 = Math.max(longest1, count1);\n longest0 = Math.max(longest0, count0);\n }\n\n return longest1 > longest0;\n};", "solution_java": "class Solution {\n public boolean checkZeroOnes(String s) {\n int length1 = 0;\n int length0 = 0;\n\n int i = 0;\n while(i < s.length()){\n int temp = 0;\n while(i < s.length() && s.charAt(i) == '1'){ //counting 1s\n temp++;\n i++;\n }\n length1 = Math.max(temp,length1);\n temp = 0;\n while(i < s.length() && s.charAt(i) == '0'){ // counting 0s\n temp++;\n i++;\n }\n length0 = Math.max(temp,length0);\n }\n return length1 > length0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkZeroOnes(string s) {\n int count1=0;\n int count2=0;\n int max1=0;int max2=0;\n for(int i=0;imax2)\n return true;\n return false;\n \n \n }\n};" }, { "title": "Tweet Counts Per Frequency", "algo_input": "A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).\n\nFor example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:\n\n\n\tEvery minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]\n\tEvery hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]\n\tEvery day (86400-second chunks): [10,10000]\n\n\nNotice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).\n\nDesign and implement an API to help the company with their analysis.\n\nImplement the TweetCounts class:\n\n\n\tTweetCounts() Initializes the TweetCounts object.\n\tvoid recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).\n\tList<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.\n\t\n\t\tfreq is one of \"minute\", \"hour\", or \"day\" representing a frequency of every minute, hour, or day respectively.\n\t\n\t\n\n\n \nExample:\n\nInput\n[\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n[[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]\n\nOutput\n[null,null,null,null,[2],[2,1],null,[4]]\n\nExplanation\nTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\ntweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\ntweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\ntweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets\n\n\n \nConstraints:\n\n\n\t0 <= time, startTime, endTime <= 109\n\t0 <= endTime - startTime <= 104\n\tThere will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency.\n\n", "solution_py": "import bisect\nclass TweetCounts:\n\n def __init__(self):\n self.tweets = {}\n \n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if not tweetName in self.tweets:\n self.tweets[tweetName] = []\n index = bisect.bisect_left(self.tweets[tweetName], time)\n self.tweets[tweetName].insert(index, time)\n \n \n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n \n def find(step):\n nonlocal tweet\n result = []\n for i in range(startTime, endTime+1, step):\n result.append(bisect.bisect_right(tweet, min(endTime, i + step - 1)) - bisect.bisect_left(tweet, i))\n return result\n \n \n tweet = self.tweets[tweetName]\n if freq == \"minute\":\n return find(60)\n elif freq == \"hour\":\n return find(3600)\n else:\n return find(86400)", "solution_js": "var TweetCounts = function() {\n this.map = new Map();\n};\n\nTweetCounts.prototype.recordTweet = function(tweetName, time) {\n if (!this.map.has(tweetName)) this.map.set(tweetName, []);\n this.map.get(tweetName).push(time);\n};\n\nTweetCounts.prototype.getTweetCountsPerFrequency = function(freq, tweetName, startTime, endTime) {\n if (!this.map.has(tweetName)) return [];\n\n const tweets = this.map.get(tweetName);\n const buckets = createBuckets(freq, startTime, endTime);\n\n for (let i = 0; i < tweets.length; i++) {\n const tweetTime = tweets[i];\n\n let left = 0;\n let right = buckets.length - 1;\n\n while (left <= right) {\n const mid = (left + right) >> 1;\n const [startTime, endTime, count] = buckets[mid];\n\n if (startTime <= tweetTime && tweetTime <= endTime) {\n buckets[mid][2] = count + 1;\n break;\n }\n\n if (endTime < tweetTime) left = mid + 1;\n else right = mid - 1;\n }\n }\n\n const res = [];\n\n for (let i = 0; i < buckets.length; i++) {\n res.push(buckets[i][2]);\n }\n\n return res;\n\n function createBuckets(freq, startTime, endTime) {\n const chunks = { \"minute\": 60, \"hour\": 3600, \"day\": 86400 };\n const buckets = [];\n\n let start = startTime;\n\n while (start <= endTime) {\n const end = Math.min(start + chunks[freq] - 1, endTime);\n buckets.push([start, end, 0])\n start = end + 1;\n }\n\n return buckets;\n }\n};", "solution_java": "class TweetCounts {\n Map> map;\n public TweetCounts() {\n map = new HashMap<>();\n }\n\n public void recordTweet(String tweetName, int time) {\n map.computeIfAbsent(tweetName, v->new ArrayList<>()).add(time);\n }\n\n public List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) {\n List res = new ArrayList<>();\n if(map.containsKey(tweetName)) {\n Collections.sort(map.get(tweetName));\n while(startTime<=endTime) {\n int interval = Freq.valueOf(freq).getVal();\n int end = Math.min(startTime+interval-1, endTime); // need this to handle the last interval\n res.add(getFreq(map.get(tweetName), startTime, end));\n startTime=end+1; // ex: for minute, the interval is 60 so our end is 59. The next startTime is end+1\n }\n }\n return res;\n }\n\n public int getFreq(List list, int start, int end) {\n int st = Collections.binarySearch(list, start);\n if(st<0) {\n st = (st+1)*-1; // our exact start time might not be in the list, to get the 1st timestamp greater than start\n }\n int en = Collections.binarySearch(list, end);\n if(en<0) {\n en = (en+2)*-1; // our exact end time might not be in the list, to get the last timestamp just smaller than end\n }\n\n return en-st+1; // the freq count\n }\n}\n\n enum Freq {\n minute(60), hour(3600), day(86400);\n Map map = new HashMap<>();\n Freq(int val) {\n map.put(this, val);\n }\n\n public int getVal() {\n return map.get(this);\n }\n\n}\n\n/**\n * Your TweetCounts object will be instantiated and called as such:\n * TweetCounts obj = new TweetCounts();\n * obj.recordTweet(tweetName,time);\n * List param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime);\n */", "solution_c": "#include \n#include \n\nusing namespace std;\nusing namespace __gnu_pbds;\n\n//less_equal to use it as a multiset\ntypedef tree, rb_tree_tag, tree_order_statistics_node_update> pbds;\n\nclass TweetCounts {\npublic:\n unordered_map tweet;\n TweetCounts() {\n tweet.clear();\n }\n \n void recordTweet(string tweetName, int time) {\n tweet[tweetName].insert(time);\n }\n \n vector getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) {\n int interval;\n if(freq == \"minute\") interval = 60;\n else if(freq == \"hour\") interval = 3600;\n else interval = 86400;\n \n vector ans;\n\t\t\n for(int i=startTime; i<=endTime; i+=interval)\n {\n int start = i, end = min(endTime, i+interval-1);\n \n //[start - end] or [start - end+1)\n auto low = tweet[tweetName].order_of_key(start);\n auto high = tweet[tweetName].order_of_key(end+1);\n \n ans.push_back(high-low);\n }\n return ans;\n }\n};" }, { "title": "Stone Game IV", "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nInitially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\n\nAlso, if a player cannot make a move, he/she loses the game.\n\nGiven a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.\n\n \nExample 1:\n\nInput: n = 1\nOutput: true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n\nExample 2:\n\nInput: n = 2\nOutput: false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n\n\nExample 3:\n\nInput: n = 4\nOutput: true\nExplanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\n", "solution_py": "class Solution:\n def winnerSquareGame(self, n: int) -> bool:\n squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n \n @cache\n def can_win(n: int) -> bool:\n return n and not all(can_win(n - s) for s in squares(n))\n \n return can_win(n)", "solution_js": "var winnerSquareGame = function(n) {\n \n const map = new Map();\n map.set(0, false);\n map.set(1, true);\n \n const dfs = (num) => {\n if( map.has(num) ) return map.get(num);\n let sqRoot = Math.floor(Math.sqrt(num));\n \n for(let g=1; g<=sqRoot; g++){\n if( !dfs(num - (g*g)) ) {\n map.set(num, true);\n return true;\n } \n }\n map.set(num, false);\n return false;\n }\n \n return dfs(n)\n};", "solution_java": "class Solution {\n // idea: Alice wins a game with n stones if and only if there exists\n // some perfect square p <= n such that Alice wins a game with\n // n - p stones... i.e., Bob DOES NOT win a game with n - p stones\n public boolean winnerSquareGame(int n) {\n // this bit would be better with just an array of booleans, but this\n // is how i thought of it at the time, so leaving it this way...\n // maybe it will be \"more explicit\" and help someone better understand dp?\n HashMap memo = new HashMap<>();\n memo.put(1, true); // if there is one stone in the pile to begin the game, the next player to go wins\n memo.put(0, false); // if there are zero stones in the pile to begin the game, the next player to go loses\n List perfectSquares = new ArrayList<>();\n int i = 1;\n while (i * i <= n) {\n perfectSquares.add(i * i);\n i++;\n }\n // if there are some perfect square number of stones in the pile to begin the game, the next player to go wins\n perfectSquares.forEach(p -> memo.put(p, true));\n // Alice goes first...\n return this.playerWins(n, perfectSquares, memo);\n }\n\n private boolean playerWins(int n, List P, HashMap m) {\n if (m.containsKey(n)) { return m.get(n); } // if we already computed the answer for n, just return it\n m.put(n, false); // otherwise, assume it's false to begin...\n for (Integer p : P) { // check every perfect square p...\n if (p <= n && !playerWins(n - p, P, m)) {\n // if p <= n AND the player who goes next (e.g., Bob) does not win a game that begins with\n // n - p stones, then we know that the player whose turn it is right now (e.g., Alice) wins\n // a game that begins with n stones, so record this discovery in the memo and then break out\n // of the loop because there's no more work to do...\n m.put(n, true);\n break;\n } // else p >= n OR taking p stones would not result in a win for the player whose turn it is right now...\n }\n // we put false in before the loop; if we never found a reason to change it to true,\n // then false is the correct result...\n return m.get(n);\n }\n\n}", "solution_c": "class Solution {\npublic:\n bool winnerSquareGame(int n) {\n\n vector dp(n+1,false);\n\n for(int i=1;i<=n;i++){\n for(int j=sqrt(i);j>=1;j--){\n if(dp[i-j*j] == false){\n dp[i] = true;\n break;\n }\n }\n }\n\n return dp[n];\n }\n};" }, { "title": "Minimum Moves to Reach Target with Rotations", "algo_input": "In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).\n\nIn one move the snake can:\n\n\n\tMove one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n\tMove down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n\tRotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).\n\t\n\tRotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).\n\t\n\n\nReturn the minimum number of moves to reach the target.\n\nIf there is no way to reach the target, return -1.\n\n \nExample 1:\n\n\n\nInput: grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n  [0,0,0,0,1,1],\n  [0,0,1,0,1,0],\n  [0,1,1,0,0,0],\n  [0,1,1,0,0,0]]\nOutput: 11\nExplanation:\nOne possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n\n\nExample 2:\n\nInput: grid = [[0,0,1,1,1,1],\n  [0,0,0,0,1,1],\n  [1,1,0,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,1],\n  [1,1,1,0,0,0]]\nOutput: 9\n\n\n \nConstraints:\n\n\n\t2 <= n <= 100\n\t0 <= grid[i][j] <= 1\n\tIt is guaranteed that the snake starts at empty cells.\n\n", "solution_py": "class Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n queue , vis , n = [(0,1,0,0)] , {} , len(grid)\n while queue:\n x,y,pos,moves = queue.pop(0)\n if x == y == n-1 and pos == 0: return moves\n if pos == 0:\n if y + 1 < n and grid[x][y+1] == 0 and (x,y+1,0) not in vis:\n vis[(x,y+1,0)] = True\n queue.append((x,y+1,0,moves+1))\n \n if x + 1 < n and grid[x+1][y-1] == 0 and grid[x+1][y] == 0:\n if (x+1,y-1,1) not in vis:\n vis[(x+1,y-1,1)] = True\n queue.append((x+1,y-1,1,moves+1))\n if (x+1,y,0) not in vis:\n vis[(x+1,y,0)] = True\n queue.append((x+1,y,0,moves+1))\n else:\n if x + 1 < n and grid[x+1][y] == 0 and (x+1,y,1) not in vis:\n vis[(x+1,y,1)] = True\n queue.append((x+1,y,1,moves+1))\n if y + 1 < n and grid[x-1][y+1] == grid[x][y+1] == 0:\n if (x-1,y+1,0) not in vis:\n vis[(x-1,y+1,0)] = True\n queue.append((x-1,y+1,0,moves+1))\n if (x,y+1,1) not in vis:\n vis[(x,y+1,1)] = True\n queue.append((x,y+1,1,moves+1))\n return -1", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumMoves = function(grid) {\n const len = grid.length;\n const initPosition = [0, true, 1]\n const visited = new Set([initPosition.join()]);\n\n const queue = new Queue();\n initPosition.push(0);\n queue.enqueue(initPosition)\n while (!queue.isEmpty()) {\n let [row, isHorizontal, col, numMoves] = queue.dequeue();\n if (row + col === len * 2 - 2 && isHorizontal) return numMoves;\n numMoves++;\n const positions = [];\n if (isHorizontal) {\n if (grid[row][col + 1] === 0) {\n positions.push([row, true, col + 1])\n }\n if (row + 1 < len && grid[row + 1][col - 1] === 0 && grid[row + 1][col] === 0) {\n positions.push([row + 1, true, col])\n positions.push([row + 1, false, col - 1]);\n }\n } else {\n if (row + 1 < len && grid[row + 1][col] === 0) {\n positions.push([row + 1, false, col]);\n }\n if (row > 0 && grid[row - 1][col + 1] === 0 && grid[row][col + 1] === 0) {\n positions.push([row, false, col + 1]);\n positions.push([row - 1, true, col + 1]);\n }\n }\n for (let position of positions) {\n const str = position.join();\n if (visited.has(str)) continue;\n visited.add(str);\n position.push(numMoves);\n queue.enqueue(position);\n }\n }\n return -1;\n};\n\nclass Queue {\n constructor() {\n this.head = { next: null };\n this.tail = this.head;\n }\n\n isEmpty() {\n return this.head.next === null;\n }\n\n dequeue() {\n const { value } = this.head.next;\n this.head = this.head.next;\n return value;\n }\n\n enqueue(value) {\n this.tail.next = { value, next: null };\n this.tail = this.tail.next;\n }\n}", "solution_java": "class Solution {\n public int minimumMoves(int[][] grid) {\n \n int n = grid.length; \n //boolean[][][][] visited = new boolean[n][n][n][n];\n Set set = new HashSet<>();\n \n Queue q = new LinkedList<>();\n q.offer(new Position(0,0,0,1)); \n int count = 0;\n \n if(grid[n-1][n-2] == 1 || grid[n-1][n-1] == 1)\n return -1;\n \n while(!q.isEmpty()){\n ++count;\n Queue nextq = new LinkedList<>();\n while(!q.isEmpty()){\n \n Position p = q.poll();\n\n int r1 = p.getr1();\n int r2 = p.getr2();\n int c1 = p.getc1();\n int c2 = p.getc2();\n \n if(r1 == n-1 && r2 == n-1 && c1 == n-2 && c2==n-1)\n return count-1;\n \n if(set.contains(p))\n continue;\n \n if(c1+1 < n && grid[r1] [c1+1] != 1 && c2+1 < n && grid[r2] [c2+1] != 1)\n nextq.offer(new Position(r1, c1+1, r2, c2+1));\n if(r1+1 < n && grid[r1+1] [c1] != 1 && r2+1 < n && grid[r2+1] [c2] != 1)\n nextq.offer(new Position(r1+1, c1, r2+1, c2));\n \n if(r1 == r2 && r1+1 < n && r2+1 < n && grid[r1+1][c1] == 0 && grid[r2+1][c2] == 0 && grid[r1+1][c1] == 0)\n nextq.offer(new Position(r1,c1, r1+1, c1));\n \n if(c1 == c2 && c1+1 < n && c2+1 < n && grid[r1][c1+1] == 0 && grid[r2][c1+1] == 0 && grid[r1][c1+1] == 0)\n nextq.offer(new Position(r1,c1, r1, c1+1));\n set.add(p);\n }\n q = nextq;\n }\n return -1;\n }\n \n private class Position{\n int r1;\n int c1;\n int r2;\n int c2;\n \n public Position(int r1, int c1, int r2, int c2){\n this.r1 = r1;\n this.r2 = r2;\n this.c1 =c1;\n this.c2 = c2;\n }\n \n public int getr1(){\n return this.r1;\n }\n public int getr2(){\n return this.r2;\n }\n public int getc1(){\n return this.c1;\n }\n public int getc2(){\n return this.c2;\n }\n \n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * r1 + c1 + prime *r2 + c2;\n return result;\n }\n \n @Override\n public boolean equals(Object obj) {\n Position p = (Position) obj;\n if(this.r1 == p.getr1() && this.r2 ==p.getr2() && this.c1 == p.getc1() && this.c2==p.getc2())\n return true;\n else\n return false;\n }\n } \n}", "solution_c": "class Solution {\n\npublic:\n\nint n;\nset> visited;\nbool candown(vector>& grid,int x,int y,bool hor){\n if(!hor){\n if(x+2>& grid,int x,int y,bool hor){\n if(hor){\n if(y+2>& grid,int x,int y,bool hor){\n if(hor){\n if(y+1>& grid) {\n queue> q;\n q.push({0,0,true});\n int ans=0;\n n=grid.size();\n while(!q.empty()){\n int size=q.size();\n while(size--){\n auto a=q.front();\n q.pop();\n if(visited.count({a[0],a[1],a[2]})){\n continue;\n }\n visited.insert({a[0],a[1],a[2]});\n int x=a[0];\n int y=a[1];\n if(x==n-1 && y==n-2 && a[2]==1){\n return ans;\n }\n if(candown(grid,x,y,a[2])){\n q.push({x+1,y,a[2]});\n }\n if(canrot(grid,x,y,a[2])){\n q.push({x,y,!a[2]});\n }\n if(canright(grid,x,y,a[2])){\n q.push({x,y+1,a[2]});\n }\n }\n ans++;\n }\n return -1;\n}\n};" }, { "title": "Merge Sorted Array", "algo_input": "You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.\n\nMerge nums1 and nums2 into a single array sorted in non-decreasing order.\n\nThe final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.\n\n \nExample 1:\n\nInput: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput: [1,2,2,3,5,6]\nExplanation: The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.\n\n\nExample 2:\n\nInput: nums1 = [1], m = 1, nums2 = [], n = 0\nOutput: [1]\nExplanation: The arrays we are merging are [1] and [].\nThe result of the merge is [1].\n\n\nExample 3:\n\nInput: nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput: [1]\nExplanation: The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.\n\n\n \nConstraints:\n\n\n\tnums1.length == m + n\n\tnums2.length == n\n\t0 <= m, n <= 200\n\t1 <= m + n <= 200\n\t-109 <= nums1[i], nums2[j] <= 109\n\n\n \nFollow up: Can you come up with an algorithm that runs in O(m + n) time?\n", "solution_py": "class Solution(object):\n def merge(self, nums1, m, nums2, n):\n # Initialize nums1's index\n i = m - 1\n # Initialize nums2's index\n j = n - 1\n # Initialize a variable k to store the last index of the 1st array...\n k = m + n - 1\n while j >= 0:\n if i >= 0 and nums1[i] > nums2[j]:\n nums1[k] = nums1[i]\n k -= 1\n i -= 1\n else:\n nums1[k] = nums2[j]\n k -= 1\n j -= 1", "solution_js": "var merge = function(nums1, m, nums2, n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n let i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n let k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n};", "solution_java": "class Solution {\n public void merge(int[] nums1, int m, int[] nums2, int n) {\n // Initialize i and j to store indices of the last element of 1st and 2nd array respectively...\n int i = m - 1 , j = n - 1;\n // Initialize a variable k to store the last index of the 1st array...\n int k = m + n - 1;\n // Create a loop until either of i or j becomes zero...\n while(i >= 0 && j >= 0) {\n if(nums1[i] >= nums2[j]) {\n nums1[k] = nums1[i];\n i--;\n } else {\n nums1[k] = nums2[j];\n j--;\n }\n k--;\n // Either of i or j is not zero, which means some elements are yet to be merged.\n // Being already in a sorted manner, append them to the 1st array in the front.\n }\n // While i does not become zero...\n while(i >= 0)\n nums1[k--] = nums1[i--];\n // While j does not become zero...\n while(j >= 0)\n nums1[k--] = nums2[j--];\n // Now 1st array has all the elements in the required sorted order...\n return;\n }\n}", "solution_c": "class Solution {\npublic:\n void merge(vector& nums1, int m, vector& nums2, int n) {\n vector temp(n+m);\n int i=0,j=0,k=0;\n while(i s[i] == 1 ? '0' : '1').join('');\n};", "solution_java": "class Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder ans= new StringBuilder(); \n for(int i=0; i& nums) {\n unordered_set s;\n for (auto num : nums) s.insert(stoi(num, 0, 2));\n int res = 0;\n while (++res) {\n if (!s.count(res)) return bitset<16>(res).to_string().substr(16-nums.size());\n }\n return \"\";\n }\n};" }, { "title": "Remove Zero Sum Consecutive Nodes from Linked List", "algo_input": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\n\nAfter doing so, return the head of the final linked list.  You may return any such answer.\n\n \n(Note that in the examples below, all sequences are serializations of ListNode objects.)\n\nExample 1:\n\nInput: head = [1,2,-3,3,1]\nOutput: [3,1]\nNote: The answer [1,2,1] would also be accepted.\n\n\nExample 2:\n\nInput: head = [1,2,3,-3,4]\nOutput: [1,2,4]\n\n\nExample 3:\n\nInput: head = [1,2,3,-3,-2]\nOutput: [1]\n\n\n \nConstraints:\n\n\n\tThe given linked list will contain between 1 and 1000 nodes.\n\tEach node in the linked list has -1000 <= node.val <= 1000.\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n root = ListNode(0,head)\n summ , d , node = 0 , {} , root\n while node:\n summ += node.val\n if summ in d:\n prev = d[summ]\n tmp = prev.next\n tmp_sum = summ\n while tmp != node:\n tmp_sum += tmp.val\n if tmp_sum in d and d[tmp_sum] == tmp :d.pop(tmp_sum)\n tmp = tmp.next\n prev.next = node.next\n node = prev\n else:\n d[summ] = node\n node = node.next\n\n return root.next", "solution_js": "var removeZeroSumSublists = function(head) {\n const dummyHead = new ListNode();\n dummyHead.next = head;\n let prev = dummyHead;\n let start = head;\n \n while (start != null) {\n let sum = 0;\n let tail = start;\n \n while (tail != null) {\n sum += tail.val;\n if (sum === 0) break;\n tail = tail.next;\n }\n \n if (tail) {\n prev.next = tail.next;\n start = tail.next;\n }\n else {\n prev = start;\n start = start.next;\n }\n }\n \n \n return dummyHead.next;\n};", "solution_java": "class Solution {\n public ListNode removeZeroSumSublists(ListNode head) {\n \n ListNode dummy = new ListNode(0);\n dummy.next = head;\n \n int prefix = 0;\n ListNode curr = dummy;\n Map seen = new HashMap<>();\n seen.put(prefix, dummy);\n \n while (curr != null) {\n prefix += curr.val;\n seen.put(prefix, curr);\n curr = curr.next;\n }\n \n prefix = 0;\n curr = dummy;\n while (curr != null) {\n prefix += curr.val;\n curr.next = seen.get(prefix).next;\n curr = curr.next;\n }\n \n return dummy.next;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* removeZeroSumSublists(ListNode* head) {\n unordered_map m; // {prefix -> node}\n ListNode* dummy = new ListNode(0);\n ListNode* cur = dummy;\n dummy->next = head;\n int prefix = 0;\n while(cur){\n prefix += cur->val;\n if(m[prefix] != NULL){\n ListNode *t = m[prefix]->next;\n int sum = prefix;\n sum+=t->val;\n while(sum != prefix){\n m.erase(sum);\n t = t->next;\n sum+= t->val;\n }\n m[prefix]->next = cur->next;\n }\n else m[prefix] = cur;\n cur = cur->next;\n }\n return dummy->next;\n }\n};" }, { "title": "Break a Palindrome", "algo_input": "Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.\n\nReturn the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.\n\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.\n\n \nExample 1:\n\nInput: palindrome = \"abccba\"\nOutput: \"aaccba\"\nExplanation: There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.\n\n\nExample 2:\n\nInput: palindrome = \"a\"\nOutput: \"\"\nExplanation: There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n\n\n \nConstraints:\n\n\n\t1 <= palindrome.length <= 1000\n\tpalindrome consists of only lowercase English letters.\n\n", "solution_py": "class Solution(object):\n def breakPalindrome(self, palindrome):\n \"\"\"\n :type palindrome: str\n :rtype: str\n \"\"\"\n s = palindrome\n palindrome = [ch for ch in s]\n if len(palindrome) == 1:\n return \"\"\n \n for i in range(len(palindrome)//2):\n if palindrome[i] != 'a':\n palindrome[i] = 'a'\n return \"\".join(palindrome)\n palindrome[-1] = 'b'\n return \"\".join(palindrome)\n \n \n \n ", "solution_js": "var breakPalindrome = function(palindrome) {\n // domain n / 2 k pehlay\n palindrome = palindrome.split('');\n const len = palindrome.length;\n if(len == 1) return \"\";\n const domain = Math.floor(len / 2);\n let firstNonAChar = -1, lastAChar = -1;\n for(let i = 0; i < domain; i++) {\n if(palindrome[i] != 'a') {\n firstNonAChar = i;\n break;\n }\n }\n if(firstNonAChar == -1) {\n palindrome[len - 1] = 'b';\n } else palindrome[firstNonAChar] = 'a';\n return palindrome.join('');\n};", "solution_java": "class Solution {\n public String breakPalindrome(String palindrome) {\n \n int left = 0;\n int right = palindrome.length()-1;\n \n if(palindrome.length()==1)\n return \"\";\n \n while(left int:\n count = Counter(nums)\n m = max(nums)\n memo = {}\n def choose(num):\n if num > m:\n return 0\n if num not in count:\n count[num] = 0\n if num in memo:\n return memo[num]\n memo[num] = max(choose(num + 1), num * count[num] + choose(num + 2))\n return memo[num]\n \n return choose(1)\n\n# time and space complexity\n# n = max(nums)\n# time: O(n)\n# space: O(n)\n \n ", "solution_js": "var deleteAndEarn = function(nums) {\n let maxNumber = 0;\n \n const cache = {};\n const points = {};\n\n function maxPoints(num) {\n if (num === 0) {\n return 0;\n }\n \n if (num === 1) {\n return points[1] || 0;\n }\n \n if (cache[num] !== undefined) {\n return cache[num];\n }\n \n const gain = points[num] || 0;\n return cache[num] = Math.max(maxPoints(num - 1), maxPoints(num - 2) + gain);\n }\n \n for (let num of nums) {\n points[num] = (points[num] || 0) + num;\n maxNumber = Math.max(maxNumber, num);\n }\n\n return maxPoints(maxNumber);\n};", "solution_java": "class Solution {\n public int deleteAndEarn(int[] nums) {\n Arrays.sort(nums);\n int onePreviousAgo = 0;\n int previous = 0;\n for(int i = 0; i < nums.length; i++) {\n int sum = 0;\n // On hop there's no constraint to add the previous value\n if(i > 0 && nums[i-1] < nums[i] - 1) {\n onePreviousAgo = previous;\n }\n // Accumulate equal values\n while(i < nums.length - 1 && nums[i] == nums[i+1]) {\n sum += nums[i];\n i++;\n }\n int currentPrevious = previous;\n previous = Math.max(\n onePreviousAgo + nums[i] + sum,\n previous\n );\n onePreviousAgo = currentPrevious;\n // System.out.println(nums[i] + \":\" + previous);\n }\n return previous;\n }\n}", "solution_c": "class Solution {\npublic:\n // Dynamic Programming : Bottom Up Approach Optmised\n int deleteAndEarn(vector& nums)\n {\n int size = nums.size();\n\n // Initialise vectors with size 10001 and value 0\n vector memo(10001 , 0);\n vector res(10001 , 0);\n\n // get the count of elements int res vector\n for(auto num : nums)\n res[num]++;\n\n // for index : less than 3 calculate memo[i] as the index times number of occurences\n // : greater than equal to 3 as calculate memo[i] as the index times number of occurences + max of the last second and third element\n for(int i = 0 ; i < 10001 ; i++)\n memo[i] += (i < 3) ? (i * res[i]) : (i * res[i]) + max(memo[i-2] , memo[i-3]);\n\n // return max of last 2 elements\n return max(memo[10000] , memo[9999]);\n }\n};" }, { "title": "Count All Valid Pickup and Delivery Options", "algo_input": "Given n orders, each order consist in pickup and delivery services. \n\nCount all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). \n\nSince the answer may be too large, return it modulo 10^9 + 7.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 1\nExplanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 6\nExplanation: All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n\n\nExample 3:\n\nInput: n = 3\nOutput: 90\n\n\n \nConstraints:\n\n\n\t1 <= n <= 500\n\n", "solution_py": "class Solution:\n def countOrders(self, n: int) -> int:\n total = 1\n mod = 10 ** 9 + 7\n for k in reversed(range(2, n + 1)):\n total = total * ((2 * k - 1) * (2 * k - 2) // 2 + 2 * k - 1)\n total = total % mod\n return total", "solution_js": "var countOrders = function(n) {\n let ans = 1; //for n=1, there will only be one valid pickup and delivery\n for(let i = 2; i<=n; i++){\n let validSlots = 2 * i -1; //calculating number of valid slots of new pickup in (n-1)th order\n validSlots = (validSlots * (validSlots+1))/2; \n ans = (ans * validSlots)%1000000007; //multiplying the ans of (n-1)th order to current order's valid slots\n }\n return ans;\n};", "solution_java": "class Solution {\n public int countOrders(int n) {\n long res = 1;\n long mod = 1000000007;\n for (int i = 1; i <= n; i++) {\n res = res * (2 * i - 1) * i % mod;\n }\n return (int)res;\n }\n}", "solution_c": "class Solution {\npublic:\n int countOrders(int n) {\n int mod = 1e9+7;\n long long ans = 1;\n for(int i=1;i<=n;i++){\n int m = 2*i-1;\n int p = (m*(m+1))/2;\n ans=(ans*p)%mod;\n }\n return ans;\n }\n};" }, { "title": "Split a String Into the Max Number of Unique Substrings", "algo_input": "Given a string s, return the maximum number of unique substrings that the given string can be split into.\n\nYou can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"ababccc\"\nOutput: 5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: 2\nExplanation: One way to split maximally is ['a', 'ba'].\n\n\nExample 3:\n\nInput: s = \"aa\"\nOutput: 1\nExplanation: It is impossible to split the string any further.\n\n\n \nConstraints:\n\n\n\t\n\t1 <= s.length <= 16\n\t\n\t\n\ts contains only lower case English letters.\n\t\n\n", "solution_py": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ans, n = 0, len(s)\n def dfs(i, cnt, visited):\n nonlocal ans, n\n if i == n: ans = max(ans, cnt); return # stop condition\n for j in range(i+1, n+1): \n if s[i:j] in visited: continue # avoid re-visit/duplicates\n visited.add(s[i:j]) # update visited set\n dfs(j, cnt+1, visited) # backtracking\n visited.remove(s[i:j]) # recover visited set for next possibility\n dfs(0, 0, set()) # function call\n return ans", "solution_js": "var maxUniqueSplit = function(s) {\n let wordSet = new Set(), res = 1;\n \n function checkUniqueSubstring(i) {\n if (i === s.length) {\n res = Math.max(wordSet.size, res);\n return;\n }\n \n for (let j = i+1; j <= s.length; j++) {\n let str = s.substring(i,j);\n if (!wordSet.has(str)) {\n wordSet.add(str);\n checkUniqueSubstring(j);\n wordSet.delete(str);\n }\n }\n }\n \n checkUniqueSubstring(0);\n \n return res;\n};", "solution_java": "class Solution {\n int max = 0;\n public int maxUniqueSplit(String s) {\n int n = s.length();\n backtrack(s, 0, new HashSet());\n return max;\n }\n public void backtrack(String s, int start, Set h) {\n if(start == s.length()) {\n max = Math.max(max, h.size());\n }\n String res = \"\";\n \n for(int i = start;i < s.length();i++) {\n res += s.charAt(i);\n if(h.contains(res)) continue;\n h.add(res);\n backtrack(s, i+1, h);\n h.remove(res);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n unordered_setst;\n int ans=0;\n void dfs(string &s, int idx)\n {\n if(st.size()>ans) ans=st.size();\n if(idx>=s.length()) return;\n string str=\"\";\n for(int i=idx ; i val) root.left = insertIntoBST(root.left, val);\n \n else root.right = insertIntoBST(root.right, val);\n \n return root;\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* insertIntoBST(TreeNode* root, int val) {\n if(root==NULL) return new TreeNode(val);\n TreeNode* node = root;\n while(true){\n if(val>=node->val){\n if(node->right) node = node->right;\n else{\n node->right = new TreeNode(val);\n break;\n }\n }\n else{\n if(node->left) node = node->left;\n else{\n node->left = new TreeNode(val);\n break;\n }\n }\n }\n return root;\n }\n};" }, { "title": "Coloring A Border", "algo_input": "You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.\n\nTwo squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.\n\nThe border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).\n\nYou should color the border of the connected component that contains the square grid[row][col] with color.\n\nReturn the final grid.\n\n \nExample 1:\nInput: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput: [[3,3],[3,2]]\nExample 2:\nInput: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput: [[1,3,3],[2,3,3]]\nExample 3:\nInput: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput: [[2,2,2],[2,1,2],[2,2,2]]\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 50\n\t1 <= grid[i][j], color <= 1000\n\t0 <= row < m\n\t0 <= col < n\n\n", "solution_py": "class Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n\n rows, cols = len(grid), len(grid[0])\n border_color = grid[row][col]\n border = []\n\n # Check if a node is a border node or not\n def is_border(r, c):\n if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n return True\n\n for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n nr, nc = r + dr, c + dc\n if grid[nr][nc] != border_color:\n return True\n return False\n\n def dfs(r, c):\n if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color:\n return\n visited.add((r, c))\n\n if is_border(r, c):\n border.append((r, c))\n\n dfs(r + 1, c)\n dfs(r - 1, c)\n dfs(r, c + 1)\n dfs(r, c - 1)\n\n visited = set()\n dfs(row, col)\n for r, c in border:\n grid[r][c] = color\n return grid", "solution_js": "var colorBorder = function(grid, row, col, color) {\n const m = grid.length;\n const n = grid[0].length;\n const dirs = [-1, 0, 1, 0, -1];\n\n const res = [];\n\n for (let i = 0; i < m; i++) {\n res[i] = new Array(n).fill(-1);\n }\n\n const val = grid[row][col];\n\n const stack = [];\n const visited = new Set();\n\n visited.add(`${row}#${col}`); \n stack.push([row, col]);\n\n while (stack.length > 0) {\n const [currRow, currCol] = stack.pop();\n\n let isConnected = true;\n\n for (let i = 0; i < dirs.length - 1; i++) {\n const neiRow = currRow + dirs[i];\n const neiCol = currCol + dirs[i + 1];\n\n if (withinBound(neiRow, neiCol)) {\n if (!visited.has(`${neiRow}#${neiCol}`)) {\n if (grid[neiRow][neiCol] === val) {\n visited.add(`${neiRow}#${neiCol}`);\n stack.push([neiRow, neiCol]);\n }\n else {\n isConnected = false;\n }\n }\n }\n }\n\n if (isBorder(currRow, currCol) || !isConnected) res[currRow][currCol] = color;\n }\n\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (res[i][j] === -1) {\n res[i][j] = grid[i][j];\n }\n }\n }\n\n return res;\n\n\n function withinBound(row, col) {\n return row >= 0 && col >= 0 && row < m && col < n;\n }\n\n function isBorder(row, col) {\n return row === 0 || col === 0 || row === m - 1 || col === n - 1;\n }\n};", "solution_java": "class Solution {\n public int[][] colorBorder(int[][] grid, int row, int col, int color) {\n dfs(grid,row,col,grid[row][col]);\n for(int i = 0;i=grid.length||coldash>=grid[0].length||\n Math.abs(grid[rowdash][coldash])!=color)\n {\n continue;\n }\n count++;\n \n if(grid[rowdash][coldash]==color)\n {\n dfs(grid,rowdash,coldash,color);\n }\n \n }\n if(count==4)\n {\n grid[row][col] = color;\n }\n \n }\n}", "solution_c": "// marking element -ve and then fix it while backtracking worked as visited matrix\n// marking element 1e9 and not fixing it while backtracking works for coloring element\nclass Solution {\nprivate:\n int m,n;\npublic:\n bool is_valid(int i,int j,vector> &grid,int org_color){\n return i >= 0 and j >= 0 and i < m and j < n and grid[i][j] == org_color and grid[i][j] > 0;\n }\n\n bool is_colorable(int i,int j,vector> &grid,int org_color){\n if(i == 0 or j == 0 or i == m-1 or j == n-1) return true; // boundary condn\n\n // checking any of the neighbour is of opposite color or not\n if(i-1 >= 0 and abs(grid[i-1][j]) != org_color and grid[i-1][j] != 1e9) return true;\n\n if(i+1 < m and abs(grid[i+1][j]) != org_color and grid[i+1][j] != 1e9) return true;\n\n if(j-1 >= 0 and abs(grid[i][j-1]) != org_color and grid[i][j-1] != 1e9) return true;\n\n if(j+1 < n and abs(grid[i][j+1]) != org_color and grid[i][j+1] != 1e9) return true;\n\n return false;\n }\n\n void dfs(int i,int j,vector> &grid,int org_color){\n if(!is_valid(i,j,grid,org_color)) return;\n\n if(is_colorable(i,j,grid,org_color)) grid[i][j] = 1e9;\n else grid[i][j] = -grid[i][j];\n\n dfs(i-1,j,grid,org_color); dfs(i+1,j,grid,org_color); // up and down\n dfs(i,j-1,grid,org_color); dfs(i,j+1,grid,org_color); // left and right\n\n if(grid[i][j] < 0) grid[i][j] = -grid[i][j];\n }\n vector> colorBorder(vector>& grid, int row, int col, int color){\n m = grid.size(), n = grid[0].size();\n dfs(row,col,grid,grid[row][col]);\n for(auto &it : grid){\n for(auto &i : it){\n if(i == 1e9) i = color;\n }\n }\n return grid;\n }\n};" }, { "title": "Perfect Rectangle", "algo_input": "Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).\n\nReturn true if all the rectangles together form an exact cover of a rectangular region.\n\n \nExample 1:\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\nOutput: true\nExplanation: All 5 rectangles together form an exact cover of a rectangular region.\n\n\nExample 2:\n\nInput: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\nOutput: false\nExplanation: Because there is a gap between the two rectangular regions.\n\n\nExample 3:\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\nOutput: false\nExplanation: Because two of the rectangles overlap with each other.\n\n\n \nConstraints:\n\n\n\t1 <= rectangles.length <= 2 * 104\n\trectangles[i].length == 4\n\t-105 <= xi, yi, ai, bi <= 105\n\n", "solution_py": "class Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n X1, Y1 = float('inf'), float('inf')\n X2, Y2 = -float('inf'), -float('inf')\n\n points = set()\n actual_area = 0\n for x1, y1, x2, y2 in rectangles:\n # calculate the coords of the potential perfect rectangle\n X1, Y1 = min(X1, x1), min(Y1, y1)\n X2, Y2 = max(X2, x2), max(Y2, y2)\n # add up to the actual_area, so we can check against to see if thers is any part overwritten.\n actual_area += (x2 - x1) * (y2 - y1)\n \n # proving steps in https://labuladong.github.io/algo/4/32/131/\n for p in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]:\n if p in points: \n points.remove(p)\n else: \n points.add(p)\n\n # check the area \n expected_area = (X2 - X1) * (Y2 - Y1)\n if actual_area != expected_area:\n return False\n \n if len(points) != 4: \n return False\n\n if (X1, Y1) not in points: \n return False\n if (X1, Y2) not in points: \n return False\n if (X2, Y1) not in points: \n return False\n if (X2, Y2) not in points: \n return False\n\n return True", "solution_js": "var isRectangleCover = function(R) {\n // left to right, bottom to top (so sort on bottom first, then left)\n R.sort(([left1, bottom1], [left2, bottom2]) => bottom1 - bottom2 || left1 - left2);\n\n // Find all corners\n let leftMost = Infinity,\n bottomMost = Infinity,\n rightMost = -Infinity,\n topMost = -Infinity;\n for (let [left, bottom, right, top] of R) {\n leftMost = Math.min(leftMost, left);\n bottomMost = Math.min(bottomMost, bottom);\n rightMost = Math.max(rightMost, right);\n topMost = Math.max(topMost, top);\n }\n\n // All calculations are with-respect-to large rectangle\n let CH = new Array(rightMost - leftMost).fill(0);\n for (let [left, bottom, right, top] of R) {\n const baseHeight = bottom - bottomMost; // how high base is\n const ceilHeight = top - bottomMost; // how high ceil is\n for (let tempLeft = left; tempLeft < right; tempLeft++) {\n if (CH[tempLeft - leftMost] != baseHeight)\n return false; // > is a duplicate cell < is a gap/ missing cell/ hole\n CH[tempLeft - leftMost] = ceilHeight;\n }\n }\n\n const rectHeight = topMost - bottomMost;\n for (let ceilHeight of CH) {\n if (ceilHeight !== rectHeight)\n return false;\n }\n return true;\n}", "solution_java": "class Solution {\n // Rectangle x0,y0,x1,y1\n public boolean isRectangleCover(int[][] rectangles) {\n // Ordered by y0 first and x0 second\n Arrays.sort(rectangles,(r1,r2)->{\n if(r1[1]==r2[1]) return r1[0]-r2[0];\n return r1[1]-r2[1];\n });\n\n // Layering rectangles with pq, ordered by y1 first and x0 second\n PriorityQueue pq = new PriorityQueue<>((r1,r2)->{\n if(r1[3]==r2[3]) return r1[0]-r2[0];\n return r1[3]-r2[3];\n });\n\n // Create first layer\n pq.offer(rectangles[0]);\n int i=1;\n while(icurr[2]){\n pq.offer(new int[]{curr[2], prev[1], prev[2], prev[3]});\n x=curr[2];\n }else {\n x=prev[2];\n }\n }\n if(x>& rectangles) {\n SegmentTree st(2e5 + 1);\n sort(rectangles.begin(), rectangles.end(), [](auto& lhs, auto& rhs) -> bool {\n if (lhs[1] != rhs[1]) return lhs[1] < rhs[1];\n return lhs[0] < rhs[0];\n });\n\n int min_x = rectangles[0][0];\n int min_y = rectangles[0][1];\n int max_a = rectangles[0][2];\n int max_b = rectangles[0][3];\n long long sum = 1ll * (max_a - min_x) * (max_b - min_y);\n st.update(min_x + 1e5 + 1, max_a + 1e5, max_b);\n for (int i = 1; i < rectangles.size(); ++i) {\n if (rectangles[i][0] < min_x) return false;\n int max_height = st.query(rectangles[i][0] + 1e5 + 1, rectangles[i][2] + 1e5);\n if (max_height > rectangles[i][1]) return false;\n max_a = max(max_a, rectangles[i][2]);\n max_b = max(max_b, rectangles[i][3]);\n sum += 1ll * (rectangles[i][2] - rectangles[i][0]) * (rectangles[i][3] - rectangles[i][1]);\n st.update(rectangles[i][0] + 1e5 + 1, rectangles[i][2] + 1e5, rectangles[i][3]);\n }\n return sum == 1ll * (max_a - min_x) * (max_b - min_y);\n }\n};" }, { "title": "Find First and Last Position of Element in Sorted Array", "algo_input": "Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.\n\nIf target is not found in the array, return [-1, -1].\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n \nExample 1:\nInput: nums = [5,7,7,8,8,10], target = 8\nOutput: [3,4]\nExample 2:\nInput: nums = [5,7,7,8,8,10], target = 6\nOutput: [-1,-1]\nExample 3:\nInput: nums = [], target = 0\nOutput: [-1,-1]\n\n \nConstraints:\n\n\n\t0 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\tnums is a non-decreasing array.\n\t-109 <= target <= 109\n\n", "solution_py": "class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n # if target is not in nums list, we simply return [-1,-1]\n\t\tif target not in nums:\n return [-1,-1]\n \n\t\t# create an empty list\n result = []\n\t\t# iterate nums for the first time, if we found nums[i] matches with target\n\t\t# append the index i to result, break the for loop\n\t\t# because we only care the first and last index of target in nums\n for i in range(len(nums)):\n if nums[i] == target:\n result.append(i)\n break\n \n\t\t# loop through nums backward, if we found nums[j] matches target\n\t\t# append j to result and break the for loop\n for j in range(len(nums)-1, -1, -1):\n if nums[j] == target:\n result.append(j)\n break\n \n return result\n\t\t\n\t\t", "solution_js": "var searchRange = function(nums, target) {\n if (nums.length === 1) return nums[0] === target ? [0, 0] : [-1, -1];\n \n const findFirstInstance = (left, right) => {\n if (left === right) return left;\n var pivot;\n while (left < right) {\n if (left === pivot) left += 1;\n pivot = Math.floor((left + right) / 2);\n if (nums[pivot] === target) {\n if (nums[pivot - 1] !== target) return pivot;\n return findFirstInstance(left, pivot - 1);\n }\n if (nums[pivot] > target) right = pivot;\n else left = pivot;\n }\n }\n const findLastInstance = (left, right) => {\n if (left === right) return left;\n var pivot;\n while (left < right) {\n if (left === pivot) left += 1;\n pivot = Math.floor((left + right) / 2);\n if (nums[pivot] === target) {\n if (nums[pivot + 1] !== target) return pivot;\n return findLastInstance(pivot + 1, right);\n }\n if (nums[pivot] > target) right = pivot;\n else left = pivot;\n }\n }\n \n var left = 0,\n right = nums.length - 1,\n pivot;\n \n while (left < right) {\n if (left === pivot) left += 1;\n pivot = Math.floor((left + right) / 2);\n if (nums[pivot] === target) {\n var first = nums[pivot - 1] !== target ? pivot : findFirstInstance(left, pivot - 1);\n var last = nums[pivot + 1] !== target ? pivot : findLastInstance(pivot + 1, right);\n return [first, last];\n }\n if (nums[pivot] > target) right = pivot;\n else left = pivot;\n }\n \n return [-1, -1];\n};", "solution_java": "class Solution {\n public int[] searchRange(int[] nums, int target) {\n int[] ans={-1,-1}; \n int start=search(nums,target,true);\n int end=search(nums,target,false);\n ans[0]=start;\n ans[1]=end;\n return ans;\n }\n int search(int[] nums ,int target,boolean findStart){\n int ans=-1;\n int start=0;\n int end=nums.length-1;\n while(start<=end){\n int mid=start+(end-start)/2;\n if(target>nums[mid]){\n start=mid+1;\n }\n else if(target& nums, int target,int l,int r)\n {\n while(l<=r)\n {\n int m = (l+r)/2;\n if(nums[m]target) r = m-1;\n else\n {\n if(m==0)\n return m;\n else if(nums[m-1]==target)\n r = m-1;\n else\n return m;\n }\n }\n\n return -1;\n }\n\n int lastEle(vector& nums, int target,int l,int r)\n {\n while(l<=r)\n {\n int m = (l+r)/2;\n if(nums[m]target) r = m-1;\n else\n {\n if(m==nums.size()-1)\n return m;\n else if(nums[m+1]==target)\n l = m+1;\n else\n return m;\n }\n }\n\n return -1;\n }\n vector searchRange(vector& nums, int target) {\n\n vector binSearch;\n int a = startEle(nums,target,0,nums.size()-1);\n if(a==-1)\n {\n binSearch.push_back(-1);\n binSearch.push_back(-1);\n return binSearch;\n }\n else\n {\n binSearch.push_back(a);\n }\n\n int b = lastEle(nums,target,0,nums.size()-1);\n binSearch.push_back(b);\n\n return binSearch;\n\n }\n};" }, { "title": "Find and Replace Pattern", "algo_input": "Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.\n\nA word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.\n\nRecall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.\n\n \nExample 1:\n\nInput: words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\nOutput: [\"mee\",\"aqq\"]\nExplanation: \"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.\n\n\nExample 2:\n\nInput: words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput: [\"a\",\"b\",\"c\"]\n\n\n \nConstraints:\n\n\n\t1 <= pattern.length <= 20\n\t1 <= words.length <= 50\n\twords[i].length == pattern.length\n\tpattern and words[i] are lowercase English letters.\n\n", "solution_py": "class Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n d={}\n for i,v in enumerate(pattern):\n if v in d:\n d[v].append(i)\n else:\n d|={v:[i]}\n #DICTIONARY CONTAINING LETTERS AND THEIR INDICES\n ans=[]\n for i in words:\n e={}\n for j,v in enumerate(i):\n if v in e:\n e[v].append(j)\n else:\n e|={v:[j]}\n #DICTIONARY CONTAINING LETTERS OF INDICES OF CURRENT WORD\n for u,v in zip(d.values(),e.values()):\n #COMPARING EACH VALUE\n if u!=v:\n break\n #IF SUCCESSFUL APPEND TO ANS\n else:ans.append(i)\n return ans", "solution_js": "var findAndReplacePattern = function(words, pattern) {\n var patt = patternarr(pattern) // 010\n return words.filter(e=>patternarr(e) == patt)\n};\n\nconst patternarr = function (str) {\n var result = '';\n \n for(let i=0;i findAndReplacePattern(String[] words, String pattern) {\n List result=new ArrayList<>();\n for(String word:words) {\n Map map=new HashMap<>();\n Set set=new HashSet<>();\n int i=0;\n for(;i found_Pattern(string pattern)\n {\n\t // if string is empty return empty vector.\n if(pattern.size() == 0)\n return {};\n \n vector v;\n\t\t\n\t\t// ind variable for keeping track of unique characters\n int ind = 0;\n\t\t\n unordered_map mp;\n for(int i = 0; i findAndReplacePattern(vector& words, string pattern) {\n \n\t\t// store numeric patten of Pattern string in v\n vector v = found_Pattern(pattern);\n \n int n = words.size();\n vector ans;\n \n\t\t// iterating and comparing pattern of each word with v(numeric pattern of Pattern)\n for(int i = 0; i pattern_word = found_Pattern(words[i]);\n \n\t\t\t// if matched add words[i] to answer vector\n if(v == pattern_word)\n ans.push_back(words[i]);\n }\n \n return ans;\n }\n};" }, { "title": "Repeated Substring Pattern", "algo_input": "Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.\n\n \nExample 1:\n\nInput: s = \"abab\"\nOutput: true\nExplanation: It is the substring \"ab\" twice.\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: false\n\n\nExample 3:\n\nInput: s = \"abcabcabcabc\"\nOutput: true\nExplanation: It is the substring \"abc\" four times or the substring \"abcabc\" twice.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n for i in range(1, len(s)//2+1):\n if s[:i] * (len(s)//i) == s:\n return True\n return False", "solution_js": "var repeatedSubstringPattern = function(s) {\n let repeatStr = s.repeat(2) //first duplicate the string with repeat function\n let sliceStr = repeatStr.slice(1,-1) // slice string first and last string word\n return sliceStr.includes(s) // now check if the main string(s) is included by sliced string\n}", "solution_java": "class Solution {\n\n public boolean repeatedSubstringPattern(String s) {\n String temp=\"\";\n for(int i=0 ;i get_kmp_table(const string &s) {\n vector table(s.size());\n int i=0; int j=-1;\n table[0] = -1;\n while (i < s.size()) {\n if (j == -1 || s[i] == s[j]) {\n i++;\n j++;\n table[i] = j;\n }\n else {\n j = table[j];\n }\n }\n return table;\n }\n \n bool validate_table(const vector& table) {\n int idx = table.size() - 1;\n while (idx >= 0 && table[idx] > 0) {\n idx--;\n }\n if (idx <= 0) return false;\n int substr_len = idx;\n if (table.size() % substr_len != 0) return false;\n idx = idx + 1; // the first nonzero element in the string\n while (idx < table.size()-1) {\n if (table[idx] != table[idx+1]-1) return false;\n idx++;\n }\n return true;\n }\n \n bool repeatedSubstringPattern(string s) {\n if (s.size() <= 1) return true;\n \n auto table1 = get_kmp_table(s);\n string ss = s;\n reverse(ss.begin(), ss.end());\n auto table2 = get_kmp_table(ss);\n \n return (validate_table(table1) && validate_table(table2));\n \n }\n};" }, { "title": "Reshape the Matrix", "algo_input": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.\n\nYou are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.\n\nThe reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.\n\nIf the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n\n \nExample 1:\n\nInput: mat = [[1,2],[3,4]], r = 1, c = 4\nOutput: [[1,2,3,4]]\n\n\nExample 2:\n\nInput: mat = [[1,2],[3,4]], r = 2, c = 4\nOutput: [[1,2],[3,4]]\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 100\n\t-1000 <= mat[i][j] <= 1000\n\t1 <= r, c <= 300\n\n", "solution_py": "import numpy\nclass Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n return numpy.reshape(mat,(r,c)) if r*c==len(mat)*len(mat[0]) else mat", "solution_js": "var matrixReshape = function(mat, r, c) {\n const origR = mat.length;\n const origC = mat[0].length;\n \n if (r*c !== origR*origC) {\n return mat;\n }\n \n const flat = mat.flatMap(n => n);\n \n const output = [];\n for (let i=0; i> matrixReshape(vector>& mat, int r, int c) {\n if(mat.size()* mat[0].size()!= r * c) {\n return mat;\n } \n vector>v(r,vector(c));\n int k = 0;\n int l = 0;\n\n for(int i = 0; i < mat.size(); i++) {\n for(int j = 0; j < mat[0].size(); j++) {\n if(l == v[0].size()) {\n l = 0;\n k++;\n }\n\n v[k][l++] = mat[i][j];\n }\n }\n return v;\n }\n};" }, { "title": "Add Two Numbers II", "algo_input": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n\n \nExample 1:\n\nInput: l1 = [7,2,4,3], l2 = [5,6,4]\nOutput: [7,8,0,7]\n\n\nExample 2:\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [8,0,7]\n\n\nExample 3:\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in each linked list is in the range [1, 100].\n\t0 <= Node.val <= 9\n\tIt is guaranteed that the list represents a number that does not have leading zeros.\n\n\n \nFollow up: Could you solve it without reversing the input lists?\n", "solution_py": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n def number(head):\n ans = ''\n while head:\n ans+=str(head.val)\n head = head.next\n return int(ans) \n temp = dummy = ListNode(0)\n for i in str(number(l1) + number(l2)):\n temp.next = ListNode(i)\n temp = temp.next\n return dummy.next\n ", "solution_js": "var addTwoNumbers = function(l1, l2) {\n const reverse = head =>{\n let prev = null\n let dummy = head\n\n while(dummy){\n let temp = dummy.next\n dummy.next = prev\n prev = dummy\n dummy = temp\n }\n return prev\n }\n\n let head1 = reverse(l1)\n let head2 = reverse(l2)\n\n // add\n let sum = new ListNode()\n let p = sum\n let carry = 0\n\n while((head1 && head2) || carry){\n let v1 = head1?head1.val:0\n let v2 = head2?head2.val:0\n let v = v1+v2+carry\n\n if(v>=10) carry = 1\n else carry = 0\n\n let node = new ListNode(v%10)\n\n sum.next = node\n sum = sum.next\n head1 = head1&&head1.next\n head2 = head2&&head2.next\n\n }\n sum.next = head1||head2\n return reverse(p.next)\n};", "solution_java": "class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode res=new ListNode(0);\n ListNode curr=res;\n l1=reverseLinkedList(l1);\n l2=reverseLinkedList(l2);\n int carry=0;\n while(l1!=null||l2!=null||carry==1)\n {\n int sum=0;\n if(l1!=null)\n {\n sum+=l1.val;\n l1=l1.next;\n }\n if(l2!=null)\n {\n sum+=l2.val;\n l2=l2.next;\n }\n sum+=carry;\n carry = sum/10; \n curr.next= new ListNode(sum % 10); \n \n curr = curr.next; \n }\n return reverseLinkedList(res.next);\n }\n public ListNode reverseLinkedList(ListNode head)\n {\n ListNode curr=head;\n ListNode prev=null;\n ListNode next;\n while(curr!=null)\n {\n next=curr.next;\n curr.next=prev;\n prev=curr;\n curr=next;\n }\n return prev;\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverse(ListNode* l1){\n if(l1==NULL||l1->next==NULL){\n return l1;\n }\n ListNode* ans=reverse(l1->next);\n l1->next->next=l1;\n l1->next=NULL;\n return ans;\n }\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode* l11= reverse(l1);\n ListNode* l22= reverse(l2);\n ListNode* dummy=new ListNode(0);\n ListNode* curr=dummy;\n int carry=0;\n int sum=0;\n while(l11||l22||carry!=0){\n int x=l11?l11->val:0;\n int y=l22?l22->val:0;\n sum=x+y+carry;\n carry=sum/10;\n curr->next=new ListNode(sum%10);\n curr=curr->next;\n l11=l11?l11->next:nullptr;\n l22=l22?l22->next:nullptr;\n }\n dummy=dummy->next;\n dummy=reverse(dummy);\n return dummy;\n }\n};" }, { "title": "Flood Fill", "algo_input": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.\n\nYou are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].\n\nTo perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.\n\nReturn the modified image after performing the flood fill.\n\n \nExample 1:\n\nInput: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.\n\n\nExample 2:\n\nInput: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\nOutput: [[0,0,0],[0,0,0]]\nExplanation: The starting pixel is already colored 0, so no changes are made to the image.\n\n\n \nConstraints:\n\n\n\tm == image.length\n\tn == image[i].length\n\t1 <= m, n <= 50\n\t0 <= image[i][j], color < 216\n\t0 <= sr < m\n\t0 <= sc < n\n\n", "solution_py": "class Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n queue = deque()\n rows = len(image)\n cols = len(image[0])\n \n targetColor = image[sr][sc]\n \n if color == targetColor:\n\t\t # in this case, we don't need to do anything\n return image\n\n rDirs = [1, 0, -1, 0]\n cDirs = [0, 1, 0, -1]\n \n queue.append((sr, sc))\n \n while len(queue) > 0:\n r, c = queue.pop()\n \n image[r][c] = color\n for rd, cd in zip(rDirs, cDirs):\n newRow = r + rd\n newCol = c + cd\n \n isValidCoordinate = newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols\n \n if isValidCoordinate and image[newRow][newCol] == targetColor:\n queue.append((newRow, newCol))\n \n return image\n \n ", "solution_js": "/**\n * @param {number[][]} image\n * @param {number} sr\n * @param {number} sc\n * @param {number} color\n * @return {number[][]}\n */\nvar floodFill = function(image, sr, sc, color) {\n const pixelsToCheck = [[sr, sc]]\n const startingPixelColor = image[sr][sc]\n const directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]\n const seenPixels = new Set()\n\n if (\n startingPixelColor === undefined ||\n startingPixelColor === color\n ) return image\n\n for (const pixel of pixelsToCheck) {\n const currentPixelColor = image[pixel[0]]?.[pixel[1]]\n\n if (\n currentPixelColor === undefined ||\n startingPixelColor !== currentPixelColor\n ) continue\n\n image[pixel[0]][pixel[1]] = color\n\n for (const direction of directions) {\n const newPixel = [pixel[0] + direction[0], pixel[1] + direction[1]]\n const pixelString = newPixel.join()\n\n if (seenPixels.has(pixelString)) continue\n\n pixelsToCheck.push(newPixel)\n seenPixels.add(pixelString)\n }\n }\n\n return image\n};", "solution_java": "class Solution {\n void colorFill(int[][]image,int sr,int sc,int sourceColor,int targetColor){\n int m = image.length, n = image[0].length;\n\n if(sr>=0 && sr=0 && sc> paths = {{0,1},{0,-1},{-1,0},{1,0}};\n bool check(int i,int j , int n, int m){\n if(i>=n or i<0 or j>=m or j<0) return false;\n return true;\n }\n void solve(vector> &image, int sr, int sc, int color, int orig){\n int n = image.size(), m = image[0].size();\n image[sr][sc] = color;\n for(int i=0;i<4;i++){\n int new_sr = paths[i][0] + sr;\n int new_sc = paths[i][1] + sc;\n if(check(new_sr,new_sc,n,m)==true and image[new_sr][new_sc]==orig){\n solve(image, new_sr, new_sc, color,orig);\n }\n }\n\n }\n vector> floodFill(vector>& image, int sr, int sc, int color) {\n if(color==image[sr][sc]) return image;\n int orig = image[sr][sc];\n solve(image, sr,sc,color, orig);\n return image;\n }\n};" }, { "title": "Valid Sudoku", "algo_input": "Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:\n\n\n\tEach row must contain the digits 1-9 without repetition.\n\tEach column must contain the digits 1-9 without repetition.\n\tEach of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.\n\n\nNote:\n\n\n\tA Sudoku board (partially filled) could be valid but is not necessarily solvable.\n\tOnly the filled cells need to be validated according to the mentioned rules.\n\n\n \nExample 1:\n\nInput: board = \n[[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput: true\n\n\nExample 2:\n\nInput: board = \n[[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\nOutput: false\nExplanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.\n\n\n \nConstraints:\n\n\n\tboard.length == 9\n\tboard[i].length == 9\n\tboard[i][j] is a digit 1-9 or '.'.\n\n", "solution_py": "class Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n\n hrow = {}\n hcol = {}\n hbox = defaultdict(list)\n\n #CHECK FOR DUPLICATES ROWWISE\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[i][j] != '.':\n\n if board[i][j] not in hrow:\n hrow[board[i][j]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS ROW\n hrow.clear()\n print(\"TRUE1\")\n #CHECK FOR DUPLICATES COLUMNWISE\n\n for i in range(9):\n for j in range(9):\n\n #JUST THAT THE DUPLICATE SHOULDNT BE \",\"\n if board[j][i] != '.':\n\n if board[j][i] not in hcol:\n hcol[board[j][i]] = 1\n\n else:\n return False\n\n #CLEAR HASHMAP FOR THIS COL\n\n hcol.clear()\n\n print('TRUE2')\n\n #CHECK DUPLICATE IN BOX, THIS IS WHERE KEY DESIGN SKILLS COME INTO PLAY, FOR SUDOKU YOU COMBINE ROW INDICES AND COL INDICES\n\n for i in range(9):\n for j in range(9):\n\n i_3 = i //3\n j_3 = j//3\n\n # print(hbox)\n if board[i][j] != '.':\n\n #CHECK ELEMENT OF ORIGINAL INDICE present in key i_3 , j_3\n if board[i][j] not in hbox[i_3 , j_3]:\n# #CHECKED IN NEW KEY\n hbox[i_3 ,j_3 ]= hbox[i_3 ,j_3 ] + [board[i][j]]\n\n else:\n return False\n\n return True", "solution_js": "/**\n * @param {character[][]} board\n * @return {boolean}\n */\nvar isValidSudoku = function(board) {\n let rowMap = new Map();\n let colMap = new Map();\n let square = new Map();\n for(let i=0; i>& board) {\n \n int n = board.size();\n \n for(int i=0;im;\n for(int j=0;jm;\n for(int j=0;jm;\n for(int k=i;k<=i+2;k++){\n for(int p=j;p<=j+2;p++){\n \n if(board[k][p]=='.'){\n continue;\n }\n \n if(m.find(board[k][p])!=m.end()){\n return false;\n }\n else{\n m[board[k][p]]++;\n }\n }\n }\n }\n }\n \n return true;\n }\n};" }, { "title": "Binary Search", "algo_input": "Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.\n\nYou must write an algorithm with O(log n) runtime complexity.\n\n \nExample 1:\n\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\n\nExample 2:\n\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-104 < nums[i], target < 104\n\tAll the integers in nums are unique.\n\tnums is sorted in ascending order.\n\n", "solution_py": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums)-1\n \n while left<=right:\n mid = (left+right)//2\n if nums[mid]==target:\n return mid\n elif nums[mid]>target:\n right = mid-1\n else:\n left = mid+1\n \n return -1", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number}\n */\nvar search = function(nums, target) {\n \n let low=0;\n let high=nums.length-1;\n \n if(targetnums[high]){\n return -1;\n }\n \n while(low<=high) {\n \n mid=Math.floor((low+high)/2);\n \n if (nums[mid]==target){\n return mid;\n }\n else{\n \n if(target>nums[mid]){\n low=mid+1;\n \n }\n else{\n high=mid-1;\n }\n }\n }\n \n return -1;\n \n};", "solution_java": "class Solution {\n public int search(int[] nums, int target) {\n int l = 0;\n int r = nums.length - 1;\n return binarySearch(nums, l, r, target);\n }\n \n private int binarySearch(int[] nums, int l, int r, int target) {\n if (l <= r) {\n int mid = (r + l) / 2;\n \n if (nums[mid] == target) {\n return mid;\n } \n \n if (nums[mid] < target) {\n return binarySearch(nums, mid + 1, r, target);\n } else {\n return binarySearch(nums, l, mid - 1, target);\n }\n } \n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int search(vector& nums, int target) {\n int n = nums.size();\n int jump = 5;\n int p = 0;\n while (jump*5 < n) jump *= 5;\n while (jump > 0) {\n while (p+jump < n && nums[p+jump] <= target) p += jump;\n jump /= 5;\n }\n return (p == n || nums[p]!= target) ? -1 : p;\n }\n};" }, { "title": "Design Circular Queue", "algo_input": "Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\".\n\nOne of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.\n\nImplementation the MyCircularQueue class:\n\n\n\tMyCircularQueue(k) Initializes the object with the size of the queue to be k.\n\tint Front() Gets the front item from the queue. If the queue is empty, return -1.\n\tint Rear() Gets the last item from the queue. If the queue is empty, return -1.\n\tboolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.\n\tboolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.\n\tboolean isEmpty() Checks whether the circular queue is empty or not.\n\tboolean isFull() Checks whether the circular queue is full or not.\n\n\nYou must solve the problem without using the built-in queue data structure in your programming language. \n\n \nExample 1:\n\nInput\n[\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 3, true, true, true, 4]\n\nExplanation\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4\n\n\n \nConstraints:\n\n\n\t1 <= k <= 1000\n\t0 <= value <= 1000\n\tAt most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.\n\n", "solution_py": "class MyCircularQueue {\n\n int head = -1;\n int tail = -1;\n int[] q;\n int k;\n \n public MyCircularQueue(int k) {\n q = new int[k];\n this.k = k;\n }\n \n public boolean enQueue(int value) {\n if(head == -1 && tail == -1) {\n // enqueue when the queue is empty\n head = tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n if((tail == k-1 && head == 0) || tail+1 == head) {\n // queue is full\n return false;\n }\n tail++;\n if(tail == k) // condition for circularity\n tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n \n public boolean deQueue() {\n if(head == -1) {\n // check if q is already empty\n return false;\n } \n if(head == tail) {\n // only 1 element is there and head,tail both points same index\n head = tail = -1; // deQueue done\n return true;\n }\n head++; // deQueue done\n if(head == k) // condition for circularity\n head = 0;\n return true;\n }\n \n public int Front() {\n if(head == -1) \n return -1;\n return q[head];\n }\n \n public int Rear() {\n if(tail == -1) \n return -1;\n return q[tail];\n }\n \n public boolean isEmpty() {\n if(head == -1 && tail == -1) \n return true;\n return false;\n }\n \n public boolean isFull() {\n if(tail == k-1 || tail+1 == head) \n return true;\n return false;\n }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */", "solution_js": "class MyCircularQueue {\n\n int head = -1;\n int tail = -1;\n int[] q;\n int k;\n \n public MyCircularQueue(int k) {\n q = new int[k];\n this.k = k;\n }\n \n public boolean enQueue(int value) {\n if(head == -1 && tail == -1) {\n // enqueue when the queue is empty\n head = tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n if((tail == k-1 && head == 0) || tail+1 == head) {\n // queue is full\n return false;\n }\n tail++;\n if(tail == k) // condition for circularity\n tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n \n public boolean deQueue() {\n if(head == -1) {\n // check if q is already empty\n return false;\n } \n if(head == tail) {\n // only 1 element is there and head,tail both points same index\n head = tail = -1; // deQueue done\n return true;\n }\n head++; // deQueue done\n if(head == k) // condition for circularity\n head = 0;\n return true;\n }\n \n public int Front() {\n if(head == -1) \n return -1;\n return q[head];\n }\n \n public int Rear() {\n if(tail == -1) \n return -1;\n return q[tail];\n }\n \n public boolean isEmpty() {\n if(head == -1 && tail == -1) \n return true;\n return false;\n }\n \n public boolean isFull() {\n if(tail == k-1 || tail+1 == head) \n return true;\n return false;\n }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */", "solution_java": "class MyCircularQueue {\n\n private int front;\n private int rear;\n private int[] arr;\n private int cap;\n \n private int next(int i){ // to get next idx after i in circular queue\n return (i+1)%cap;\n }\n private int prev(int i){ // to get prev idx before i in circular queue\n return (i+cap-1)%cap;\n }\n \n\t// rest is as simple as implmenting a normal queue using array.\n public MyCircularQueue(int k) {\n arr = new int[k];\n cap=k;\n front=-1;\n rear=-1;\n }\n \n public boolean enQueue(int value) {\n if(isFull())return false;\n if(front==-1){\n front=0;\n rear=0;\n arr[rear]=value;\n return true;\n }\n rear = next(rear);\n arr[rear]=value;\n return true;\n }\n \n public boolean deQueue() {\n if(isEmpty())return false;\n if(front==rear){\n front=-1;\n rear=-1;\n return true;\n }\n front=next(front);\n return true;\n }\n \n public int Front() {\n if(front==-1)return -1;\n return arr[front];\n }\n \n public int Rear() {\n if(rear==-1)return -1;\n return arr[rear];\n }\n \n public boolean isEmpty() {\n return front==-1;\n }\n \n public boolean isFull() {\n return front!=-1 && next(rear)==front;\n }\n}", "solution_c": "class MyCircularQueue {\n\n int head = -1;\n int tail = -1;\n int[] q;\n int k;\n \n public MyCircularQueue(int k) {\n q = new int[k];\n this.k = k;\n }\n \n public boolean enQueue(int value) {\n if(head == -1 && tail == -1) {\n // enqueue when the queue is empty\n head = tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n if((tail == k-1 && head == 0) || tail+1 == head) {\n // queue is full\n return false;\n }\n tail++;\n if(tail == k) // condition for circularity\n tail = 0;\n q[tail] = value; // enQueue done\n return true;\n }\n \n public boolean deQueue() {\n if(head == -1) {\n // check if q is already empty\n return false;\n } \n if(head == tail) {\n // only 1 element is there and head,tail both points same index\n head = tail = -1; // deQueue done\n return true;\n }\n head++; // deQueue done\n if(head == k) // condition for circularity\n head = 0;\n return true;\n }\n \n public int Front() {\n if(head == -1) \n return -1;\n return q[head];\n }\n \n public int Rear() {\n if(tail == -1) \n return -1;\n return q[tail];\n }\n \n public boolean isEmpty() {\n if(head == -1 && tail == -1) \n return true;\n return false;\n }\n \n public boolean isFull() {\n if(tail == k-1 || tail+1 == head) \n return true;\n return false;\n }\n}\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue obj = new MyCircularQueue(k);\n * boolean param_1 = obj.enQueue(value);\n * boolean param_2 = obj.deQueue();\n * int param_3 = obj.Front();\n * int param_4 = obj.Rear();\n * boolean param_5 = obj.isEmpty();\n * boolean param_6 = obj.isFull();\n */" }, { "title": "Online Majority Element In Subarray", "algo_input": "Design a data structure that efficiently finds the majority element of a given subarray.\n\nThe majority element of a subarray is an element that occurs threshold times or more in the subarray.\n\nImplementing the MajorityChecker class:\n\n\n\tMajorityChecker(int[] arr) Initializes the instance of the class with the given array arr.\n\tint query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.\n\n\n \nExample 1:\n\nInput\n[\"MajorityChecker\", \"query\", \"query\", \"query\"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]\nOutput\n[null, 1, -1, 2]\n\nExplanation\nMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 2 * 104\n\t1 <= arr[i] <= 2 * 104\n\t0 <= left <= right < arr.length\n\tthreshold <= right - left + 1\n\t2 * threshold > right - left + 1\n\tAt most 104 calls will be made to query.\n\n", "solution_py": "MAX_N = 2*10**4\nMAX_BIT = MAX_N.bit_length()\nclass MajorityChecker:\n\n def __init__(self, nums: List[int]):\n n = len(nums)\n self.bit_sum = [[0] * MAX_BIT for _ in range(n+1)]\n for i in range(1, n+1):\n for b in range(MAX_BIT):\n self.bit_sum[i][b] = self.bit_sum[i-1][b] + ((nums[i-1] >> b) & 1)\n self.num_idx = defaultdict(list)\n for i in range(n):\n self.num_idx[nums[i]].append(i)\n\n def query(self, left: int, right: int, threshold: int) -> int:\n num = 0\n for b in range(MAX_BIT):\n if self.bit_sum[right+1][b] - self.bit_sum[left][b] >= threshold:\n num |= 1 << b\n l = bisect.bisect_left(self.num_idx[num], left)\n r = bisect.bisect_right(self.num_idx[num], right)\n if r-l >= threshold:\n return num\n return -1", "solution_js": "var MajorityChecker = function(arr) {\n this.arr = arr;\n};\n\nMajorityChecker.prototype.query = function(left, right, threshold) {\n var candidate = 0\n var count = 0\n for (var i = left; i < right+1; i++) {\n if (count == 0) {\n candidate = this.arr[i];\n count = 1;\n }\n else if (candidate == this.arr[i]) {\n count += 1\n }\n else {\n count -= 1\n }\n }\n \n count = 0\n for (var i = left; i < right+1; i++) {\n if (candidate == this.arr[i]) {\n count += 1\n }\n }\n\n if (count >= threshold) {\n return candidate\n } \n return -1\n};", "solution_java": "class MajorityChecker {\n \n private final int digits=15;\n private int[][]presum;\n private ArrayList[]pos;\n \n public MajorityChecker(int[] arr) {\n int len=arr.length;\n presum=new int[len+1][digits];\n pos=new ArrayList[20001];\n \n for(int i=0;i>=1;\n }\n }\n }\n \n public int query(int left, int right, int threshold) {\n int ans=0;\n for(int i=digits-1;i>=0;i--){\n int cnt=presum[right+1][i]-presum[left][i];\n int b=1;\n if(cnt>=threshold)b=1;\n else if(right-left+1-cnt>=threshold)b=0;\n else return -1;\n ans=(ans<<1)+b;\n }\n \n // check\n ArrayListlist=pos[ans];\n if(list==null)return -1;\n int L=floor(list,left-1);\n int R=floor(list,right);\n if(R-L>=threshold)return ans;\n return -1;\n }\n \n private int floor(ArrayListlist,int n){\n int left=0, right=list.size()-1, mid;\n while(left<=right){\n mid=left+(right-left)/2;\n int index=list.get(mid);\n if(index==n)return mid;\n else if(index& arr) {\n this->arr = arr;\n map cnt;\n for (auto& v: arr) {\n cnt[v]++;\n }\n val_idx = vector(20001, -1);\n for (auto it = cnt.begin(); it != cnt.end(); ++it) {\n if (it->second >= 250) {\n val_idx[it->first] = elems.size();\n elems.push_back(it->first);\n }\n }\n n = elems.size();\n pre = vector>(n, vector(arr.size(), 0));\n if (val_idx[arr[0]] != -1)\n pre[val_idx[arr[0]]][0]++;\n for (int i = 1; i < arr.size(); ++i) {\n for (int j = 0; j < n; ++j) {\n pre[j][i] = pre[j][i-1];\n }\n if (val_idx[arr[i]] != -1)\n pre[val_idx[arr[i]]][i]++;\n }\n }\n\n int query(int left, int right, int threshold) {\n int width = right - left + 1;\n if (width < 500) {\n map cnt;\n int most_frequent = 0;\n int most_frequent_val;\n while (left <= right) {\n if (++cnt[arr[left++]] > most_frequent) {\n most_frequent = cnt[arr[left - 1]];\n most_frequent_val = arr[left - 1];\n }\n // early end condition, there are not enough elements left\n if (right + most_frequent + 1 < threshold + left) return -1;\n }\n return most_frequent >= threshold ? most_frequent_val : -1;\n }\n\n for (int i = 0; i < n; ++i) {\n if (pre[i][right] - (left - 1 >= 0 ? pre[i][left - 1] : 0) >= threshold) {\n return elems[i];\n }\n }\n return -1;\n }\n\nprivate:\n vector arr;\n vector elems;\n vector val_idx;\n int n;\n vector> pre;\n};" }, { "title": "Find And Replace in String", "algo_input": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.\n\nTo complete the ith replacement operation:\n\n\n\tCheck if the substring sources[i] occurs at index indices[i] in the original string s.\n\tIf it does not occur, do nothing.\n\tOtherwise if it does occur, replace that substring with targets[i].\n\n\nFor example, if s = \"abcd\", indices[i] = 0, sources[i] = \"ab\", and targets[i] = \"eee\", then the result of this replacement will be \"eeecd\".\n\nAll replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.\n\n\n\tFor example, a testcase with s = \"abc\", indices = [0, 1], and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap.\n\n\nReturn the resulting string after performing all replacement operations on s.\n\nA substring is a contiguous sequence of characters in a string.\n\n \nExample 1:\n\nInput: s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput: \"eeebffff\"\nExplanation:\n\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".\n\n\nExample 2:\n\nInput: s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput: \"eeecd\"\nExplanation:\n\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\tk == indices.length == sources.length == targets.length\n\t1 <= k <= 100\n\t0 <= indexes[i] < s.length\n\t1 <= sources[i].length, targets[i].length <= 50\n\ts consists of only lowercase English letters.\n\tsources[i] and targets[i] consist of only lowercase English letters.\n\n", "solution_py": "class Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n \n inputs = list(zip(indices,sources,targets))\n inputs.sort(key = lambda x: x[0])\n \n offset = 0\n for idx, src, tgt in inputs:\n idx += offset\n if s[idx:idx + len(src)] != src:\n print('hi')\n print(idx)\n continue\n \n offset += len(tgt) - len(src)\n s = s[:idx] + tgt + s[idx+len(src):]\n \n return s", "solution_js": "var findReplaceString = function(s, indices, sources, targets) {\n let res = s.split(''); \n\n for(let i=0; i subst = new HashMap<>();\n HashMap tgt = new HashMap<>();\n \n for(int i = 0; i< indices.length; i++) {\n subst.put(indices[i], sources[i]);\n tgt.put(indices[i],targets[i]);\n }\n \n Arrays.sort(indices);\n \n String res = \"\";\n int count = 0;\n int avail[] = new int[indices.length];\n for(int i = 0; i< s.length(); i++) {\n if(count < indices.length && i == indices[count] && s.indexOf(subst.get(indices[count]), indices[count]) == indices[count]){\n res = res+\"\"+tgt.get(indices[count]);\n i = i+ subst.get(indices[count]).length()-1;\n count++;\n } else {\n if(count < indices.length && i == indices[count])\n count++;\n res+= s.charAt(i);\n }\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n string findReplaceString(string s, vector& indices, vector& sources, vector& targets) { \n int baggage = 0;\n int n = indices.size();\n map> mp;\n for(int i=0;i List[int]:\n ogLength = intLength\n isOdd = intLength & 1\n if isOdd:\n intLength += 1\n k = intLength // 2\n k = 10 ** (k - 1)\n op = []\n for q in queries:\n pal = str(k + q - 1)\n if isOdd:\n pal += pal[::-1][1:]\n else:\n pal += pal[::-1]\n if len(pal) == ogLength:\n op.append(int(pal))\n else:\n op.append(-1)\n return op", "solution_js": "var kthPalindrome = function(queries, intLength) {\n let output=[];\n // 1. We use FIRST 2 digits to create palindromes: Math.floor((3+1)/2)=2\n let digit=Math.floor((intLength+1)/2);\n\n for(let i=0; i=100, which is INVALID\n if(helper>=10**digit){output.push(-1)}\n else{\n let m=intLength-digit;\n // 3A. We still need m digits for REFLECTION: 14=>[\"1\",\"4\"]=>\"41\"\n let add=helper.toString().substr(0, m).split(\"\").reverse().join(\"\");\n // 3B. Multiply 10**m for reversed digits: 14=>1400=>1441\n helper=helper*10**m+add*1;\n output.push(helper);\n }\n }\n return output; // [1441,-1]\n};", "solution_java": "class Solution {\n public long[] kthPalindrome(int[] queries, int intLength) {\n long[] res= new long[queries.length];\n for(int i=0;i0)\n palindrome /= 10;\n while (palindrome>0)\n {\n res1=res1*10+(palindrome % 10);\n palindrome /= 10;\n }\n String g=\"\";\n g+=res1;\n if(g.length()!=kdigit)\n return -1;\n return res1;\n}\n}", "solution_c": "#define ll long long\nclass Solution {\npublic:\n vector kthPalindrome(vector& queries, int intLength) {\n vector result;\n ll start = intLength % 2 == 0 ? pow(10, intLength/2 - 1) : pow(10, intLength/2);\n for(int q: queries) { \n string s = to_string(start + q - 1);\n string palindrome = s;\n reverse(s.begin(), s.end());\n if(intLength % 2 == 0) {\n palindrome += s;\n } else {\n palindrome += s.substr(1, s.size() - 1);\n }\n\t\t\t\n\t\t\t// len of palindrome should be intLength, otherwise -1\n if (palindrome.size() == intLength)\n result.push_back(stoll(palindrome));\n else\n result.push_back(-1);\n }\n \n return result;\n }\n};" }, { "title": "Find Subsequence of Length K With the Largest Sum", "algo_input": "You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.\n\nReturn any such subsequence as an integer array of length k.\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n\n \nExample 1:\n\nInput: nums = [2,1,3,3], k = 2\nOutput: [3,3]\nExplanation:\nThe subsequence has the largest sum of 3 + 3 = 6.\n\nExample 2:\n\nInput: nums = [-1,-2,3,4], k = 3\nOutput: [-1,3,4]\nExplanation: \nThe subsequence has the largest sum of -1 + 3 + 4 = 6.\n\n\nExample 3:\n\nInput: nums = [3,4,3,3], k = 2\nOutput: [3,4]\nExplanation:\nThe subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t-105 <= nums[i] <= 105\n\t1 <= k <= nums.length\n\n", "solution_py": "class Solution(object):\n def maxSubsequence(self, nums, k):\n ret, max_k = [], sorted(nums, reverse=True)[:k]\n for num in nums:\n if num in max_k:\n ret.append(num)\n max_k.remove(num)\n if len(max_k) == 0:\n return ret", "solution_js": "var maxSubsequence = function(nums, k) {\n return nums.map((v,i)=>[v,i]).sort((a,b)=>a[0]-b[0]).slice(-k).sort((a,b)=>a[1]-b[1]).map(x=>x[0]);\n};", "solution_java": "class Solution {\n public int[] maxSubsequence(int[] nums, int k) {\n PriorityQueue pq = new PriorityQueue<>((a,b) -> b[0] - a[0]);\n \n for(int i=0; i l = new ArrayList<>();\n \n while(k-- != 0)\n l.add(pq.poll());\n \n Collections.sort(l, (a,b) -> a[1] - b[1]);\n \n int[] res = new int[l.size()];\n \n int index = 0;\n \n for(int[] i: l)\n res[index++] = i[0];\n \n return res;\n }\n}", "solution_c": "// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(N)\nclass Solution {\npublic:\n vector maxSubsequence(vector& A, int k) {\n vector id(A.size());\n iota(begin(id), end(id), 0); // Index array 0, 1, 2, ...\n sort(begin(id), end(id), [&](int a, int b) { return A[a] > A[b]; }); // Sort the indexes in descending order of their corresponding values in `A`\n id.resize(k); // Only keep the first `k` indexes with the greatest `A` values\n sort(begin(id), end(id)); // Sort indexes in ascending order\n vector ans;\n for (int i : id) ans.push_back(A[i]);\n return ans;\n }\n};" }, { "title": "Minimum Operations to Make a Subsequence", "algo_input": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.\n\nIn one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.\n\nReturn the minimum number of operations needed to make target a subsequence of arr.\n\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n\n \nExample 1:\n\nInput: target = [5,1,3], arr = [9,4,2,3,4]\nOutput: 2\nExplanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.\n\n\nExample 2:\n\nInput: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= target.length, arr.length <= 105\n\t1 <= target[i], arr[i] <= 109\n\ttarget contains no duplicates.\n\n", "solution_py": "from bisect import bisect_left\nclass Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n dt = {num: i for i, num in enumerate(target)}\n stack = []\n for num in arr:\n if num not in dt: continue\n i = bisect_left(stack, dt[num])\n if i == len(stack):\n stack.append(dt[num])\n else:\n stack[i] = dt[num]\n return len(target) - len(stack)", "solution_js": "const minOperations = function (targets, arr) {\n const map = {};\n const n = targets.length;\n const m = arr.length;\n targets.forEach((target, i) => (map[target] = i));\n\n//map elements in arr to index found in targets array\n const arrIs = arr.map(el => {\n if (el in map) {\n return map[el];\n } else {\n return -1;\n }\n });\n\n//create a LIS table dp whose length is the longest increasing subsequence\n const dp = [];\n\n for (let i = 0; i < m; i++) {\n const curr = arrIs[i];\n if (curr === -1) continue;\n if (!dp.length || curr > dp[dp.length - 1]) {\n dp.push(curr);\n } else if (curr < dp[0]) {\n dp[0] = curr;\n } else {\n let l = 0;\n let r = dp.length;\n while (l < r) {\n const mid = Math.floor((l + r) / 2);\n if (arrIs[i] <= dp[mid]) {\n r = mid;\n } else {\n l = mid + 1;\n }\n }\n dp[r] = curr;\n }\n }\n return n-dp.length;\n};", "solution_java": "class Solution {\n public int minOperations(int[] target, int[] arr) {\n int n = target.length;\n Map map = new HashMap<>();\n\n for(int i = 0; i < n; i++) {\n map.put(target[i], i);\n }\n\n List array = new ArrayList<>();\n\n for(int i = 0; i < arr.length; i++) {\n if(!map.containsKey(arr[i])) {\n continue;\n }\n\n array.add(map.get(arr[i]));\n }\n\n int maxLen = 0;\n int[] tails = new int[n + 1];\n\n for(int i = 0; i < n; i++) {\n tails[i] = -1;\n }\n\n for(int num: array) {\n int index = findMinIndex(tails, maxLen, num);\n\n if(tails[index] == -1) {\n maxLen++;\n }\n tails[index] = num;\n }\n\n return n - maxLen;\n }\n\n public int findMinIndex(int[] tails, int n, int val) {\n int low = 0;\n int ans = n;\n int high = n - 1;\n\n while(low <= high) {\n int mid = (high + low) / 2;\n\n if(tails[mid] >= val) {\n ans = mid;\n high = mid - 1;\n }\n else {\n low = mid + 1;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector ans;\n \n void bin(int lo, int hi, int num) {\n if(lo == hi) {\n ans[lo] = num;\n return;\n }\n int mid = (lo + hi) / 2;\n if(ans[mid] < num) bin(mid + 1, hi, num);\n else bin(lo, mid, num);\n }\n \n int minOperations(vector& target, vector& arr) {\n unordered_map idx;\n for(int i = 0; i < target.size(); i++) {\n idx[target[i]] = i;\n }\n \n for(int i = 0; i < arr.size(); i++) {\n if(idx.find(arr[i]) == idx.end()) continue;\n int num = idx[arr[i]];\n if(ans.size() == 0 || num > ans.back()) {\n ans.push_back(num);\n }\n else {\n bin(0, ans.size() - 1, num);\n }\n }\n \n return (target.size() - ans.size());\n }\n};" }, { "title": "Ugly Number", "algo_input": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\n\nGiven an integer n, return true if n is an ugly number.\n\n \nExample 1:\n\nInput: n = 6\nOutput: true\nExplanation: 6 = 2 × 3\n\n\nExample 2:\n\nInput: n = 1\nOutput: true\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n\n\nExample 3:\n\nInput: n = 14\nOutput: false\nExplanation: 14 is not ugly since it includes the prime factor 7.\n\n\n \nConstraints:\n\n\n\t-231 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def isUgly(self, n: int) -> bool:\n if n == 0:\n return False\n res=[2, 3, 5]\n while n!= 1:\n for i in res:\n if n%i==0:\n n=n//i\n break\n else:\n return False\n return True", "solution_js": "var isUgly = function(n) {\n let condition = true;\n if(n == 0) // 0 has infinite factors. So checking if the number is 0 or not\n return false;\n while(condition){ //applying for true until 2, 3, 5 gets removed from the number\n if(n % 2 == 0)\n n = n / 2;\n else if(n % 3 == 0)\n n = n / 3;\n else if(n % 5 == 0)\n n = n / 5;\n else\n condition = false; //if the number doesnt have 2, 3, 5 in it anymore, this part will execute and will end the while loop\n }\n return n == 1 ? true : false;//checking if the number only had 2, 3, 5 in it or had something else in it as well\n};", "solution_java": "class Solution {\n public boolean isUgly(int n) {\n if(n==0) return false; //edge case\n while(n!=1){\n if(n%2==0){\n n=n/2;\n }\n else if(n%3==0){\n n=n/3;\n }\n else if(n%5==0){\n n=n/5;\n }\n else{\n return false;\n }\n }\n return true;\n\n }\n}", "solution_c": "class Solution {\npublic:\n bool isUgly(int n)\n {\n if (n <= 0) return false;\n int n1 = 0;\n while(n != n1)\n {\n n1 = n;\n if ((n % 2) == 0) n /= 2;\n if ((n % 3) == 0) n /= 3;\n if ((n % 5) == 0) n /= 5;\n }\n if (n < 7) return true;\n return false;\n }\n};" }, { "title": "Word Pattern", "algo_input": "Given a pattern and a string s, find if s follows the same pattern.\n\nHere follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.\n\n \nExample 1:\n\nInput: pattern = \"abba\", s = \"dog cat cat dog\"\nOutput: true\n\n\nExample 2:\n\nInput: pattern = \"abba\", s = \"dog cat cat fish\"\nOutput: false\n\n\nExample 3:\n\nInput: pattern = \"aaaa\", s = \"dog cat cat dog\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= pattern.length <= 300\n\tpattern contains only lower-case English letters.\n\t1 <= s.length <= 3000\n\ts contains only lowercase English letters and spaces ' '.\n\ts does not contain any leading or trailing spaces.\n\tAll the words in s are separated by a single space.\n\n", "solution_py": "class Solution(object):\n def wordPattern(self, pattern, s):\n \"\"\"\n :type pattern: str\n :type s: str\n :rtype: bool\n \"\"\"\n p, s = list(pattern), list(s.split(\" \"))\n\n return len(s) == len(p) and len(set(zip(p, s))) == len(set(s)) == len(set(p))", "solution_js": "var wordPattern = function(pattern, s) {\n let wordArray = s.split(\" \");\n if(wordArray.length !== pattern.length) return false;\n\n let hm = {};\n let hs = new Set();\n\n for(let index in pattern) {\n let word = wordArray[index];\n let char = pattern[index];\n\n if(hm[char] !== undefined) {\n if(hm[char] !== word) return false;\n } else {\n if(hs.has(word)) return false; // Duplicate Occurence of word on first occurrence of a char\n hm[char] = word;\n hs.add(word);\n }\n }\n\n return true;\n}", "solution_java": "class Solution {\n public boolean wordPattern(String pattern, String s) {\n String[] arr=s.split(\" \");\n if(pattern.length()!=arr.length) return false;\n Map map=new HashMap();\n \n for(int i=0;i processed_words;\n string m[26]; // char to string mapping\n\n bool crunch_next_word(char c, string word)\n {\n int idx = c-'a';\n if(m[idx].empty() && processed_words.count(word)==0)\n {\n m[idx] = word;\n processed_words.insert(word);\n return true;\n }\n else if(m[idx]==word) return true;\n else return false;\n }\n\n bool wordPattern(string pattern, string s)\n {\n int count = 0;\n\n int start = 0;\n int end = s.find(' ');\n while (end != -1)\n {\n string word = s.substr(start, end - start);\n char c = pattern[count];\n if(!crunch_next_word(c,word)) return false;\n\n start = end + 1;\n end = s.find(' ', start);\n count++;\n if(count == pattern.length()) return false;\n }\n if(count != pattern.length()-1) return false;\n string word = s.substr(start, end - start);\n char c = pattern[count];\n if(!crunch_next_word(c,word)) return false;\n return true;\n }\n};" }, { "title": "House Robber", "algo_input": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.\n\n \nExample 1:\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\nExample 2:\n\nInput: nums = [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t0 <= nums[i] <= 400\n\n", "solution_py": "class Solution:\n def rob(self, nums: List[int]) -> int:\n # [rob1,rob2,n,n+1]\n # 1 | 2 | 3 | 1 \n #index 0 1 2 3\n # so upto last index it depends on previous 2 values :\n # here upto 2nd index max rob is 1+3=4; not choosing adjacent element 2\n # and upto 1st index max rob is 2 ; not choosing any adjacent elements\n # so at 3rd index it depend on prev rob value and 1st index rob value+last value\n # i.e max(2+(val at last index),4)\n rob1=0;rob2=0;\n for i in nums:\n temp=max(rob1+i,rob2);\n rob1=rob2;\n rob2=temp;\n return rob2;", "solution_js": "const max=(x,y)=>x>y?x:y\nvar rob = function(nums) {\n if(nums.length==1) return(nums[0]);\n let temp=[]\n temp[0]=nums[0];\n temp[1]=max(nums[0],nums[1]);\n\n for(let i =2;i=nums.length){\n return 0;\n }\n if(i==nums.length-1){\n return nums[i];\n }\n if(t[i] != -1){\n return t[i];\n }\n\n int pick = nums[i] + helper(nums,i+2,t);\n int unpicked = helper(nums,i+1,t);\n t[i] = Math.max(pick,unpicked);\n return t[i];\n\n }\n}", "solution_c": "class Solution {\npublic:\n int helper(int i, vector& nums) {\n if(i == 0) return nums[i];\n if(i < 0) return 0;\n\n int pick = nums[i] + helper(i-2, nums);\n int not_pick = 0 + helper(i-1, nums);\n\n return max(pick,not_pick);\n }\n int rob(vector& nums) {\n return helper(nums.size()-1, nums);\n }\n};" }, { "title": "Integer to English Words", "algo_input": "Convert a non-negative integer num to its English words representation.\n\n \nExample 1:\n\nInput: num = 123\nOutput: \"One Hundred Twenty Three\"\n\n\nExample 2:\n\nInput: num = 12345\nOutput: \"Twelve Thousand Three Hundred Forty Five\"\n\n\nExample 3:\n\nInput: num = 1234567\nOutput: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n\n\n \nConstraints:\n\n\n\t0 <= num <= 231 - 1\n\n", "solution_py": "class Solution:\n def numberToWords(self, num: int) -> str:\n \n if num == 0:\n return \"Zero\"\n \n dic1 = {1000000000: \"Billion\", 1000000: \"Million\", 1000: \"Thousand\", 1: \"\"}\n dic2 = {90: \"Ninety\", 80: \"Eighty\", 70: \"Seventy\", 60: \"Sixty\", 50: \"Fifty\", 40: \"Forty\", 30: \"Thirty\", 20: \"Twenty\", 19: 'Nineteen', 18: \"Eighteen\", 17: \"Seventeen\", 16: \"Sixteen\", 15: \"Fifteen\", 14: \"Fourteen\", 13: \"Thirteen\", 12: \"Twelve\", 11: \"Eleven\", 10: \"Ten\", 9: \"Nine\", 8: \"Eight\", 7: \"Seven\", 6: \"Six\", 5: \"Five\", 4: \"Four\", 3: \"Three\", 2: \"Two\", 1: \"One\"}\n \n def construct_num(num):\n ans = ''\n d, num = divmod(num, 100)\n if d > 0:\n ans += dic2[d] + \" \" + \"Hundred\"\n for k, v in dic2.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + v\n return ans.lstrip() \n \n ans = \"\"\n for k, v in dic1.items():\n d, num = divmod(num, k)\n if d > 0:\n ans += \" \" + construct_num(d) + \" \" + v\n \n return ans.strip()", "solution_js": "let numberMap = {\n\t0: 'Zero',\n 100: 'Hundred',\n 1: 'One',\n 2: 'Two',\n 3: 'Three',\n 4: 'Four',\n 5: 'Five',\n 6: 'Six',\n 7: 'Seven',\n 8: 'Eight',\n 9: 'Nine',\n 10: 'Ten',\n 11: 'Eleven',\n 12: 'Twelve',\n 13: 'Thirteen',\n 14: 'Fourteen',\n 15: 'Fifteen',\n 16: 'Sixteen',\n 17: 'Seventeen',\n 18: 'Eighteen',\n 19: 'Nineteen',\n 20: 'Twenty',\n 30: 'Thirty',\n 40: 'Forty',\n 50: 'Fifty',\n 60: 'Sixty',\n 70: 'Seventy',\n 80: 'Eighty',\n 90: 'Ninety'\n};\n\nlet bigNumberMap = {\n\t1000000000: 'Billion',\n 1000000: 'Million',\n 1000: 'Thousand',\n 1: 'One'\n}\n\nlet bases = [];\n\nfor (let base in numberMap) {\n\tbases.push(parseInt(base, 10));\n}\nbases = bases.sort((a,b) => b-a);\n\nlet bigBases = [];\nfor (let base in bigNumberMap) {\n\tbigBases.push(parseInt(base, 10));\n}\nbigBases = bigBases.sort((a,b) => b-a);\n\nvar numberToWords = function(num) {\n let res = '';\n if (num === 0) return numberMap[num];\n \tbigBases.forEach((base) => {\n \tbase = parseInt(base, 10);\n let baseAsString = base + '';\n let nums = num/base << 0;\n let remainder = num - nums * base;\n if (nums >= 1) {\n \t\t[res, nums] = getForHundredBase(res, nums);\n res += baseAsString.length > 1 ? (' ' + bigNumberMap[base + '']) : '';\n num = remainder;\n }\n });\n return res;\n};\n\nfunction getForHundredBase(res, num) {\n\t\tbases.forEach((base) => {\n \tbase = parseInt(base, 10);\n \t[num, res] = getNums(num, base, res);\n });\n return [res, num];\n}\n\nfunction getNums(num, base, res) {\n\tlet nums = num / base << 0;\n let baseAsString = base + '';\n if (nums > 1 || (nums == 1 && baseAsString.length > 2)) {\n \tres += res === '' ? res : \" \";\n \tres += numberMap[nums] + \" \" + numberMap[baseAsString];\n } else if (nums == 1) {\n \tres += res === '' ? res : \" \";\n \tres += numberMap[baseAsString];\n }\n return [num - (nums * base), res];\n}", "solution_java": "class Solution {\n \n private static final int[] INT_NUMBERS = {\n 1_000_000_000, 1_000_000, 1000, 100, 90, 80, 70, 60, 50, 40, 30, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};\n private static final String[] STRING_NUMBERS = {\n \"Billion\", \"Million\", \"Thousand\", \"Hundred\", \"Ninety\", \"Eighty\", \"Seventy\", \"Sixty\", \"Fifty\", \"Forty\", \"Thirty\", \"Twenty\",\n \"Nineteen\", \"Eighteen\", \"Seventeen\", \"Sixteen\", \"Fifteen\", \"Fourteen\", \"Thirteen\", \"Twelve\", \"Eleven\", \"Ten\",\n \"Nine\", \"Eight\", \"Seven\", \"Six\", \"Five\", \"Four\", \"Three\", \"Two\", \"One\"};\n\n public String numberToWords(int num) {\n if (num == 0) return \"Zero\";\n return numberToWordsHelper(num).toString();\n }\n\n private StringBuilder numberToWordsHelper(int num) {\n StringBuilder sb = new StringBuilder();\n if (num == 0) return sb;\n for (int i = 0; i < INT_NUMBERS.length; i++) {\n if (num >= INT_NUMBERS[i]) {\n if (num >= 100) {\n sb.append(numberToWordsHelper(num / INT_NUMBERS[i]).append(\" \"));\n }\n\n sb.append(STRING_NUMBERS[i]).append(\" \").append(numberToWordsHelper(num % INT_NUMBERS[i]));\n break;\n }\n }\n return sb.charAt(sb.length() - 1) == ' ' ? sb.deleteCharAt(sb.length() - 1) : sb; // trim\n }\n \n}", "solution_c": "unordered_map mp_0 = {{1, \"One \"},{2, \"Two \"},{3, \"Three \"},{4, \"Four \"}, {5, \"Five \"},{6, \"Six \"},{7, \"Seven \"},{8, \"Eight \"},{9, \"Nine \"}, {10, \"Ten \"},{11,\"Eleven \"},{12, \"Twelve \"},{13, \"Thirteen \"},{14, \"Fourteen \"},{15, \"Fifteen \"},{16, \"Sixteen \"},{17, \"Seventeen \"},{18, \"Eighteen \"},{19, \"Nineteen \"}};\n \nunordered_map mp_10 = {{20, \"Twenty \"},{30, \"Thirty \"},{40 , \"Forty \"},{50, \"Fifty \"},{60, \"Sixty \"},{70, \"Seventy \"},{80, \"Eighty \"},{90, \"Ninety \"}};\n\nclass Solution {\n \n void Solve2(string &ans , int num)\n {\n ans = mp_0[num] + ans;\n }\n \n void Solve( string &ans, int num)\n {\n int factor = 1;\n for(int i = 0 ; num>0 ; i++)\n {\n if(factor == 1)\n {\n \n if(num%100 < 20)\n {\n Solve2(ans, num%100);\n factor = factor*10;\n num = num/10;\n }\n else\n {\n if(num%10 !=0)\n ans = mp_0[num%10] + ans; \n }\n }\n \n else if(factor == 10)\n {\n if(num%10 != 0)\n ans = mp_10[(num%10)*10] + ans; \n }\n \n else if(factor == 100)\n {\n if(num%10 != 0)\n ans = (mp_0[num%10] + \"Hundred \") + ans; \n }\n \n factor = factor*10;\n num = num/10;\n }\n }\npublic:\n string numberToWords(int num) {\n //2,147,483,647\n \n if(num == 0)\n return \"Zero\";\n \n string ans ;\n \n \n for(int i = 0 ; num>0 ; i++)\n { \n if(i == 1) \n { \n if(num%1000>0)\n ans = \"Thousand \"+ ans;\n }\n else if(i == 2)\n { \n if(num%1000>0)\n ans = \"Million \"+ ans;\n }\n else if( i == 3)\n ans = \"Billion \"+ ans;\n \n Solve(ans, num%1000);\n num = num/1000;\n \n }\n ans.pop_back();\n return ans;\n \n \n }\n};" }, { "title": "Calculate Money in Leetcode Bank", "algo_input": "Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.\n\nHe starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday. \n\nGiven n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.\n\n \nExample 1:\n\nInput: n = 4\nOutput: 10\nExplanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\n\n\nExample 2:\n\nInput: n = 10\nOutput: 37\nExplanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\n\n\nExample 3:\n\nInput: n = 20\nOutput: 96\nExplanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\n", "solution_py": "from itertools import cycle, \\\n repeat, \\\n starmap\nfrom operator import floordiv\n\n\nclass Solution:\n def totalMoney(self, n: int) -> int:\n return sum(starmap(add,zip(\n starmap(floordiv, zip(range(n), repeat(7, n))),\n cycle((1,2,3,4,5,6,7))\n )))", "solution_js": "var totalMoney = function(n) {\n let min = 1;\n let days = 7;\n let total = 0;\n let inc = 1;\n for (let i = 0; i < n; i++) {\n if (days !== 0) {\n total += min;\n min++;\n days--;\n } else {\n inc++;\n min = inc\n days = 7;\n i--;\n }\n }\n return total;\n};", "solution_java": "class Solution {\n public int totalMoney(int n) {\n int m=n/7; //(no.of full weeks)\n // first week 1 2 3 4 5 6 7 (sum is 28 i.e. 7*(i+3) if i=1)\n // second week 2 3 4 5 6 7 8 (sum is 35 i.e. 7*(i+3) if i=2)\n //.... so on\n int res=0; //for result\n //calculating full weeks\n for(int i=1;i<=m;i++){\n res+=7*(i+3);\n }\n //calculating left days\n for(int i=7*m;i int:\n nums = [1] + nums + [1]\n length = len(nums)\n dp = [[None]*(length+1) for i in range(length+1)]\n \n @cache\n def dfs(l,r):\n if l>r: return 0\n if dp[l][r] is not None: return dp[l][r]\n dp[l][r] = 0\n for i in range(l,r+1):\n coins = dfs(l, i-1) + dfs(i+1, r) + nums[l-1]*nums[i]*nums[r+1]\n dp[l][r] = max(dp[l][r], coins)\n return dp[l][r]\n return dfs(1, length-2)", "solution_js": "var rec = function(i,j,arr,dp){\n if(i>j)return 0;\n if(dp[i][j] !== -1)return dp[i][j];\n let max = Number.MIN_VALUE;\n for(let k=i;k<=j;k++){\n let cost = arr[i-1] * arr[k] * arr[j+1] + rec(i,k-1,arr,dp)+rec(k+1,j,arr,dp);\n if(cost>max){\n max = cost\n }\n }\n return dp[i][j] = max\n}\nvar maxCoins = function(nums) {\n let n = nums.length;\n let sol = [];\n for(let i=0;i j) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n \n int max = Integer.MIN_VALUE;\n for(int n = i; n <= j; n++){\n int coins = a[i-1] * a[n] * a[j+1] + f(i, n-1, a, dp) + f(n+1, j, a, dp);\n max = Math.max(max, coins);\n }\n return dp[i][j] = max;\n }\n}\n\n// Time Complexity: O(N * N * N) ~ O(N^3);\n// Space Complexity: O(N^2) + O(N);", "solution_c": "class Solution {\npublic:\n //topDown+memoization\n int solve(int i,int j,vector& nums,vector>& dp){\n if(i>j) return 0;\n if(dp[i][j]!=-1) return dp[i][j];\n \n int maxcost = INT_MIN;\n for(int k = i;k<=j;k++){\n int cost = nums[i-1]*nums[k]*nums[j+1]+solve(i,k-1,nums,dp)+solve(k+1,j,nums,dp);\n maxcost = max(maxcost,cost);\n }\n return dp[i][j] = maxcost;\n }\n \n int maxCoins(vector& nums) {\n nums.insert(nums.begin(),1);\n nums.push_back(1);\n int n = nums.size();\n vector> dp(n+1,vector(n+1,-1));\n return solve(1,n-2,nums,dp);\n }\n \n //bottomUp dp\n int maxCoins(vector& nums) {\n //including the nums[-1] == 1 and nums[n] == 1\n int n = nums.size();\n nums.insert(nums.begin(),1);\n nums.push_back(1);\n vector> dp(nums.size()+1,vector(nums.size()+1,0));\n \n for (int len = 1; len <= n; ++len)\n for (int left = 1; left <= n - len + 1; ++left) {\n int right = left + len - 1;\n for (int k = left; k <= right; ++k)\n dp[left][right] = max(dp[left][right], nums[left-1]*nums[k]*nums[right+1] + dp[left][k-1] + dp[k+1][right]);\n }\n return dp[1][n];\n }\n};" }, { "title": "Count Elements With Strictly Smaller and Greater Elements", "algo_input": "Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.\n\n \nExample 1:\n\nInput: nums = [11,7,2,15]\nOutput: 2\nExplanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n\n\nExample 2:\n\nInput: nums = [-3,3,3,90]\nOutput: 2\nExplanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t-105 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def countElements(self, nums: List[int]) -> int:\n M = max(nums)\n m = min(nums)\n return sum(1 for i in nums if m a-b).slice(1, newNums.length-1).forEach(num => total += map[num]);\n\n // return total variable\n return total;\n};", "solution_java": "class Solution {\n public int countElements(int[] nums) {\n int nmin=Integer.MAX_VALUE;\n int nmax=Integer.MIN_VALUE;\n for(int a:nums)\n {\n nmin=Math.min(a,nmin);\n nmax=Math.max(a,nmax);\n }\n int count=0;\n for(int a:nums)\n {\n if(a>nmin && a& nums) {\n int M = *max_element(nums.begin(), nums.end()); \n int m = *min_element(nums.begin(), nums.end()); \n int res = 0;\n for(int i = 0; i < nums.size(); i++){\n if(nums[i] > m && nums[i] < M) res++;\n }\n return res;\n }\n};" }, { "title": "Redundant Connection", "algo_input": "In this problem, a tree is an undirected graph that is connected and has no cycles.\n\nYou are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.\n\nReturn an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.\n\n \nExample 1:\n\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\n\nExample 2:\n\nInput: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput: [1,4]\n\n\n \nConstraints:\n\n\n\tn == edges.length\n\t3 <= n <= 1000\n\tedges[i].length == 2\n\t1 <= ai < bi <= edges.length\n\tai != bi\n\tThere are no repeated edges.\n\tThe given graph is connected.\n\n", "solution_py": "class UnionFind:\n \n def __init__(self, size):\n \n self.parent = [-1 for _ in range(size)]\n self.rank = [-1 for _ in range(size)]\n \n def find(self, i):\n \n if self.parent[i] == -1:\n return i\n \n k = self.find(self.parent[i])\n self.parent[i] = k\n return k\n \n def union(self, x, y):\n \n x = self.find(x)\n y = self.find(y)\n \n if x == y:\n return -1\n else:\n \n if self.rank[x] > self.rank[y]:\n self.parent[y] = x\n \n elif self.rank[x] < self.rank[y]:\n self.parent[x] = y\n \n else:\n self.rank[x] += 1\n self.parent[y] = x\n\nclass Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n \n vertex_set = set()\n \n for edge in edges:\n vertex_set.add(edge[0])\n vertex_set.add(edge[1])\n \n \n union_find = UnionFind(len(vertex_set))\n \n for edge in edges:\n \n new_edge = [edge[0]-1, edge[1]-1]\n \n if union_find.union(new_edge[0], new_edge[1]) == -1:\n return edge\n \n return []", "solution_js": "var findRedundantConnection = function(edges) {\n const root = [];\n const find = (index) => {\n const next = root[index];\n return next ? find(next) : index;\n };\n\n for (const [a, b] of edges) {\n const x = find(a);\n const y = find(b);\n\n if (x === y) return [a, b];\n root[x] = y;\n }\n};", "solution_java": "class Solution {\n public int[] findRedundantConnection(int[][] edges) {\n UnionFind uf = new UnionFind(edges.length);\n for (int[] edge : edges) {\n if (!uf.union(edge[0], edge[1])) {\n return new int[]{edge[0], edge[1]};\n }\n }\n return null;\n }\n\n private class UnionFind {\n int[] rank;\n int[] root;\n\n UnionFind(int n) {\n rank = new int[n + 1];\n root = new int[n + 1];\n for (int i = 1; i <= n; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n int find(int x) {\n if (x == root[x]) {\n return x;\n }\n return root[x] = find(root[x]);\n }\n\n boolean union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = root[rootX];\n } else if (rank[rootY] > rank[rootX]) {\n root[rootX] = root[rootY];\n } else {\n root[rootY] = root[rootX];\n rank[rootX]++;\n }\n return true;\n }\n return false;\n }\n }\n}", "solution_c": "class UnionFind {\n public:\n\n int* parent;\n int* rank;\n\n UnionFind(int n){\n rank = new int[n];\n parent = new int[n];\n\n for(int i=0; i findRedundantConnection(vector>& edges) {\n UnionFind UF = UnionFind(1001);\n\n for(vector& edge : edges){\n int u = edge[0];\n int v = edge[1];\n\n // if adding this edge creates a cycle\n if(UF.Find(u) == UF.Find(v)){\n return {u,v};\n }\n\n // add u and v to the same set\n UF.Union(u,v);\n }\n\n // if no cycle was found\n return {-1};\n }\n};" }, { "title": "Knight Dialer", "algo_input": "The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagaram:\n\nA chess knight can move as indicated in the chess diagram below:\n\nWe have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).\n\nGiven an integer n, return how many distinct phone numbers of length n we can dial.\n\nYou are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.\n\nAs the answer may be very large, return the answer modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 10\nExplanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 20\nExplanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\n\n\nExample 3:\n\nInput: n = 3131\nOutput: 136006598\nExplanation: Please take care of the mod.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 5000\n\n", "solution_py": "class Solution:\n def knightDialer(self, n: int) -> int:\n # Sum elements of matrix modulo mod subroutine\n def sum_mat(matrix, mod):\n return sum(sum(row) % mod for row in matrix) % mod\n \n # Matrix multiplication subroutine\n def mult_mat(a, b):\n return [[sum(a[i][k]*b[k][j] for k in range(10)) for j in range(10)] for i in range(10)]\n \n # Matrix exponentiation subroutine\n def pow_mat(matrix, k, dp):\n if k not in dp:\n if k == 0:\n dp[k] = [[(1 if i == j else 0) for j in range(10)] for i in range(10)]\n else:\n dp[k] = pow_mat(matrix, k//2, dp)\n dp[k] = mult_mat(dp[k], dp[k])\n if k % 2:\n dp[k] = mult_mat(dp[k], matrix)\n return dp[k]\n \n # Create matrix\n edges = [(1, 6), (1, 8), (2, 9), (2, 7), (3, 4), (3, 8), (4, 0), (4, 9), (6, 1), (6, 0), (6, 7)]\n matrix = [[0 for j in range(10)] for i in range(10)]\n for i, j in edges:\n matrix[i][j] = 1\n matrix[j][i] = 1\n \n\t\t# Solve\n mod = 10**9 + 7\n return sum_mat(pow_mat(matrix, n-1, {}), mod)", "solution_js": "var knightDialer = function(n) {\n\n let dp = Array(10).fill(1)\n let MOD = 10**9 + 7\n\n for(let i = 2; i <= n ; i++) {\n oldDp = [...dp]\n dp[0] = (oldDp[4] + oldDp[6]) % MOD\n dp[1] = (oldDp[8] + oldDp[6]) % MOD\n dp[2] = (oldDp[9] + oldDp[7]) % MOD\n dp[3] = (oldDp[8] + oldDp[4]) % MOD\n dp[4] = (oldDp[3] + oldDp[9] + oldDp[0]) % MOD\n dp[5] = 0\n dp[6] = (oldDp[0] + oldDp[7] + oldDp[1]) % MOD\n dp[7] = (oldDp[6] + oldDp[2]) % MOD\n dp[8] = (oldDp[3] + oldDp[1]) % MOD\n dp[9] = (oldDp[4] + oldDp[2]) % MOD\n }\n\n return dp.reduce((ans, ele) => ans += ele, 0) % MOD\n};", "solution_java": "class Solution {\n public int knightDialer(int n) {\n var dp = new long[10];\n var tmp = new long[10];\n Arrays.fill(dp, 1);\n for (int i = 1; i < n; i++) {\n tmp[1] = dp[6]+dp[8];\n tmp[2] = dp[7]+dp[9];\n tmp[3] = dp[4]+dp[8];\n tmp[4] = dp[0]+dp[3]+dp[9];\n tmp[5] = 0;\n tmp[6] = dp[0]+dp[1]+dp[7];\n tmp[7] = dp[2]+dp[6];\n tmp[8] = dp[1]+dp[3];\n tmp[9] = dp[2]+dp[4];\n tmp[0] = dp[4]+dp[6];\n for (int j = 0; j < 10; j++) tmp[j] = tmp[j] % 1000000007;\n var arr = dp;\n dp = tmp;\n tmp = arr;\n }\n long res = 0;\n for (int i = 0; i < 10; i++) {\n res = (res+dp[i]) % 1000000007;\n }\n return (int)res;\n }\n}", "solution_c": "class Solution {\n int MOD=1e9+7;\npublic:\n int knightDialer(int n) {\n if(n==1) return 10;\n int a=2, b=2, c=3, d=2; //a{2,8} b{1,3,7,9} c{4,6} d{0}\n for(int i=3; i<=n; i++){\n int w, x, y, z;\n w = 2ll*b%MOD;\n x = (1ll*a + 1ll*c)%MOD;\n y = (2ll*b + 1ll*d)%MOD;\n z = 2ll*c%MOD;\n a = w; b = x; c = y; d = z;\n }\n int ans = (2ll*a + 4ll*b + 2ll*c + d)%MOD;\n return ans;\n }\n};" }, { "title": "Find the Longest Substring Containing Vowels in Even Counts", "algo_input": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n\n \nExample 1:\n\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\n\nExample 2:\n\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\n\n\nExample 3:\n\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 x 10^5\n\ts contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n integrals = [(False, False, False, False, False)] # integrals[10][mapping[\"a\"]] == False means we have seen \"a\" appears even times before index 10\n mapping = {\n \"a\": 0,\n \"i\": 1,\n \"u\": 2,\n \"e\": 3,\n \"o\": 4\n }\n\n for v in s:\n vector = list(integrals[-1])\n if v in mapping: # if v is a vowel\n vector[mapping[v]] = not vector[mapping[v]] # toggle that dimension, because if v had appeared even times before, it becomes odd times now\n integrals.append(tuple(vector))\n\n seen = {}\n res = 0\n\n for i, v in enumerate(integrals):\n if v in seen: # we have seen this vector before\n res = max(res, i - seen[v]) # compare its substring length\n else:\n seen[v] = i # just record the first time each vector appears\n\n return res", "solution_js": "var findTheLongestSubstring = function(s) {\n // u o i e a\n // 0 0 0 0 0 => initial state, all are even letters\n // s = \"abcab\"\n // 0 0 0 0 1 => at index 0, only a is odd count\n // 0 0 0 0 1 => at index 1, max = 1\n // 0 0 0 0 1 => at index 2, max = 2\n // 0 0 0 0 0 => at index 3, max = 4\n // 0 0 0 0 0 => at index 4, max = 5\n\n // valid condition: same state in previous index, then it means we have a even count for all letters within the middle substring.\n var mask = 0;\n var t = \"aeiou\";\n var count = new Map(); // \n count.set(0,-1);\n var res = 0;\n for(var i = 0; i=0)\n {\n var j = t.indexOf(s[i]);\n mask = mask ^ (1 << j);\n }\n if(!count.has(mask))\n {\n count.set(mask,i);\n }\n else\n {\n // substring is from [prevIdx+1, i];\n res = Math.max(res, i - count.get(mask));\n }\n }\n return res;\n};", "solution_java": "class Solution {\n public int findTheLongestSubstring(String s) {\n int res = 0 , mask = 0, n = s.length();\n HashMap seen = new HashMap<>();// key--> Mask, value--> Index\n seen.put(0, -1);\n for (int i = 0; i < n; ++i) {\n if(s.charAt(i)=='a' || s.charAt(i)=='e' || s.charAt(i)=='i' || s.charAt(i)=='o' || s.charAt(i)=='u'){ // check only vowels and skip consonant\n int c=s.charAt(i);\n mask=mask ^ c;\n seen.putIfAbsent(mask, i);\n } \n res = Math.max(res, i - seen.get(mask));\n }\n return res;\n }\n}", "solution_c": "//When the xor of all the even times numbers are done it results in 0. The xor of the vowels are done by indicating\n//them with a single digit and the xor value is stored in a map\nclass Solution {\npublic:\n int findTheLongestSubstring(string s) {\n int x= 0;\n unordered_mapmp;\n mp[0]=-1;\n int n=0;\n for(int i=0;i List[List[int]]:\n mix, res, last_i = DefaultDict(int), [], 0\n for start, end, color in segments:\n mix[start] += color\n mix[end] -= color\n for i in sorted(mix.keys()):\n if last_i in mix and mix[last_i]:\n res.append([last_i, i, mix[last_i]])\n mix[i] += mix[last_i]\n last_i = i\n return res", "solution_js": "/**\n * @param {number[][]} segments\n * @return {number[][]}\n */\nvar splitPainting = function(segments) {\n const arr = [];\n segments.forEach(([start, end, val])=>{\n arr.push([start, val]);\n arr.push([end, -val]);\n });\n arr.sort((i,j)=>i[0]-j[0]);\n\n const ans = [];\n let currVal = 0, prevTime;\n arr.forEach(([time, val])=>{\n if(prevTime !== undefined && currVal && prevTime !== time) ans.push([prevTime, time, currVal]);\n currVal += val;\n prevTime = time;\n })\n\n return ans;\n};", "solution_java": "class Solution {\n //class for segments \n class Seg{\n int val,end;\n int color;\n boolean isStart;\n public Seg(int val,int end,int color, boolean isStart){\n this.val = val;\n this.end = end;\n this.color = color;\n this.isStart = isStart; \n }\n public String toString(){\n return \"[\" + val+\" \"+end+\" \"+color+\" \"+isStart+\"]\";\n }\n }\n public List> splitPainting(int[][] segments) {\n List> res = new ArrayList();\n \n List list = new ArrayList();\n \n //making a list of segments\n for(int[] segment : segments){\n list.add(new Seg(segment[0],segment[1],segment[2],true));\n list.add(new Seg(segment[1],segment[1],segment[2],false)); \n }\n \n //Sorting the segments\n Collections.sort(list,(a,b)->{return a.val-b.val;});\n \n //System.out.println(list);\n \n //Iterating over list to combine the elements\n for(Seg curr: list){\n int len = res.size();\n if(curr.isStart){\n //if the segment is starting there could be three ways \n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if starting point of two things is same\n List temp = res.get(len-1);\n temp.set(1,Math.max(temp.get(1),curr.end));\n temp.set(2,(long)(temp.get(2)+curr.color));\n }else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a start in between create a new segment of different color \n List prev = res.get(len-1);\n prev.set(1,(long)curr.val);\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)(prev.get(2)+curr.color));\n res.add(temp);\n }else{\n //Add a new value if nothing is present in result\n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)curr.end); temp.add((long)curr.color);\n res.add(temp);\n }\n }else{\n if(res.size()>0 && res.get(len-1).get(0)==curr.val){\n //if ending point of 2 segments is same\n Long prevColor = res.get(len-1).get(2);\n res.get(len-1).set(2,(long)(prevColor-curr.color));\n }\n else if(res.size()>0 && res.get(len-1).get(1)>curr.val){\n //if there is a ending in between create a new segment of different color \n Long prevColor = res.get(len-1).get(2);\n Long prevEnd = res.get(len-1).get(1);\n res.get(len-1).set(1,(long)curr.val);\n \n List temp = new ArrayList();\n temp.add((long)curr.val); temp.add((long)prevEnd); temp.add((long)(prevColor-curr.color));\n res.add(temp);\n }\n }\n //System.out.println(res+\" \"+curr);\n \n }\n //System.out.println(res);\n return res; \n \n }\n}", "solution_c": "typedef long long ll;\n\nclass Solution {\npublic:\n vector> splitPainting(vector>& segments) {\n vector > ans;\n map um;\n \n for(auto s : segments){\n um[s[0]] += s[2];\n um[s[1]] -= s[2];\n }\n bool flag = false;\n pair prev;\n ll curr = 0;\n \n for(auto x : um){\n if(flag == false){\n prev = x;\n curr += x.second;\n flag = true;\n continue;\n }\n \n vector v = {prev.first,x.first,curr};\n prev = x;\n if(curr)\n ans.push_back(v);\n curr += x.second;\n \n }\n return ans;\n }\n};" }, { "title": "Substring With Largest Variance", "algo_input": "The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.\n\nGiven a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"aababbb\"\nOutput: 3\nExplanation:\nAll possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings \"a\", \"aa\", \"ab\", \"abab\", \"aababb\", \"ba\", \"b\", \"bb\", and \"bbb\".\n- Variance 1 for substrings \"aab\", \"aba\", \"abb\", \"aabab\", \"ababb\", \"aababbb\", and \"bab\".\n- Variance 2 for substrings \"aaba\", \"ababbb\", \"abbb\", and \"babb\".\n- Variance 3 for substring \"babbb\".\nSince the largest possible variance is 3, we return it.\n\n\nExample 2:\n\nInput: s = \"abcde\"\nOutput: 0\nExplanation:\nNo letter occurs more than once in s, so the variance of every substring is 0.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n class Solution:\n def largestVariance(self, s: str) -> int:\n \n def maxSubArray(nums: List[int]):\n ans=-float('inf')\n runningSum=0\n seen=False\n for x in (nums):\n if x<0:\n seen=True\n runningSum+=x\n if seen:\n ans=max(ans,runningSum)\n else:\n ans=max(ans,runningSum-1)\n if runningSum<0:\n runningSum=0\n seen=False\n return ans\n \n f=set()\n a=''\n for x in s:\n if x not in f:\n a+=x\n f.add(x)\n \n n=len(s)\n res=0\n for j in range(len(a)-1):\n for k in range(j+1,len(a)):\n x=a[j]\n y=a[k]\n arr=[]\n for i in range(n):\n if s[i]!=x and s[i]!=y:\n continue\n elif s[i]==x:\n arr.append(1)\n else:\n arr.append(-1)\n \n res=max(res,maxSubArray(arr),maxSubArray([-x for x in arr]))\n \n return res\n \n \n \n ", "solution_js": "var largestVariance = function(s) {\n let chars = new Set(s.split(\"\")), maxDiff = 0;\n for (let l of chars) {\n for (let r of chars) {\n if (l === r) continue;\n let lCount = 0, rCount = 0, hasRight = false;\n for (let char of s) {\n lCount += char === l ? 1 : 0;\n rCount += char === r ? 1 : 0;\n if (rCount > 0 && lCount > rCount) { // has both characters and positive difference\n maxDiff = Math.max(maxDiff, lCount - rCount);\n }\n if (lCount > rCount && hasRight) { // has positive difference and a previous \"right\" character we can add to the start\n maxDiff = Math.max(maxDiff, lCount - rCount - 1);\n }\n if (lCount < rCount) {\n lCount = 0, rCount = 0;\n hasRight = true;\n }\n }\n }\n }\n return maxDiff;\n};", "solution_java": "class Solution {\n public int largestVariance(String s) {\n \n int [] freq = new int[26];\n for(int i = 0 ; i < s.length() ; i++)\n freq[(int)(s.charAt(i) - 'a')]++;\n \n int maxVariance = 0;\n for(int a = 0 ; a < 26 ; a++){\n for(int b = 0 ; b < 26 ; b++){\n int remainingA = freq[a];\n int remainingB = freq[b];\n if(a == b || remainingA == 0 || remainingB == 0) continue;\n \n\t\t\t\t// run kadanes on each possible character pairs (A & B)\n int currBFreq = 0, currAFreq = 0;\n for(int i = 0 ; i < s.length() ; i++){\n int c = (int)(s.charAt(i) - 'a');\n \n if(c == b) currBFreq++;\n if(c == a) {\n currAFreq++;\n remainingA--;\n }\n \n if(currAFreq > 0)\n maxVariance = Math.max(maxVariance, currBFreq - currAFreq);\n \n if(currBFreq < currAFreq && remainingA >= 1){\n currBFreq = 0;\n currAFreq = 0;\n }\n }\n }\n }\n \n return maxVariance;\n }\n}", "solution_c": "/*\n Time: O(26*26*n)\n Space: O(1)\n Tag: Kadane's Algorithm\n Difficulty: H (Logic) | E(Implementation)\n*/\n\nclass Solution {\npublic:\n int largestVariance(string s) {\n int res = 0;\n for (int i = 0; i < 26; i++) {\n for (int j = 0; j < 26; j++) {\n if (i == j) continue;\n int highFreq = 0;\n int lowFreq = 0;\n bool prevHadLowFreqChar = false;\n for (char ch : s) {\n if (ch - 'a' == i)\n highFreq++;\n else if (ch - 'a' == j)\n lowFreq++;\n if (lowFreq > 0)\n res = max(res, highFreq - lowFreq);\n else if (prevHadLowFreqChar)\n res = max(res, highFreq - 1);\n if (highFreq - lowFreq < 0) {\n highFreq = 0;\n lowFreq = 0;\n prevHadLowFreqChar = true;\n }\n }\n }\n }\n return res;\n }\n};" }, { "title": "Rectangle Area", "algo_input": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.\n\nThe first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).\n\nThe second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).\n\n \nExample 1:\n\nInput: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput: 45\n\n\nExample 2:\n\nInput: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput: 16\n\n\n \nConstraints:\n\n\n\t-104 <= ax1 <= ax2 <= 104\n\t-104 <= ay1 <= ay2 <= 104\n\t-104 <= bx1 <= bx2 <= 104\n\t-104 <= by1 <= by2 <= 104\n\n", "solution_py": "class Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n def segment(ax1,ax2,bx1,bx2):\n return min(ax2,bx2) - max(ax1, bx1) if max(ax1, bx1) < min(ax2, bx2) else 0\n return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - segment(ax1,ax2,bx1,bx2)*segment(ay1,ay2,by1,by2)", "solution_js": "var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {\n let area1 = (ax2-ax1)*(ay2-ay1)\n let area2 = (bx2-bx1)*(by2-by1)\n let overlap = (by1>ay2 || by2ax2 || bx2 x1 && y2 > y1){\n int overlap = (x2-x1)*(y2-y1);\n area = area - overlap;\n }\n\n return area;\n }\n}", "solution_c": "class Solution {\npublic:\n int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {\n int rec1=abs(ax2-ax1)*abs(ay2-ay1); //Area(Rectangle 1)\n int rec2=abs(bx2-bx1)*abs(by2-by1); //Area(Rectangle 2)\n\n //As explained above, if intervals overlap, max(x1,x3) < min(x2,x4) and overlapped interval\n //is ( max(x1,x3) , min(x2,x4) ).\n\n int ox1=(max(ax1,bx1)-min(ax2,bx2)); //if ox1 is negative, abs(ox1) is the length of overlapped rectangle, else rectangles do not overlap.\n int oy1=(max(ay1,by1)-min(ay2,by2)); //breadth of overlapped rectangle\n\n int rec3=0; //if rectangles do not overlap, area of overlapped rectangle is zero.\n if(ox1<0&&oy1<0) //if both ox1 and oy2 are negative, two rectangles overlap.\n rec3=ox1*oy1;\n return rec1+rec2-rec3; //Area(Rectangle 1) + Area(Rectangle 2) - Area(Overlapped triangle)\n }\n};" }, { "title": "Maximum Split of Positive Even Integers", "algo_input": "You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.\n\n\n\tFor example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique.\n\n\nReturn a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.\n\n \nExample 1:\n\nInput: finalSum = 12\nOutput: [2,4,6]\nExplanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.\n\n\nExample 2:\n\nInput: finalSum = 7\nOutput: []\nExplanation: There are no valid splits for the given finalSum.\nThus, we return an empty array.\n\n\nExample 3:\n\nInput: finalSum = 28\nOutput: [6,8,2,12]\nExplanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). \n(6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.\n\n\n \nConstraints:\n\n\n\t1 <= finalSum <= 1010\n\n", "solution_py": "class Solution:\n def maximumEvenSplit(self, finalSum: int) -> List[int]:\n l=[]\n if finalSum%2!=0:\n return l\n else:\n s=0\n i=2 # even pointer 2, 4, 6, 8, 10, 12...........\n while(s maximumEvenSplit(long finalSum) {\n List res = new ArrayList();\n //odd sum cannot be divided into even numbers\n if(finalSum % 2 != 0) {\n return res;\n }\n //Greedy approach, try to build the total sum using minimum unique even nos\n long currNum = 2;\n long remainingSum = finalSum;\n //as long as we can add subtract this number from remaining sum\n while(currNum <= remainingSum) {\n res.add(currNum);\n remainingSum -= currNum;//reducing remaining sum\n currNum += 2;//next even number\n }\n //now, remaining sum cannot be fulfilled by any larger even number\n //so extract the largest even number we added to the last index of res, and make it even larger by adding this current remaining sum\n //add remaining sum to the last element\n long last = res.remove(res.size()-1);\n res.add(last+remainingSum);\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n using ll = long long;\n\n ll bs(ll low , ll high, ll fs){\n\n ll ans = 1;\n while(low<=high){\n ll mid = low + (high-low)/2;\n if(mid*(mid+1)>fs){\n high = mid-1; // If sum till index equal to 'mid' > fs then make high = mid-1\n }\n else if(mid*(mid+1)==fs){\n return mid; // If sum till index equal to 'mid == fs, return 'mid'\n }\n else{\n ans = mid; // If sum till index equal to 'mid' < fs, update answer\n low = mid+1; // check for better answer\n }\n }\n return ans;\n }\n\n vector maximumEvenSplit(long long finalSum) {\n // ****some base cases / corner cases****\n if(finalSum&1) return {};\n if(finalSum==4) return {4};\n if(finalSum==8) return {2,6};\n\n vector ans;\n\n // assume that we are giving indices to even numbers\n // EVEN NUMBERS -> 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 ..............\n // THEIR INDICES-> 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ..............\n\n // 'idx' is the index of that EVEN number uptil which the total sum of all even numbers <= finalSum\n ll idx = bs(1,finalSum/2,finalSum);\n\n //Consequently, 'end' is that EVEN number uptil which the total sum of all even numbers <= finalSum\n ll start = 2, end = idx*2;\n\n //Now, we add all the even numbers from index 1 to index 'idx-1'\n // 2 + 4 + 6 + 8 ........................... + (end-2) + end\n // 1 2 3 4 ........................... idx-1 idx\n for(int i = start; i<= (idx-1)*2; i+=2){\n ans.push_back(i);\n }\n\n // We do not add the last even number yet, so that we can modify it and add it later to make the (totalSumSoFar) == finalSum\n // 'totalSumSoFar' can be easily calculated by using the formula ( totalSumSoFar = idx*(idx+1) )\n\n // increasing the last even number 'end' by the difference of (finalSum and totalSumSoFar)\n if(idx*(idx+1) List[int]:\n \n h = {}\n for i in nums:\n if i in h:\n h[i]+=1\n else:\n h[i]=1\n \n heap = []\n for i in h:\n heap.append([i,h[i]])\n \n heapq.heapify(heap)\n ans = []\n \n while heap:\n x = heapq.heappop(heap)\n ans.append(x[0])\n if x[1]>1:\n heapq.heappush(heap,[x[0],x[1]-1])\n \n return ans", "solution_js": "var sortArray = function(nums) {\n return quickSort(nums, 0, nums.length - 1);\n};\n\nconst quickSort = (arr, start, end) => {\n // base case\n if (start >= end) return arr;\n\n // return pivot index to divide array into 2 sub-arrays.\n const pivotIdx = partition(arr, start, end);\n // sort sub-array to the left and right of pivot index.\n quickSort(arr, start, pivotIdx - 1);\n quickSort(arr, pivotIdx + 1, end);\n\n return arr;\n}\n\nconst partition = (arr, start, end) => {\n // select a random pivot index, and swap pivot value with end value.\n const pivotIdx = Math.floor(Math.random() * (end - start + 1)) + start;\n [arr[pivotIdx], arr[end]] = [arr[end], arr[pivotIdx]];\n\n const pivotVal = arr[end];\n // loop from start to before end index (because pivot is stored at end index).\n for (let i = start; i < end; i++) {\n if (arr[i] < pivotVal) {\n // swap smaller-than-pivot value (at i) with the value at the start index.\n // This ensures all values to the left of start index will be less than pivot.\n [arr[i], arr[start]] = [arr[start], arr[i]];\n start++;\n }\n }\n\n // swap pivot (which was stored at end index) with value at start index.\n // This puts the pivot in its correct place.\n [arr[start], arr[end]] = [arr[end], arr[start]];\n return start;\n}\n\n/*\nNote: Instead of always picking a fixed index as the pivot (ie. start or end index),\nThe pivot was randomly selected to mitigate the odds of achieving worst case TC and SC.\nTC:\nBest and avg case: O(nlogn)\nworst case: O(n^2)\n\nSC:\nSince algo done in-place, space comes from recursive call stack.\nbest and avg case: O(logn)\nworst case: O(n)\n*/", "solution_java": "class Solution {\n\n public void downHeapify(int[] nums, int startIndex, int lastIndex){\n\n int parentIndex = startIndex;\n int leftChildIndex = 2*parentIndex + 1;\n int rightChildIndex = 2*parentIndex + 2;\n\n while(leftChildIndex <= lastIndex){\n int maxIndex = parentIndex;\n if(nums[leftChildIndex] > nums[maxIndex]){\n maxIndex = leftChildIndex;\n }\n if(rightChildIndex <= lastIndex && nums[rightChildIndex] > nums[maxIndex]){\n maxIndex = rightChildIndex;\n }\n if(maxIndex == parentIndex){\n return;\n }\n int temp = nums[maxIndex];\n nums[maxIndex] = nums[parentIndex];\n nums[parentIndex] = temp;\n parentIndex = maxIndex;\n leftChildIndex = 2*parentIndex + 1;\n rightChildIndex = 2*parentIndex + 2;\n }\n return;\n }\n\n public int[] sortArray(int[] nums) {\n int len = nums.length;\n //building a heap - O(n) time\n for(int i=(len/2)-1;i>=0;i--){\n downHeapify(nums,i,len-1);\n }\n //sorting element - nlogn(n) time\n for(int i=len -1 ;i>0;i--){\n int temp = nums[i];\n nums[i] = nums[0];\n nums[0] = temp;\n downHeapify(nums,0,i-1);\n }\n return nums;\n\n }\n}", "solution_c": "class Solution {\npublic:\n vector sortArray(vector& nums) {\n priority_queue, greater>pq;\n for(auto it : nums)\n {\n pq.push(it);\n }\n vectorans;\n while(!pq.empty())\n {\n ans.push_back(pq.top());\n pq.pop();\n }\n\n return ans;\n }\n};" }, { "title": "Min Cost Climbing Stairs", "algo_input": "You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.\n\nYou can either start from the step with index 0, or the step with index 1.\n\nReturn the minimum cost to reach the top of the floor.\n\n \nExample 1:\n\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n\n\nExample 2:\n\nInput: cost = [1,100,1,1,1,100,1,1,100,1]\nOutput: 6\nExplanation: You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.\n\n\n \nConstraints:\n\n\n\t2 <= cost.length <= 1000\n\t0 <= cost[i] <= 999\n\n", "solution_py": "class Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n n = len(cost)\n dp = cost[:2] + [0]*(n-2)\n for i in range(2, n):\n dp[i] = min(dp[i-1], dp[i-2]) + cost[i]\n return min(dp[-1], dp[-2])", "solution_js": "var minCostClimbingStairs = function(cost) {\n //this array will be populated with the minimum cost of each step starting from the top\n let minCostArray = [];\n //append a 0 at end to represent reaching the 'top'\n minCostArray[cost.length] = 0;\n //append the last stair to the end of the array\n minCostArray[cost.length - 1] = cost[cost.length - 1];\n \n //starts at -2 the length since we already have two elements in our array\n for (let i = cost.length - 2; i > -1; i--) {\n //checks which minimum cost is lower and assigns the value at that index accordingly\n if (minCostArray[i + 1] < minCostArray[i + 2]) minCostArray[i] = cost[i] + minCostArray[i + 1];\n else minCostArray[i] = cost[i] + minCostArray[i + 2];\n }\n //checks which of the first two options is the lowest cost\n return minCostArray[0] > minCostArray[1] ? minCostArray[1] : minCostArray[0];\n};", "solution_java": "class Solution {\n public int minCostClimbingStairs(int[] cost) {\n int a[] = new int[cost.length+1];\n a[0]=0;\n a[1]=0;\n \n for(int i=2;i<=cost.length;i++)\n {\n a[i]= Math.min(cost[i-1]+a[i-1], cost[i-2]+a[i-2]);\n }\n return a[cost.length];\n }\n}", "solution_c": "class Solution {\npublic:\n int minCostClimbingStairs(vector& cost) {\n /* Minimize cost of steps, where you can take one or two steps.\n \n At each step, store the minimum of the current step plus the step previous\n or the step two previous. At the last step we can either take the last\n element or leave it off.\n */\n int n = cost.size();\n for(int i = 2; i < n; i++) {\n cost[i] = min(cost[i] + cost[i-2], cost[i] + cost[i-1]); \n }\n \n return min(cost[n-1], cost[n-2]);\n }\n};" }, { "title": "Watering Plants II", "algo_input": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.\n\nEach plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:\n\n\n\tAlice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously.\n\tIt takes the same amount of time to water each plant regardless of how much water it needs.\n\tAlice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.\n\tIn case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant.\n\n\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.\n\n \nExample 1:\n\nInput: plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput: 1\nExplanation:\n- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.\n\n\nExample 2:\n\nInput: plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput: 2\nExplanation:\n- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.\n\n\nExample 3:\n\nInput: plants = [5], capacityA = 10, capacityB = 8\nOutput: 0\nExplanation:\n- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.\n\n\n \nConstraints:\n\n\n\tn == plants.length\n\t1 <= n <= 105\n\t1 <= plants[i] <= 106\n\tmax(plants[i]) <= capacityA, capacityB <= 109\n\n", "solution_py": "class Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n \n Alice , Bob = capacityA, capacityB\n \n res, i, j = 0, 0, len(plants)-1\n \n while i < j:\n if Alice >= plants[i]:\n Alice -= plants[i]\n else:\n res += 1\n Alice = capacityA - plants[i]\n \n if Bob >= plants[j]:\n Bob -= plants[j]\n else:\n res += 1\n Bob = capacityB - plants[j]\n \n i += 1 \n j -= 1\n \n return res + 1 if i == j and Alice < plants[i] and Bob < plants[i] else res\n\t\t", "solution_js": "var minimumRefill = function(plants, capacityA, capacityB) {\n const n = plants.length;\n\n let left = 0;\n let right = n - 1;\n\n let remA = capacityA;\n let remB = capacityB;\n\n let refills = 0;\n\n while (left < right) {\n const leftAmount = plants[left++];\n const rightAmount = plants[right--];\n\n if (leftAmount > remA) {\n ++refills;\n remA = capacityA;\n }\n remA -= leftAmount;\n\n if (rightAmount > remB) {\n ++refills;\n remB = capacityB;\n }\n remB -= rightAmount;\n\n }\n\n if (left === right) {\n const midAmount = plants[left];\n\n if (remB > remA) {\n if (remB < midAmount) ++refills;\n }\n else {\n if (remA < midAmount) ++refills;\n }\n }\n\n return refills;\n};", "solution_java": "class Solution {\n public int minimumRefill(int[] plants, int capacityA, int capacityB) {\n int count=0;\n int c1=capacityA,c2=capacityB;\n for(int start=0,end=plants.length-1;start<=plants.length/2&&end>=plants.length/2;start++,end--){\n if(start==end||start>end)break;\n if(c1>=plants[start]){\n c1-=plants[start];\n }\n else{\n count++;\n c1=capacityA;\n c1-=plants[start];\n }\n if(c2>=plants[end]){\n c2-=plants[end];\n }\n else{\n count++;\n c2=capacityB;\n c2-=plants[end];\n }\n }\n if((c1>c2||c1==c2)&&plants.length%2!=0){\n if(plants[plants.length/2]>c1)count++;\n }\n else if(c1c2)count++;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumRefill(vector& plants, int capacityA, int capacityB) {\n \n int n(plants.size()), res(0), aliceC(capacityA), bobC(capacityB), alice(0), bob(n-1);\n \n while (alice < bob)\n {\n if (alice == bob)\n {\n if (aliceC < plants[alice] and bobC < plants[bob]) res++;\n break;\n }\n if (aliceC < plants[alice]) aliceC = capacityA, res++;\n if (bobC < plants[bob]) bobC = capacityB, res++;\n aliceC -= plants[alice++];\n bobC -= plants[bob--];\n }\n return res;\n }\n};" }, { "title": "Largest Multiple of Three", "algo_input": "Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.\n\nSince the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.\n\n \nExample 1:\n\nInput: digits = [8,1,9]\nOutput: \"981\"\n\n\nExample 2:\n\nInput: digits = [8,6,7,1,0]\nOutput: \"8760\"\n\n\nExample 3:\n\nInput: digits = [1]\nOutput: \"\"\n\n\n \nConstraints:\n\n\n\t1 <= digits.length <= 104\n\t0 <= digits[i] <= 9\n\n", "solution_py": "class Solution:\n\tdef largestMultipleOfThree(self, digits: List[int]) -> str:\n\t\tA = digits\n\t\tA.sort()\n\t\tA.reverse()\n\n\t\t@cache\n\t\tdef DP(i, r): # max number whose remainder is r using subarray [0:i] (inclusive) \n\t\t\tif i == 0:\n\t\t\t\tif A[0] % 3 == r:\n\t\t\t\t\treturn A[0]\n\t\t\t\telse:\n\t\t\t\t\treturn 0\n\n\t\t\tRa = DP(i-1, r)\n\t\t\tRb = [ x for j in range(3) \\\n\t\t\t\t for x in ( DP(i-1,j) * 10 + A[i] ,)\n\t\t\t\t if x % 3 == r ]\n\n\t\t\treturn max([Ra, *Rb])\n\n\t\tans = DP(len(A) - 1, 0)\n\n\t\tif ans == 0 and 0 not in A:\n\t\t\treturn \"\"\n\t\telse:\n\t\t\treturn str(ans)", "solution_js": "/**\n * @param {number[]} digits\n * @return {string}\n */\nvar largestMultipleOfThree = function(digits) {\n // highest digit first\n digits.sort((l, r) => r - l);\n \n // what is the remainder of the total sum?\n const sumRemainder = digits.reduce((a, c) => a + c, 0) % 3;\n \n if (sumRemainder) {\n let targetIndex = 0, i = digits.length - 1;\n \n // try to find what is the smallest number that can be removed\n for (; i >= 0; i--) {\n if ((digits[i] - sumRemainder) % 3 === 0) {\n targetIndex = i;\n break;\n }\n }\n\n if (i < 0) {\n // iterated the whole loop, couldn't find a single number to remove\n // remove everything but multiples of 3\n digits = digits.filter(v => v % 3 === 0);\n } else {\n digits.splice(targetIndex, 1);\n }\n }\n \n return (digits[0] === 0) ? '0' : digits.join('');\n};", "solution_java": "class Solution {\n public String largestMultipleOfThree(int[] digits) {\n int n=digits.length;\n Arrays.sort(digits);\n \n if(digits[digits.length-1]==0){\n return \"0\";\n }\n \n int sum=0;\n \n for(int i=0;i=0;i--){\n sb.append(digits[i]);\n }\n \n return sb.toString();\n }else if(sum%3==1){\n int modOne=-1;\n \n for(int i=0;i=0;i--){\n if(digits[i]!=-1){\n sb.append(digits[i]);\n }\n \n }\n \n if(sb.length()>0 && sb.toString().charAt(0)=='0'){\n return \"0\";\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n\n vector ans;\n\n void calculate(vector& count,int no,vector& temp){\n\n if(no==0){\n int flag=0,sum1=0,sum2=0,validSum=0;\n for(int j=1;j<10;j++){\n sum1+=temp[j];\n sum2+=ans[j];\n validSum+=(temp[j]*j);\n }\n if(validSum%3!=0){\n return ;\n }\n\n if(sum2>sum1)\n return;\n else if(sum1>sum2){\n for(int i=1;i<10;i++){\n ans[i]=temp[i];\n }\n return ;\n }\n int j=9;\n while(j>0){\n if(ans[j]temp[j])\n break;\n j--;\n }\n if (flag==1){\n for(int i=1;i<10;i++){\n ans[i]=temp[i];\n }\n }\n return ;\n }\n\n int targetCount=count[no]-2;\n\n if(targetCount<0)\n targetCount=0;\n\n int co=count[no];\n\n do{\n temp[no]=co;\n\n calculate(count,no-1,temp);\n\n co--;\n }\n while(co>=targetCount);\n\n }\n\n string largestMultipleOfThree(vector& digits) {\n vector count(10,0);\n int n=digits.size();\n for(int i=0;i temp(10,0);\n ans.resize(10,0);\n calculate(count,9,temp);\n\n string res=\"\";\n ans[0]=count[0];\n for(int i=9;i>=0;i--){\n for(int j=1;j<=ans[i];j++){\n res+=('0'+i);\n }\n }\n if(res.size()>=2 && res[0]=='0' && res[1]=='0')\n return \"0\";\n return res;\n }\n};" }, { "title": "Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", "algo_input": "Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.\n\n \nExample 1:\n\nInput: nums = [8,2,4,7], limit = 4\nOutput: 2 \nExplanation: All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.\n\n\nExample 2:\n\nInput: nums = [10,1,2,4,7,2], limit = 5\nOutput: 4 \nExplanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\n\n\nExample 3:\n\nInput: nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 109\n\t0 <= limit <= 109\n\n", "solution_py": "# max absolte diff within a subarray is subarray max substracted by subarray min\nclass Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n q = collections.deque() # monotonic decreasing deque to compute subarray max, index of\n q2 = collections.deque() # monotonic increasing deque to compute subarray min, index of\n \n # sliding window\n res = left = 0\n for right in range(len(nums)):\n # pop monotocity-violating numbers from right end\n while q and nums[q[-1]] <= nums[right]:\n q.pop()\n q.append(right)\n \n # pop monotocity-violating numbers from right end\n while q2 and nums[q2[-1]] >= nums[right]:\n q2.pop()\n q2.append(right)\n \n # sliding window\n while left < right and q and q2 and nums[q[0]] - nums[q2[0]] > limit:\n # compress window from left pointer\n if q and q[0] == left:\n q.popleft()\n \n # compress left pointer\n if q2 and q2[0] == left:\n q2.popleft()\n \n left += 1\n \n if nums[q[0]] - nums[q2[0]] <= limit:\n res = max(res, right - left + 1)\n \n return res", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} limit\n * @return {number}\n */\nvar longestSubarray = function(nums, limit) {\n const maxQueue = [];\n const minQueue = [];\n let start = 0;\n let res = 0;\n for(let end = 0; end < nums.length; end ++) {\n const num = nums[end];\n while(maxQueue.length > 0 && maxQueue[maxQueue.length - 1] < num) {\n maxQueue.pop();\n }\n\n while(minQueue.length > 0 && minQueue[minQueue.length - 1] > num) {\n minQueue.pop();\n }\n maxQueue.push(num);\n minQueue.push(num);\n if(maxQueue[0] - minQueue[0] > limit) {\n if(maxQueue[0] === nums[start]) {\n maxQueue.shift();\n }\n\n if(minQueue[0] === nums[start]) {\n minQueue.shift();\n }\n\n start +=1;\n }\n res = Math.max(res, end - start + 1);\n }\n\n return res;\n};", "solution_java": "class Solution {\n \n public int longestSubarray(int[] nums, int limit) {\n \n Deque increasing = new LinkedList(); // To keep track of Max_value index\n Deque decreasing = new LinkedList(); // To keep track of Min_value index\n \n int i = 0 ;\n int j = 0 ;\n int max_length = 0 ;\n \n while(j < nums.length){\n \n while(!increasing.isEmpty() && nums[increasing.peekLast()] >= nums[j]){\n increasing.pollLast() ;\n }\n \n increasing.add(j);\n \n while(!decreasing.isEmpty() && nums[decreasing.peekLast()] <= nums[j]){\n decreasing.pollLast() ;\n }\n \n decreasing.add(j);\n \n int max_val = nums[decreasing.peekFirst()] ;\n int min_val = nums[increasing.peekFirst()] ;\n \n if(max_val-min_val <= limit){\n max_length = Math.max(max_length , j-i+1);\n }else{\n \n // If maximum absolute diff > limit , then remove from dequeue and increase i\n while(i<=j && nums[decreasing.peekFirst()] - nums[increasing.peekFirst()] > limit ){\n \n if(!increasing.isEmpty() && increasing.peekFirst() == i){\n increasing.pollFirst() ;\n }\n \n if(!decreasing.isEmpty() && decreasing.peekFirst() == i){\n decreasing.pollFirst() ;\n }\n \n i++ ; \n } \n \n }\n \n \n j++ ;\n }\n \n return max_length ;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestSubarray(vector& nums, int limit) {\n\n int max_ans = 0;\n map mp;\n int j = 0;\n for(int i = 0 ; i < nums.size() ; i++) {\n\n mp[nums[i]] ++;\n\n while( mp.size() > 0 && abs(mp.rbegin()->first - mp.begin()->first) > limit)\n {\n\n if(mp[nums[j]] > 0) {\n mp[nums[j]] --;\n }\n\n if(mp[nums[j]] == 0) {\n\n mp.erase(nums[j]);\n }\n\n j++;\n }\n\n max_ans = max(max_ans, i - j + 1);\n }\n\n return max_ans;\n }\n};" }, { "title": "Parsing A Boolean Expression", "algo_input": "Return the result of evaluating a given boolean expression, represented as a string.\n\nAn expression can either be:\n\n\n\t\"t\", evaluating to True;\n\t\"f\", evaluating to False;\n\t\"!(expr)\", evaluating to the logical NOT of the inner expression expr;\n\t\"&(expr1,expr2,...)\", evaluating to the logical AND of 2 or more inner expressions expr1, expr2, ...;\n\t\"|(expr1,expr2,...)\", evaluating to the logical OR of 2 or more inner expressions expr1, expr2, ...\n\n\n \nExample 1:\n\nInput: expression = \"!(f)\"\nOutput: true\n\n\nExample 2:\n\nInput: expression = \"|(f,t)\"\nOutput: true\n\n\nExample 3:\n\nInput: expression = \"&(t,f)\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= expression.length <= 2 * 104\n\texpression[i] consists of characters in {'(', ')', '&', '|', '!', 't', 'f', ','}.\n\texpression is a valid expression representing a boolean, as given in the description.\n\n", "solution_py": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n \n # expresssion map\n opMap = {\"!\" : \"!\", \"|\" : \"|\" , \"&\" : \"&\"}\n expMap = {\"t\" : True, \"f\" : False}\n expStack = []\n opStack = []\n ans = 0\n i = 0\n \n while i < len(expression):\n \n if expression[i] in opMap:\n opStack.append(opMap[expression[i]])\n \n elif expression[i] in expMap:\n expStack.append(expMap[expression[i]])\n \n elif expression[i] == \"(\":\n expStack.append(\"(\")\n \n # strat performing operations\n elif expression[i] == \")\":\n op = opStack.pop()\n ans = [] # evaluator arr\n \n # To Check\n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"outer WHILE\")\n \n # Performing serries of operation on exp inside a ()\n while expStack[-1] != \"(\":\n \n # To check \n # print(\"EXPSTACK :- \", expStack, \"OPSTACK :- \", opStack, \"OPerator :- \",op, \"INNER WHILE\")\n \n # Not single operation only\n if op == \"!\":\n ans.append(not expStack.pop())\n else:\n ans.append(expStack.pop())\n \n # Operation evaluation for more then 1 exp inside () for &, or\n while len(ans) > 1:\n # or\n if op == \"|\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 or exp2\n ans.append(res)\n # and\n elif op == \"&\":\n exp1, exp2 = ans.pop(), ans.pop()\n res = exp1 and exp2\n ans.append(res)\n \n # poping \")\" and adding the res of operation done above\n expStack.pop() # poping \")\"\n expStack.append(ans[-1])\n \n # increment i \n i += 1\n \n return expStack[-1]\n \n \n\"\"\"\nTC : O(n * m) | n = len(expression), m = no of expression inside a prenthesis\nSc : O(n)\n\"\"\"", "solution_js": "var parseBoolExpr = function(expression) {\n let sol, stack = [],\n op={t:true, f:false};\n for(let i=0; i(op[a]||op[b]) === true?'t':'f');\n }\n if(operator == '&'){\n ko=findings.reduce((a,b)=>(op[a]&&op[b]) === true?'t':'f');\n }\n if(operator == '!'){\n ko=findings.pop()==='f'?'t':'f';\n }\n stack.push(ko);\n }\n\n }\n return stack.pop()=='f'?false:true;\n};", "solution_java": "class Solution {\n \n int pos = 0;\n \n public boolean parseBoolExpr(String s) {\n pos = 0;\n return solve(s, '-');\n }\n \n public boolean solve(String s, char prev_sign) {\n \n boolean res = s.charAt(pos) == 'f' ? false : true;\n char cur_sign = ' ';\n int flag_res_init = 0;\n while(pos < s.length()) {\n \n char cur_char = s.charAt(pos++);\n \n if(isExpr(cur_char)){\n res = eval(cur_char == 't'?true:false, res , prev_sign);\n }\n else if(isSign(cur_char)){\n cur_sign = cur_char;\n }\n else if(cur_char == '('){\n if(flag_res_init == 1 || prev_sign == '!')\n res = eval(solve(s, cur_sign), res, prev_sign);\n else {\n res = solve(s, cur_sign);\n flag_res_init = 1;\n }\n }\n else if(cur_char == ')'){\n return res;\n }\n \n }\n return res;\n }\n \n public boolean isExpr(char c){\n return (c == 'f' || c == 't');\n }\n \n public boolean isSign(char c){\n return (c == '!' || c == '&' || c == '|');\n }\n \n public boolean eval(boolean e1, boolean e2, char sign) {\n \n boolean res = false;\n if(sign == '!')\n res = !e1;\n \n else if(sign == '|')\n res = e1 | e2;\n \n else if(sign == '&')\n res = e1&e2;\n \n return res;\n }\n}", "solution_c": "class Solution {\n pair dfs(string &e, int idx){\n bool res;\n if(e[idx]=='!'){\n auto [a,b]=dfs(e, idx+2);\n return {!a,b+3};\n }else if(e[idx]=='&'){\n int len=2;\n res=true;\n idx+=2;\n while(e[idx]!=')'){\n if(e[idx]==','){\n idx++;len++;\n }\n auto [a,b]=dfs(e,idx);\n res&=a;\n idx+=b;\n len+=b;\n }\n return {res,len+1};\n }else if(e[idx]=='|'){\n int len=2;\n res=false;\n idx+=2;\n while(e[idx]!=')'){\n if(e[idx]==','){\n idx++;len++;\n }\n auto [a,b]=dfs(e,idx);\n res|=a;\n idx+=b;\n len+=b;\n }\n return {res,len+1};\n }else{\n return {e[idx]=='t',1};\n }\n }\npublic:\n bool parseBoolExpr(string expression) {\n return dfs(expression, 0).first;\n }\n};" }, { "title": "Design a Stack With Increment Operation", "algo_input": "Design a stack which supports the following operations.\n\nImplement the CustomStack class:\n\n\n\tCustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.\n\tvoid push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.\n\tint pop() Pops and returns the top of stack or -1 if the stack is empty.\n\tvoid inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.\n\n\n \nExample 1:\n\nInput\n[\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]\nOutput\n[null,null,null,2,null,null,null,null,null,103,202,201,-1]\nExplanation\nCustomStack customStack = new CustomStack(3); // Stack is Empty []\ncustomStack.push(1); // stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\ncustomStack.push(2); // stack becomes [1, 2]\ncustomStack.push(3); // stack becomes [1, 2, 3]\ncustomStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4\ncustomStack.increment(5, 100); // stack becomes [101, 102, 103]\ncustomStack.increment(2, 100); // stack becomes [201, 202, 103]\ncustomStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\ncustomStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]\ncustomStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []\ncustomStack.pop(); // return -1 --> Stack is empty return -1.\n\n\n \nConstraints:\n\n\n\t1 <= maxSize <= 1000\n\t1 <= x <= 1000\n\t1 <= k <= 1000\n\t0 <= val <= 100\n\tAt most 1000 calls will be made to each method of increment, push and pop each separately.\n\n", "solution_py": "\tclass CustomStack:\n\n\t\tdef __init__(self, maxSize: int):\n\t\t\tself.size = maxSize\n\t\t\tself.stack = []\n\n\t\tdef push(self, x: int) -> None:\n\t\t\tif self.size > len(self.stack):\n\t\t\t\tself.stack.append(x)\n\n\t\tdef pop(self) -> int:\n\t\t\tif self.stack:\n\t\t\t\treturn self.stack.pop()\n\t\t\treturn -1\n\n\t\tdef increment(self, k: int, val: int) -> None:\n\t\t\tlen_stack = len(self.stack)\n\n\t\t\tif len_stack < k:\n\t\t\t\tself.stack[:] = [i + val for i in self.stack]\n\t\t\t\treturn\n\n\t\t\tfor i in range(k):\n\t\t\t\tself.stack[i] += val", "solution_js": "var CustomStack = function(maxSize) {\n this.stack = new Array(maxSize).fill(-1);\n this.maxSize = maxSize;\n this.size = 0;\n};\n\nCustomStack.prototype.push = function(x) {\n if(this.size < this.maxSize){\n this.stack[this.size] = x;\n this.size++;\n }\n};\n\nCustomStack.prototype.pop = function() {\n if(this.size > 0){\n this.size--;\n return this.stack[this.size];\n }\n return -1;\n};\n\nCustomStack.prototype.increment = function(k, val) {\n let count = k >= this.size ? this.size-1 : k-1;\n\n while(count >= 0){\n this.stack[count] += val;\n count--;\n }\n};", "solution_java": "class CustomStack {\n\n int[] stack;\n int top;\n\n public CustomStack(int maxSize) {\n\n //intialise the stack and the top\n stack= new int[maxSize];\n top=-1;\n }\n\n public void push(int x) {\n\n // if the stack is full just skip\n if( top==stack.length-1) return;\n\n //add to the stack\n top++;\n stack[top]=x;\n }\n\n public int pop() {\n\n //if stack is empty return -1\n if( top==-1) return -1;\n\n //remove/pop the top element\n top--;\n return stack[top+1];\n\n }\n\n public void increment(int k, int val) {\n\n //got to increment the min of the elements present in the stack and k\n int n= Math.min(top+1,k);\n\n for( int i=0; i= nextIndex else runt upto k only\n int n = (k >= nextIndex) ? nextIndex : k;\n for(int i = 0; i < n; i++){\n data[i] = data[i] + val;\n }\n }\n};" }, { "title": "Ambiguous Coordinates", "algo_input": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s.\n\n\n\tFor example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\".\n\n\nReturn a list of strings representing all possibilities for what our original coordinates could have been.\n\nOur original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\".\n\nThe final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)\n\n \nExample 1:\n\nInput: s = \"(123)\"\nOutput: [\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]\n\n\nExample 2:\n\nInput: s = \"(0123)\"\nOutput: [\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\nExplanation: 0.0, 00, 0001 or 00.01 are not allowed.\n\n\nExample 3:\n\nInput: s = \"(00011)\"\nOutput: [\"(0, 0.011)\",\"(0.001, 1)\"]\n\n\n \nConstraints:\n\n\n\t4 <= s.length <= 12\n\ts[0] == '(' and s[s.length - 1] == ')'.\n\tThe rest of s are digits.\n\n", "solution_py": "class Solution(object):\n def ambiguousCoordinates(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n def _isValidSplit(s):\n return False if len(s)>1 and re.match('/^[0]+$/',s) else True\n\n def _isValidNum(ipart,fpart):\n return False if (len(ipart)>1 and ipart[0]=='0') or (fpart and fpart[-1]=='0') else True\n\n def _splitToNums(s):\n rets=[]\n if len(s)==1:return [s]\n for i in range(1,len(s)+1):\n a,b=s[:i],s[i:]\n if _isValidNum(a,b):rets.append(\"%s.%s\"%(a,b) if b else \"%s\"%(a))\n return rets\n\n ans,s=[],s[1:-1]\n for i in range(1,len(s)):\n a,b=s[:i],s[i:]\n if not _isValidSplit(a) or not _isValidSplit(b):continue\n for c1,c2 in itertools.product(_splitToNums(a),_splitToNums(b)):ans.append(\"(%s, %s)\"%(c1,c2))\n return ans", "solution_js": "var ambiguousCoordinates = function(S) {\n let ans = [], xPoss\n const process = (str, xy) => {\n if (xy)\n for (let x of xPoss)\n ans.push(`(${x}, ${str})`)\n else xPoss.push(str)\n }\n const parse = (str, xy) => {\n if (str.length === 1 || str[0] !== \"0\")\n process(str, xy)\n if (str.length > 1 && str[str.length-1] !== \"0\")\n process(str.slice(0,1) + \".\" + str.slice(1), xy)\n if (str.length > 2 && str[0] !== \"0\" && str[str.length-1] !== \"0\")\n for (let i = 2; i < str.length; i++)\n process(str.slice(0,i) + \".\" + str.slice(i), xy)\n }\n for (let i = 2; i < S.length - 1; i++) {\n let strs = [S.slice(1,i), S.slice(i, S.length - 1)]\n xPoss = []\n for (let j = 0; j < 2; j++)\n if (xPoss.length || !j) parse(strs[j], j)\n }\n return ans\n};", "solution_java": "class Solution {\n public List ret;\n public List ans;\n public List ambiguousCoordinates(String s) {\n ret=new ArrayList<>();\n ans=new ArrayList<>();\n String start=s.substring(0,2);\n util(s,1);\n fun();\n return ans;\n }\n \n //putting comma\n void util(String s,int idx) {\n if(idx==s.length()-2) {\n return;\n }\n \n String ns=s.substring(0,idx+1)+\", \"+s.substring(idx+1);\n ret.add(ns);\n util(s,idx+1);\n }\n \n //helper function for puting decimals after comma\n void fun() {\n for(String s:ret) {\n int cIndex=0;\n for(int i=0;i n1=dot(a);\n List n2=dot(b);\n if(n1==null || n2==null) { //invalid strings\n continue;\n }else { //valid strings\n for(String fir:n1) {\n for(String sec:n2) {\n ans.add(\"(\"+fir+\", \"+sec+\")\");\n }\n }\n }\n }\n }\n \n //putting decimal point\n List dot(String n) {\n List li=new ArrayList<>();\n if(n.length()==1) {\n li.add(n);\n }else {\n \n //just checking for first and last zeroes and making conditions accordingly\n\n if(n.charAt(n.length()-1)=='0') {\n if(n.charAt(0)=='0') {\n return null;\n }else {\n li.add(n);\n }\n }else if(n.charAt(0)=='0') {\n li.add(\"0.\"+n.substring(1));\n }else {\n for(int i=0;i check(string s){\n int n = s.size();\n vector res;\n if(s[0] == '0'){\n if(n == 1)\n res.push_back(s);\n else{\n if(s[n-1] == '0')\n return res;\n \n s.insert(1, \".\");\n res.push_back(s);\n }\n }\n else{\n if(s[n-1] == '0'){\n res.push_back(s);\n return res;\n }\n \n for(int i=1; i ambiguousCoordinates(string s) {\n int n = s.size();\n vector res;\n \n for(int i=2; i left = check(s.substr(1, i-1));\n vector right = check(s.substr(i, n-i-1));\n for(int j=0; j str:\n dec = {}\n c = 0\n res=''\n for i in indices:\n dec[i] = s[c]\n c += 1\n # dec = {\"4\":\"c\",\"5\":\"o\",\"6\":\"d\",\"7\":\"e\",\"0\":\"l\",\"2\":\"e\",\"1\":\"e\",\"3\":\"t\"}\n for x in range(len(indices)):\n res += dec[x]\n # x in range 0, 1, 2,....... len *indices or s*\n return res", "solution_js": "var restoreString = function(s, indices) {\n const result = []\n \n for(let i=0; i& indices) {\n\n string ans = s;\n\n for(int i=0 ; i List[str]:\n temp = []\n result = []\n x = target[-1]\n for i in range(1,x+1):\n temp.append(i)\n for i in range(len(temp)):\n if temp[i] in target:\n result.append(\"Push\")\n elif temp[i] not in target:\n result.append(\"Push\")\n result.append(\"Pop\")\n return result", "solution_js": "/**\n * @param {number[]} target\n * @param {number} n\n * @return {string[]}\n */\nvar buildArray = function(target, n) {\n let arr = [];\n let index = 0;\n for(let i = 1; i <= target[target.length-1];i++){\n if(target[index] == i){\n arr.push('Push');\n index++;\n }else{\n arr.push('Push');\n arr.push('Pop');\n }\n }\n return arr;\n};", "solution_java": "class Solution {\n public List buildArray(int[] target, int n) {\n List result=new ArrayList<>();\n int i=1,j=0;\n while(j buildArray(vector& target, int n) {\n vectorans;\n int l=target.size(), count=0,ind=0; // ind is index of the target array\n\n for(int i=1;i<=n;i++){\n if(count==l) break;\n if(target[ind]!=i){\n ans.push_back(\"Push\");\n ans.push_back(\"Pop\");\n }\n else{\n ans.push_back(\"Push\");\n count++;\n ind++;\n }\n }\n return ans;\n }\n};" }, { "title": "Delete Node in a BST", "algo_input": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.\n\nBasically, the deletion can be divided into two stages:\n\n\n\tSearch for a node to remove.\n\tIf the node is found, delete the node.\n\n\n \nExample 1:\n\nInput: root = [5,3,6,2,4,null,7], key = 3\nOutput: [5,4,6,2,null,null,7]\nExplanation: Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.\n\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,7], key = 0\nOutput: [5,3,6,2,4,null,7]\nExplanation: The tree does not contain a node with value = 0.\n\n\nExample 3:\n\nInput: root = [], key = 0\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-105 <= Node.val <= 105\n\tEach node has a unique value.\n\troot is a valid binary search tree.\n\t-105 <= key <= 105\n\n\n \nFollow up: Could you solve it with time complexity O(height of tree)?\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:\ndef deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n\ndef find_inorder(root, key):\n\n\tif root is None :\n\t\treturn []\n\n\treturn find_inorder(root.left, key) + [root.val] + find_inorder(root.right, key)\n\ndef find_preorder(root, key):\n\n\tif root is None:\n\t\treturn []\n\n\treturn [root.val] + find_preorder(root.left,key) + find_preorder(root.right, key)\n\npreorder = find_preorder(root, key)\n\ntry:\n\tpreorder.remove(key)\nexcept:\n\treturn root\n\ninorder = find_inorder(root, key)\n\ninorder.remove(key)\n\n\n\n\nhashmap = {}\n\nfor i in range(len(inorder)):\n\tkey = inorder[i]\n\thashmap[key] = i\n\ndef buildTree(left, right):\n\n\tif left > right:\n\t\treturn \n\n\tval = inorder[left]\n\troot = TreeNode(val)\n\n\tindex = hashmap[val]\n\n\troot.left = buildTree(left, index-1)\n\troot.right = buildTree(index+1, right)\n\n\treturn root\n\nN = len(inorder)\nnew_tree = buildTree(0,N-1)\n\nreturn new_tree", "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\nconst getLeftMostNode=(root)=>{\n if(!root)return null;\n let node=getLeftMostNode(root.left);\n return node?node:root;\n}\n/**\n * @param {TreeNode} root\n * @param {number} key\n * @return {TreeNode}\n */\n\n\nvar deleteNode = function(root, key) {\n if(!root)return null;\n if(root.val>key){\n root.left=deleteNode(root.left,key);\n }else if(root.valroot.val){\n root.right = deleteNode(root.right,key);\n return root;\n }\n \n else{\n if(root.left==null){\n return root.right;\n }\n else if(root.right==null){\n return root.left;\n }\n else{\n TreeNode min = root.right;\n while(min.left!=null){\n min = min.left;\n }\n \n root.val = min.val;\n root.right = deleteNode(root.right,min.val);\n return root;\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* deleteNode(TreeNode* root, int key) {\n if(root) \n if(key < root->val) root->left = deleteNode(root->left, key); //We frecursively call the function until we find the target node\n else if(key > root->val) root->right = deleteNode(root->right, key); \n else{\n if(!root->left && !root->right) return NULL; //No child condition\n if (!root->left || !root->right)\n return root->left ? root->left : root->right; //One child contion -> replace the node with it's child\n\t\t\t\t\t //Two child condition \n TreeNode* temp = root->left; //(or) TreeNode *temp = root->right;\n while(temp->right != NULL) temp = temp->right; // while(temp->left != NULL) temp = temp->left;\n root->val = temp->val; // root->val = temp->val;\n root->left = deleteNode(root->left, temp->val); // root->right = deleteNode(root->right, temp);\t\t\n }\n return root;\n } \n};" }, { "title": "Relative Ranks", "algo_input": "You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.\n\nThe athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:\n\n\n\tThe 1st place athlete's rank is \"Gold Medal\".\n\tThe 2nd place athlete's rank is \"Silver Medal\".\n\tThe 3rd place athlete's rank is \"Bronze Medal\".\n\tFor the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is \"x\").\n\n\nReturn an array answer of size n where answer[i] is the rank of the ith athlete.\n\n \nExample 1:\n\nInput: score = [5,4,3,2,1]\nOutput: [\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\nExplanation: The placements are [1st, 2nd, 3rd, 4th, 5th].\n\nExample 2:\n\nInput: score = [10,3,8,9,4]\nOutput: [\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\nExplanation: The placements are [1st, 5th, 3rd, 2nd, 4th].\n\n\n\n \nConstraints:\n\n\n\tn == score.length\n\t1 <= n <= 104\n\t0 <= score[i] <= 106\n\tAll the values in score are unique.\n\n", "solution_py": "class Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n scores_ids = []\n for i in range(len(score)):\n scores_ids.append((score[i], i))\n scores_ids.sort(reverse=True)\n\n ans = [0] * len(scores_ids)\n for i in range(len(scores_ids)):\n ans[scores_ids[i][1]] = str(i+1)\n\n try:\n ans[scores_ids[0][1]] = \"Gold Medal\"\n ans[scores_ids[1][1]] = \"Silver Medal\"\n ans[scores_ids[2][1]] = \"Bronze Medal\"\n except:\n pass\n\n return ans", "solution_js": "var findRelativeRanks = function(score) {\n let output=score.slice(0);\n let map={};\n score.sort((a,b)=>b-a).forEach((v,i)=>map[v]=i+1);\n for(let item in map){\n if(map[item]==1){map[item]=\"Gold Medal\"};\n if(map[item]==2){map[item]=\"Silver Medal\"};\n if(map[item]==3){map[item]=\"Bronze Medal\"};\n }\n return output.map(v=>map[v]+\"\"); // +\"\": num=>str.\n};", "solution_java": "class Solution {\n public String[] findRelativeRanks(int[] score) {\n String[] res = new String[score.length];\n TreeMap map = new TreeMap<>();\n for(int i = 0; i < score.length; i++) map.put(score[i], i);\n int rank = score.length;\n for(Map.Entry p: map.entrySet()){\n if(rank == 1) res[p.getValue()] = \"Gold Medal\";\n else if(rank == 2) res[p.getValue()] = \"Silver Medal\";\n else if(rank == 3) res[p.getValue()] = \"Bronze Medal\";\n else res[p.getValue()] = String.valueOf(rank);\n rank--;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector findRelativeRanks(vector& score) {\n int n=score.size();\n vector vs(n);\n unordered_map mp;\n for(int i=0; i());\n for(int i=0; i int: \n def calculate(k,ans):\n if k>1:\n ans+=((k-1)*(k))//2 \n\t\t\t\t#Sum of Natural Numbers\n return ans\n else:\n return ans\n end = 0\n start = 0\n prev= sys.maxsize\n k= 0\n ans = 0\n while end1:\n ans = calculate(k,ans)\n\t\t\t\n return ans+len(prices)", "solution_js": "var getDescentPeriods = function(prices) {\n const n = prices.length;\n\n let left = 0;\n let totRes = 0;\n\n while (left < n) {\n let count = 1;\n\n let right = left + 1;\n\n while (right < n && prices[right] + 1 === prices[right - 1]) {\n count += (right - left + 1);\n ++right;\n }\n\n totRes += count;\n\n left = right;\n }\n\n return totRes;\n};", "solution_java": "class Solution {\n public long getDescentPeriods(int[] prices) {\n int i=0;\n int j=1;\n long ans=1;\n while(j& prices) {\n long long ans = 0;\n long long temp = 0;\n for(int i=1; i int:\n m = defaultdict(list)\n for a, b, p in edges:\n m[a].append((p, b))\n m[b].append((p, a))\n\n vis = set()\n queue = []\n heappush(queue, (0, 0))\n edgevis = set()\n edgeofl = defaultdict(lambda: 0)\n ans = 0\n while queue:\n # print(queue)\n cost, cur = heappop(queue)\n vis.add(cur)\n for p, nxt in m[cur]:\n if p < maxMoves - cost:\n if (cur, nxt) not in edgevis and (nxt, cur) not in edgevis:\n ans += p\n # if nxt in vis:\n # ans -= 1\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n if nxt not in vis:\n heappush(queue, (cost + p + 1, nxt))\n else:\n bal = maxMoves - cost\n if (cur, nxt) in edgevis:\n continue\n if bal <= edgeofl[(cur, nxt)]:\n continue\n if bal + edgeofl[(nxt, cur)] < p:\n ans += bal - edgeofl[(cur, nxt)]\n edgeofl[(cur, nxt)] = bal\n else:\n ans += p - edgeofl[(nxt, cur)] - edgeofl[(cur, nxt)]\n edgevis.add((cur, nxt))\n edgevis.add((nxt, cur))\n return ans + len(vis)", "solution_js": "var reachableNodes = function(edges, maxMoves, n) {\n const g = Array.from({length: n}, () => []);\n \n for(let [u, v, cnt] of edges) {\n g[u].push([v, cnt + 1]);\n g[v].push([u, cnt + 1]);\n }\n \n // find min budget to reach from 0 to all nodes\n const budget = new Array(n).fill(Infinity);\n budget[0] = 0;\n const dijkstra = () => {\n // heap will be collection [node, weight]\n const heap = new MinPriorityQueue({ priority: (x) => x[1] });\n heap.enqueue([0, 0]);\n while(heap.size()) {\n const [n, c] = heap.dequeue().element;\n for(let [nextNode, cost] of g[n]) {\n let temp = c + cost;\n if(budget[nextNode] > temp) {\n budget[nextNode] = temp;\n heap.enqueue([nextNode, temp]);\n }\n }\n }\n };\n dijkstra();\n \n // add to sum all reachable nodes from 0 with max move\n let vis = 0;\n for(let w of budget) vis += w <= maxMoves;\n\n // add intermediate nodes between edges with available budget\n for(let [a, b, c] of edges) {\n let [availableFromA, availableFromB] = [maxMoves - budget[a], maxMoves - budget[b]];\n if(availableFromA < 0 || availableFromB < 0) {\n vis += Math.max(availableFromA, 0) + Math.max(availableFromB, 0);\n } else {\n const total = availableFromA + availableFromB;\n vis += total - Math.max(total - c, 0);\n }\n }\n \n return vis;\n};", "solution_java": "class Solution {\n public int reachableNodes(int[][] edges, int maxMoves, int n) {\n int[][] graph = new int[n][n];\n for ( int[] t: graph ) {\n Arrays.fill(t, -1);\n }\n for ( int[] t: edges ) {\n graph[t[0]][t[1]] = t[2];\n graph[t[1]][t[0]] = t[2];\n }\n PriorityQueue heap = new PriorityQueue<>( (a, b) -> b[1]-a[1] );\n int ans = 0;\n boolean[] vis = new boolean[n];\n heap.offer(new int[]{0, maxMoves});\n while ( !heap.isEmpty() ) {\n int[] info = heap.poll();\n int nearestNodeId = info[0];\n int maxMovesRemaining = info[1];\n if ( vis[nearestNodeId] ) {\n continue;\n }\n // visiting the current node\n vis[nearestNodeId] = true;\n // since we visited this node we increment our counter\n ans++;\n for ( int i=0; i=graph[nearestNodeId][i]+1 ) {\n heap.offer( new int[] {i, maxMovesRemaining-graph[nearestNodeId][i]-1} );\n }\n int movesTaken = Math.min(maxMovesRemaining, graph[nearestNodeId][i]);\n graph[nearestNodeId][i] -= movesTaken;\n graph[i][nearestNodeId] -= movesTaken;\n ans += movesTaken;\n }\n }\n }\n return ans;\n }\n}", "solution_c": " class Solution {\n public:\n int reachableNodes(vector>& edges, int maxMoves, int n) {\n const int INF = 1e8;\n vector> g(n);\n for(auto i: edges){\n g[i[0]].push_back({i[1],i[2]});\n g[i[1]].push_back({i[0],i[2]});\n }\n \n priority_queue, vector>, greater> > pq;\n pq.push({0, 0}); //distance,node\n vector d(n, INF);\n d[0] = 0;\n \n while(!pq.empty()){\n int dist = pq.top().first;\n int node = pq.top().second;\n pq.pop();\n //if(d[u.second]!=u.first) continue;\n for(auto it:g[node]){\n if(d[it.first]>dist+it.second+1) //since number of edges=nodes in between+1\n {\n d[it.first]=dist+it.second+1;\n pq.push({d[it.first], it.first});\n }\n }\n }\n //now we have minimum distances to reach each node, so check how many reachable with minMoves\n int ans = 0;\n for(int i = 0; i < n; ++i) { // add 1 for nodes that can be visited\n if(d[i] <= maxMoves) \n ans++; \n } \n \n\n /*\n Now add for intermediate newly added nodes\n Eg. 0->1 and 10 in between\n\n Visitable from 0 -> maxMoves-(dist/moves already covered by 0 (from source)) \n Visitable from 1 -> maxMoves-(dist/moves already covered by 1 (from source))\n \n To calculate Extra nodes I can visit we follow above\n */\n for(auto i : edges) {\n int src=i[0],dest=i[1], between=i[2];\n int x = max(0, (maxMoves - d[src])); // nodes visited using edge e[0]->e[1]\n int y = max(0, (maxMoves - d[dest])); // nodes visited using edge e[1]->e[0]\n ans += min(between, x + y); //minimum to avoid overlapping in counting\n }\n return ans;" }, { "title": "Random Pick with Weight", "algo_input": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.\n\nYou need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).\n\n\n\tFor example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).\n\n\n \nExample 1:\n\nInput\n[\"Solution\",\"pickIndex\"]\n[[[1]],[]]\nOutput\n[null,0]\n\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n\n\nExample 2:\n\nInput\n[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\n\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n\n\n \nConstraints:\n\n\n\t1 <= w.length <= 104\n\t1 <= w[i] <= 105\n\tpickIndex will be called at most 104 times.\n\n", "solution_py": "class Solution(object):\n\tdef __init__(self, w):\n\t\t\"\"\"\n\t\t:type w: List[int]\n\t\t\"\"\"\n\t\t#Cumulative sum\n\t\tself.list = [0] * len(w)\n\n\t\ts = 0\n\t\tfor i, n in enumerate(w):\n\t\t\ts += n\n\t\t\tself.list[i] = s\n\n\n\tdef pickIndex(self):\n\t\t\"\"\"\n\t\t:rtype: int\n\t\t\"\"\"\n\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()", "solution_js": "class Solution {\n constructor(nums) {\n this.map = new Map();\n this.sum = 0;\n \n nums.forEach((num, i) => {\n this.sum += num;\n this.map.set(this.sum, i);\n })\n }\n pickIndex = function() {\n const random_sum = Math.floor(Math.random() * this.sum);\n return this.fetchIndexUsingBS(random_sum);\n }\n fetchIndexUsingBS = function(target) {\n const sums = Array.from(this.map.keys());\n let lo = 0,\n hi = sums.length - 1,\n mid;\n \n while(lo <= hi) {\n mid = Math.floor((hi - lo)/2) + lo;\n // if((mid === 0 || sums[mid - 1] < target) && sums[mid] >= target) {\n // return this.map.get(sums[mid]);\n // }\n if(sums[mid] > target) {\n hi = mid - 1;\n } else {\n lo = mid + 1;\n }\n }\n return lo;\n }\n}", "solution_java": "class Solution {\n\n private int[] prefixSum;\n private Random random;\n\n public Solution(int[] w) {\n for (int i = 1; i < w.length; i++)\n w[i] += w[i - 1];\n prefixSum = w;\n random = new Random();\n }\n\n public int pickIndex() {\n int num = 1 + random.nextInt(prefixSum[prefixSum.length - 1]); // Generate random number between 1 and total sum of weights\n int left = 0;\n int right = prefixSum.length - 1;\n\n while (left < right) {\n int mid = (left + right) / 2;\n if (num == prefixSum[mid])\n return mid;\n else if (num < prefixSum[mid])\n right = mid;\n else\n left = mid + 1;\n }\n return left;\n }\n}", "solution_c": "class Solution {\npublic:\n vector cumW; \n Solution(vector& w) {\n // initialising random seeder\n srand(time(NULL));\n // populating the cumulative weights vector\n cumW.resize(w.size());\n cumW[0] = w[0];\n for (int i = 1; i < w.size(); i++) cumW[i] = cumW[i - 1] + w[i];\n }\n \n int pickIndex() {\n return upper_bound(begin(cumW), end(cumW), rand() % cumW.back()) - begin(cumW);\n }\n};" }, { "title": "Beautiful Arrangement II", "algo_input": "Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:\n\n\n\tSuppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.\n\n\nReturn the list answer. If there multiple valid answers, return any of them.\n\n \nExample 1:\n\nInput: n = 3, k = 1\nOutput: [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n\n\nExample 2:\n\nInput: n = 3, k = 2\nOutput: [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n\n\n \nConstraints:\n\n\n\t1 <= k < n <= 104\n\n", "solution_py": "class Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n # n = 8, k = 5\n # 1 2 3 8 4 7 5 6\n # 1 1 5 4 3 2 1\n res = list(range(1,n-k+1))\n sign, val = 1, k\n for i in range(k):\n res.append(res[-1]+sign*val)\n sign *= -1\n val -= 1\n return res", "solution_js": "var constructArray = function(n, k) {\n const result = [];\n let left = 1;\n let right = n;\n\n for (let index = 0; index < n; index++) {\n if (k === 1) {\n result.push(left++);\n continue;\n }\n const num = k & 1 ? left++ : right--;\n result.push(num);\n k -= 1;\n }\n\n return result;\n};", "solution_java": "class Solution {\n public int[] constructArray(int n, int k) {\n int [] result = new int[n];\n result[0] = 1;\n int sign = 1;\n for(int i = 1 ; i < n; i++, k--){\n if(k > 0){\n result[i] = result[i-1] + k * sign;\n sign *= -1;\n }\n else{\n result[i] = i+1;\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector constructArray(int n, int k) {\n int diff = n - k;\n int lo = 1;\n int hi = n;\n vector out;\n int i = 0; \n\t\t// we generate a difference of 1 between subsequent elements for the first n-k times.\n while(i < diff){\n out.push_back(lo);\n lo++;\n i++;\n }\n bool flag = true;\n\t\t//Now we go zig zag to generate k unique differences, the last one will be automatically taken care\n\t\t//as the difference between last two elements will be one which we have already generated above.\n for(int i = out.size() ; i < n ; i++){\n //flag to alternatively zig zag\n\t\t if(flag){\n out.push_back(hi);\n hi--;\n flag = false;\n }\n else{\n out.push_back(lo);\n lo++;\n flag = true;\n }\n }\n return out;\n }\n};" }, { "title": "Longest Consecutive Sequence", "algo_input": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.\n\nYou must write an algorithm that runs in O(n) time.\n\n \nExample 1:\n\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\n\n\nExample 2:\n\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n\n\n \nConstraints:\n\n\n\t0 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution(object):\n def longestConsecutive(self, nums):\n ans=0\n nums=set(nums)\n count=0\n for i in nums:\n if i-1 not in nums:\n j=i\n count=0\n while j in nums:\n count+=1\n j+=1\n ans=max(ans,count) \n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestConsecutive = function(nums) {\n if(nums.length === 1){\n return 1\n }\n if(nums.length === 0){\n return 0\n }\n nums.sort((a, b) => a - b)\n let result = 1\n let streak = 1\n let i = 0\n while(i < nums.length - 1){\n if(nums[i] == nums[i + 1]) {\n i++ \n continue\n }\n if(nums[i] == nums[i + 1] - 1){\n streak++\n if(streak > result){\n result = streak\n }\n } else {\n streak = 1\n }\n i++\n }\n return result\n};", "solution_java": "class Solution {\n public int longestConsecutive(int[] nums) {\n Set storage = new HashSet();\n \n for(int i = 0; i < nums.length; i++){\n storage.add(nums[i]);\n }\n \n int maxL = 0;\n \n for(int i = 0; i < nums.length; i++){\n \n //check if nums[i] id present in set or not\n //since after checking in set we remove the element from \n //set, there is no double calculation for same sequence \n if(storage.contains(nums[i])){\n storage.remove(nums[i]);\n \n int dec = nums[i]-1;\n int inc = nums[i]+1;\n int tempL = 1;\n \n //check both ways from nums[i] and calculate \n //tempL. since we are removing elements from \n //set we only calculate once for every sequence.\n \n while(storage.contains(dec)){\n storage.remove(dec);\n dec--;\n tempL++;\n }\n \n while(storage.contains(inc)){\n storage.remove(inc);\n inc++;\n tempL++;\n }\n \n \n maxL = Math.max(maxL, tempL);\n \n }\n }\n \n return maxL;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestConsecutive(vector& nums) {\n \n set hashSet;\n \n int longestConsecutiveSequence = 0; \n \n for(auto it : nums){\n hashSet.insert(it);\n }\n \n for(auto it : nums){\n \n if(!hashSet.count(it-1)){\n \n int count = 1;\n \n while(hashSet.count(it+count)) ++count;\n \n longestConsecutiveSequence = max(count,longestConsecutiveSequence);\n \n }\n \n }\n \n return longestConsecutiveSequence;\n }\n};" }, { "title": "Remove Digit From Number to Maximize Result", "algo_input": "You are given a string number representing a positive integer and a character digit.\n\nReturn the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.\n\n \nExample 1:\n\nInput: number = \"123\", digit = \"3\"\nOutput: \"12\"\nExplanation: There is only one '3' in \"123\". After removing '3', the result is \"12\".\n\n\nExample 2:\n\nInput: number = \"1231\", digit = \"1\"\nOutput: \"231\"\nExplanation: We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".\n\n\nExample 3:\n\nInput: number = \"551\", digit = \"5\"\nOutput: \"51\"\nExplanation: We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".\n\n\n \nConstraints:\n\n\n\t2 <= number.length <= 100\n\tnumber consists of digits from '1' to '9'.\n\tdigit is a digit from '1' to '9'.\n\tdigit occurs at least once in number.\n\n", "solution_py": "class Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n \n # Initializing the last index as zero\n last_index = 0\n \n #iterating each number to find the occurences, \\\n # and to find if the number is greater than the next element \\ \n\n for num in range(1, len(number)):\n \n # Handling [case 1] and [case 2]\n if number[num-1] == digit:\n if int(number[num]) > int(number[num-1]):\n return number[:num-1] + number[num:]\n else:\n last_index = num - 1\n \n # If digit is the last number (last occurence) in the string [case 3]\n if number[-1] == digit:\n last_index = len(number) - 1\n\n return number[:last_index] + number[last_index + 1:]", "solution_js": "/**\n * @param {string} number\n * @param {character} digit\n * @return {string}\n */\nvar removeDigit = function(number, digit) {\n\n let str = [];\n let flag = 0;\n for (let i = 0; i < number.length; i++) {\n if (number[i] == digit ) {\n let temp = number.substring(0, i) + number.substring(i+1);\n str.push(temp);\n }\n }\n\n str.sort();\n return str[str.length-1];\n};", "solution_java": "class Solution {\n public String removeDigit(String number, char digit) {\n List digits = new ArrayList<>();\n for (int i = 0; i < number.length(); i++) {\n if (number.charAt(i) == digit) {\n String stringWithoutDigit = number.substring(0, i) + number.substring(i + 1);\n digits.add(stringWithoutDigit);\n }\n }\n Collections.sort(digits);\n return digits.get(digits.size() - 1);\n }\n}", "solution_c": "class Solution {\npublic:\n string removeDigit(string number, char digit) {\n string res = \"\";\n for(int i=0; i str:\n st,sp=[],[]\n for i,ch in enumerate(s):\n if ch.isalpha():\n st.append(ch)\n else:\n sp.append([i,ch])\n st=st[::-1]\n for i in sp:\n st.insert(i[0],i[1])\n return (''.join(st))", "solution_js": "var reverseOnlyLetters = function(s) {\n let valid = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n let arr = s.split('')\n \n let r = arr.length - 1;\n let l = 0;\n \n while (l < r) {\n while (!valid.includes(arr[l]) && l < r) {\n l++;\n continue;\n }\n \n while (!valid.includes(arr[r]) && l < r) {\n r--;\n continue\n }\n \n if (l >= r) break;\n \n [arr[l], arr[r]] = [arr[r], arr[l]];\n l++;\n r--;\n }\n \n \n return arr.join('')\n\t```", "solution_java": "class Solution {\n public String reverseOnlyLetters(String s) {\n // converting the string to the charArray...\n char[] ch = s.toCharArray();\n\n int start = 0;\n int end = s.length()-1;\n\n // Storing all the english alphabets in a hashmap so that the searching becomes easy...\n HashMap hash = new HashMap<>();\n for(int i=0 ; i<26 ;i++){\n hash.put((char)(97+i) , 1);\n }\n for(int i=0 ; i<26 ; i++){\n hash.put((char)(65+i) , 1);\n }\n\n // using two while loops ..since the constraints are too less thats why we can prefer nested loops approach..\n while(startstart&&!hash.containsKey(ch[end])){\n end--;\n }\n\n // swapping the array elements..\n char temp = ch[start];\n ch[start] = ch[end];\n ch[end] = temp;\n\n start++;\n end--;\n }\n\n // converting the charArray to the string again..\n String ans = new String(ch);\n return ans;\n\n // Time Complexity : O(N) (since the loops will run only till the number of charcters in the string..)\n // Space Complexity : O(N) since we used hashmap..\n }\n}", "solution_c": "class Solution {\npublic:\n string reverseOnlyLetters(string s) {\n int a=0,b=s.size()-1;\n for(;a='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n {\n char z=s[a];\n s[a]=s[b];\n s[b]=z;\n a++;\n b--;\n }\n else if(!((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n {\n a++;\n }\n else if(((s[a]>='a'&&s[a]<='z')||(s[a]>='A'&&s[a]<='Z'))&&!((s[b]>='a'&&s[b]<='z')||(s[b]>='A'&&s[b]<='Z')))\n b--;\n else{\n a++;\n b--;\n }\n\n }\n return s;\n }\n};" }, { "title": "Sum of Beauty in the Array", "algo_input": "You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:\n\n\n\t2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.\n\t1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.\n\t0, if none of the previous conditions holds.\n\n\nReturn the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.\n\n \nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.\n\n\nExample 2:\n\nInput: nums = [2,4,6,4]\nOutput: 1\nExplanation: For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.\n\n\nExample 3:\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.\n\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 105\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n n = len(nums)\n max_dp = [0] * n\n min_dp = [float(inf)] * n\n max_dp[0] = nums[0]\n min_dp[-1] = nums[-1]\n \n for i in range(1, n):\n max_dp[i] = max(nums[i], max_dp[i-1])\n \n for i in range(n-2, -1, -1):\n min_dp[i] = min(nums[i], min_dp[i+1])\n \n ans = 0\n for i in range(1, n-1):\n if max_dp[i-1] < max_dp[i] and nums[i] < min_dp[i+1]:\n ans += 2\n elif nums[i-1] < nums[i] < nums[i+1]:\n ans += 1\n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar sumOfBeauties = function(nums) {\n let min = nums[0], max = Infinity, maxArr = [], total = 0;\n\n // Creating an array, which will keep the record of minimum values from last index\n for(let i=nums.length-1; i>1; i--) {\n if(nums[i] < max) max = nums[i];\n maxArr.push(max);\n }\n\n // iterating through array to check the given conditions\n for(let i=1; i min) min = nums[i-1];\n\n // Checking conditions\n if(nums[i] < maxArr.pop() && min < nums[i]) total += 2;\n else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) total += 1;\n }\n\n return total;\n};", "solution_java": "class Solution {\n public int sumOfBeauties(int[] nums) {\n boolean[] left = new boolean[nums.length];\n boolean[] right = new boolean[nums.length];\n\n left[0] = true;\n int leftMax = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > leftMax) {\n left[i] = true;\n leftMax = nums[i];\n }\n }\n\n right[nums.length-1] = true;\n int rightMin = nums[nums.length-1];\n for(int i = nums.length-2; i >= 0; i--) {\n if(nums[i] < rightMin) {\n right[i] = true;\n rightMin = nums[i];\n }\n }\n\n int beautyCount = 0;\n for(int i = 1; i < nums.length-1; i++) {\n if(left[i] && right[i]) {\n beautyCount += 2;\n }\n\n else if(nums[i-1] < nums[i] && nums[i] < nums[i+1]) {\n beautyCount += 1;\n }\n\n }\n return beautyCount;\n }\n}", "solution_c": "class Solution {\npublic:\n int sumOfBeauties(vector& nums) {\n int n=nums.size();\n vectorright;\n vectorleft;\n int low=nums[0];\n for(int i=0;i=0;i--){\n \n right.push_back(low);\n low=min(low,nums[i]);\n }\n reverse(right.begin(),right.end());\n int ans=0;\n for(int i=1;ileft[i] && nums[i]nums[i-1] && nums[i] bool:\n n1, n2, t = jug1Capacity, jug2Capacity, targetCapacity\n if n1 == t or n2 == t or n1 + n2 == t:\n return True\n if n1 + n2 < t:\n return False\n if n1 < n2:\n n1, n2 = n2, n1\n stack = []\n visited = set()\n d = n1 - n2\n if d == t:\n return True\n while d > n2:\n d -= n2\n if d == t:\n return True\n stack.append(d)\n while stack:\n #print(stack)\n d = stack.pop()\n visited.add(d)\n n = n1 + d\n if n == t:\n return True\n n = n1 - d\n if n == t:\n return True\n while n > n2:\n n -= n2\n if n == t:\n return True\n if n < n2 and n not in visited:\n stack.append(n)\n n = n2 - d\n if n == t:\n return True\n if n not in visited:\n stack.append(n)\n return False", "solution_js": "var canMeasureWater = function(jug1Capacity, jug2Capacity, targetCapacity) {\n\tconst gcd = (x, y) => y === 0 ? x : gcd(y, x % y);\n\n\treturn jug1Capacity + jug2Capacity >= targetCapacity && \n\t\ttargetCapacity % gcd(jug1Capacity, jug2Capacity) === 0;\n};", "solution_java": "class Solution {\n private static int gcd(int a,int b){\n if(b==0)return a;\n return gcd(b,a%b);\n }\n public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n if(targetCapacity>jug1Capacity+jug2Capacity){\n return false;\n }\n int g=gcd(jug1Capacity,jug2Capacity);\n return (targetCapacity%g==0);\n }\n}", "solution_c": "class Solution {\npublic:\n bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n \n if(targetCapacity > jug1Capacity + jug2Capacity)\n return false;\n \n vector dp(jug1Capacity + jug2Capacity + 1, -1);\n return helper(0, jug1Capacity, jug2Capacity, targetCapacity, dp);\n }\n \n bool helper(int tmp, int &jug1Capacity, int &jug2Capacity, int &targetCapacity, vector &dp)\n {\n if(tmp < 0 || tmp > jug1Capacity + jug2Capacity)\n return false;\n \n if(tmp == targetCapacity)\n return true;\n \n if(dp[tmp] != -1)\n return dp[tmp];\n \n dp[tmp] = false; \n if(helper(tmp + jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n return dp[tmp] = true;\n \n if(helper(tmp - jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n return dp[tmp] = true;\n \n if(helper(tmp + jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n return dp[tmp] = true;\n \n if(helper(tmp - jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))\n return dp[tmp] = true;\n \n return dp[tmp] = false;\n }\n};" }, { "title": "Majority Element II", "algo_input": "Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.\n\n \nExample 1:\n\nInput: nums = [3,2,3]\nOutput: [3]\n\n\nExample 2:\n\nInput: nums = [1]\nOutput: [1]\n\n\nExample 3:\n\nInput: nums = [1,2]\nOutput: [1,2]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5 * 104\n\t-109 <= nums[i] <= 109\n\n\n \nFollow up: Could you solve the problem in linear time and in O(1) space?\n", "solution_py": "class Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n \n #Boyer Moore Voting Algo (As used in ME1 ques) \n #now we can observe that there cannot be more than two elements occuring more than n//3 times in an array\n #so find two majority elements(me=majority element)\n \n\n n=len(nums)\n req=n//3 #for an element to be ME required number of times present \n\n c1=0 #count 1\n c2=0 #count 2\n me1=None #majority element 1\n me2=None #majority element 2\n\n for i in nums:\n if i == me1:\n c1+=1\n\n elif i == me2:\n c2+=1\n\n elif c1 == 0:\n me1=i\n c1=1\n\n elif c2 == 0:\n me2=i\n c2=1\n\n else:\n c1-=1\n c2-=1\n #here we have found our majority elements now check if the found majority element is ME\n # print(me1,me2)\n\n #check if the found majority element is ME\n c1=0\n c2=0\n for i in nums:\n if i==me1:\n c1+=1\n if i==me2:\n c2+=1\n # print(c1,c2)\n\n if c1 > req and c2 > req:\n\n return [me1,me2]\n\n elif c1> req :\n return [me1]\n\n elif c2> req :\n return [me2]", "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar majorityElement = function(nums) {\n const objElement = {};\n const timesVar = Math.floor(nums.length/3);\n const resultSet = new Set();\n\n for(var indexI=0; indexItimesVar) resultSet.add(nums[indexI]);\n }\n\n return [...resultSet];\n};", "solution_java": "class Solution {\n public List majorityElement(int[] nums) {\n int val1 = nums[0], val2 = nums[0], cnt1 = 1, cnt2 = 0;\n for(int i = 1; i < nums.length; i++){\n if(val1 == nums[i]){\n cnt1++;\n } else if(val2 == nums[i]){\n cnt2++;\n } else{\n if(cnt1 == 0){\n val1 = nums[i];\n cnt1++;\n } else if(cnt2 == 0){\n val2 = nums[i];\n cnt2++;\n } else{\n cnt1--;\n cnt2--;\n }\n }\n }\n int check1 = 0, check2 = 0;\n for(int i = 0; i < nums.length; i++){\n if(val1 == nums[i])check1++;\n else if(val2 == nums[i])check2++;\n }\n List ans = new ArrayList<>();\n if(check1 > nums.length / 3) ans.add(val1);\n if(check2 > nums.length / 3) ans.add(val2);\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector majorityElement(vector& nums) {\n\n int n = nums.size();\n\n vector result;\n\n int num1 = -1 , num2 = -1 , count1 = 0 , count2 = 0;\n\n for(auto it : nums){\n\n if(num1 == it) ++count1;\n else if(num2 == it) ++count2;\n else if(count1 == 0){\n num1 = it;\n count1 = 1;\n }\n else if(count2 == 0){\n num2 =it;\n count2 = 1;\n }\n else{\n --count1;\n --count2;\n }\n\n }\n\n count1 = 0;\n count2 = 0;\n\n for(auto it : nums){\n\n if(it == num1) ++count1;\n else if(it == num2) ++count2;\n\n }\n\n if(count1>(n/3)) result.push_back(num1);\n if(count2>(n/3)) result.push_back(num2);\n\n return result;\n\n }\n};" }, { "title": "Reformat Phone Number", "algo_input": "You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.\n\nYou would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:\n\n\n\t2 digits: A single block of length 2.\n\t3 digits: A single block of length 3.\n\t4 digits: Two blocks of length 2 each.\n\n\nThe blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.\n\nReturn the phone number after formatting.\n\n \nExample 1:\n\nInput: number = \"1-23-45 6\"\nOutput: \"123-456\"\nExplanation: The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".\n\n\nExample 2:\n\nInput: number = \"123 4-567\"\nOutput: \"123-45-67\"\nExplanation: The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".\n\n\nExample 3:\n\nInput: number = \"123 4-5678\"\nOutput: \"123-456-78\"\nExplanation: The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".\n\n\n \nConstraints:\n\n\n\t2 <= number.length <= 100\n\tnumber consists of digits and the characters '-' and ' '.\n\tThere are at least two digits in number.\n\n", "solution_py": "class Solution:\n def reformatNumber(self, number: str) -> str:\n s = number.replace(\" \", \"\").replace(\"-\", \"\")\n pieces = list()\n while s:\n if len(s) == 2:\n pieces.append(s)\n break\n elif len(s) == 4:\n pieces.append(s[:2])\n pieces.append(s[2:])\n break\n else:\n pieces.append(s[:3])\n s = s[3:]\n return \"-\".join(pieces)", "solution_js": "var reformatNumber = function(number) {\n let numArr = number.replace(/-/g,'').replace(/ /g,'').split('')\n let res = ''\n while(numArr.length >= 4){\n numArr.length == 4 ?\n res += numArr.splice(0,2).join('') +'-'+numArr.splice(0,2).join('') :\n res += numArr.splice(0,3).join('') + '-'\n }\n res += numArr.join('')\n return res\n};", "solution_java": "class Solution {\n String modifiedNumber=\"\";\n public String reformatNumber(String number) {\n modifiedNumber=number.replace(\" \",\"\");\n modifiedNumber=modifiedNumber.replace(\"-\",\"\");\n int l=modifiedNumber.length();\n if(l<=3){\n return modifiedNumber;\n } else if(l==4){\n return modifiedNumber.substring(0,2)+\"-\"+ modifiedNumber.substring(2,4);\n } else {\n modifiedNumber=modifiedNumber.substring(0,3)+\"-\"+reformatNumber(modifiedNumber.substring(3,l));\n }\n return modifiedNumber;\n }\n}", "solution_c": "class Solution {\npublic:\n string reformatNumber(string number) {\n\n string temp; // stores the digits from string number\n string ans; //stores final answer\n int n = number.size();\n\n for(auto ch:number)\n if(isdigit(ch)) temp += ch;\n\n int len = temp.size();\n int i = 0;\n\n while(len>0){\n //check for different values of \"len\"\n if(len > 4){ //if len > 4 -> make grp of 3 digits\n ans += temp.substr(i,i+3);\n temp.erase(i,3);\n len = len-3;\n ans += \"-\";\n }\n\n else if(len == 3){ //if len == 3 -> make grp of 3 digits\n ans += temp.substr(i,i+3);\n temp.erase(i,3);\n len = len-3;\n ans += \"-\";\n }\n\n else if(len == 2){ //if len == 2 -> make grp of 2 digits\n ans += temp.substr(i,i+2);\n temp.erase(i,2);\n len = len-2;\n ans += \"-\";\n }\n\n else if(len == 4){ //if len == 4 -> make 1 grp of 2 digits & reduce the length by 2 units, in the next iteration it will automatically catch (len==2) condition\n ans += temp.substr(i,i+2);\n temp.erase(i,2);\n ans += \"-\";\n // ans += temp.substr(i,i+2); ------(1)\n // temp.erase(i,2); ------(2)\n // ans += \"-\"; ------(3)\n len = len-2; // *len = len-4* can be edited to *len = len-2*------(4)\n\n }\n\n }\n\n ans.pop_back();\n return ans;\n }\n};" }, { "title": "Arithmetic Slices", "algo_input": "An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n\n\n\tFor example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.\n\n\nGiven an integer array nums, return the number of arithmetic subarrays of nums.\n\nA subarray is a contiguous subsequence of the array.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4]\nOutput: 3\nExplanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n\n\nExample 2:\n\nInput: nums = [1]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5000\n\t-1000 <= nums[i] <= 1000\n\n", "solution_py": "#Baraa\nclass Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n \"\"\"\n what is (x * (x + 1)) // 2? this is series sum formula between n and 1\n\n which means: n + (n - 1) + (n - 2) + (n - 3) .... + 1\n\n when we have a total number of 10 elements that form an arithmetic sum\n eg: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n we can form subarrays up until count - 2\n which means 1,2,3,4,5,6,7,8\n if we take 7 for example --> [7, 8, 9, 10] or [7, 8, 9]\n\n we cant take [9, 10] as subarray as its length < 3\n \"\"\"\n\n #this is done for termination only\n nums += [-float(\"inf\")]\n n = len(nums)\n #base case\n if n < 3:\n return 0\n res = 0\n #store inital difference we have\n prev_diff = nums[1] - nums[0]\n #because we calculated an initial difference we store 2 inside count\n #which represents number of elements\n count = 2\n for i in range(2, n):\n diff = nums[i] - nums[i - 1]\n if prev_diff != diff:\n x = count - 2\n res = res + (x * (x + 1)) // 2\n prev_diff = diff\n count = 2\n else:\n count += 1\n prev_diff = diff\n return res", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numberOfArithmeticSlices = function(nums) {\n nums.push(-2000)\n let count = 0 \n let dist = nums[1]-nums[0]\n let start = 0\n \n for (let i = 1; i < nums.length; i++) {\n if (nums[i]-nums[i-1] !== dist) {\n \n let len = i - start\n start = i-1\n dist = nums[i] - nums[i-1]\n \n // count the length of each largest AS and add to sum \n // of len = 5 => the number of sub AS = 1 (len = 5) + 2 (len = 4) + 3 (len = 3)\n for (let k = 3; k <=len; k++) {\n count += len - k + 1\n }\n \n }\n }\n \n return count\n};", "solution_java": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n = nums.length;\n if (n < 3) {\n return 0;\n }\n int[] dp = new int[n - 1];\n dp[0] = nums[1] - nums[0];\n for (int i = 2; i < n; i++) {\n dp[i - 1] = nums[i] - nums[i - 1];\n }\n int si = 0;\n int count = 0;\n for (int i = 1; i < n - 1; i++) {\n if (dp[i] == dp[i - 1]) {\n count += (i - si);\n } else {\n si = i;\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfArithmeticSlices(vector& nums) {\n int n=nums.size(),i,j,count=0,comm_diff;\n for(i=0;i<=n-3;i++)\n {\n comm_diff = nums[i+1]-nums[i];\n for(j=i+1;j=3)\n {\n count++;\n }\n }\n else\n {\n break;\n }\n }\n }\n return count;\n }\n};" }, { "title": "Tiling a Rectangle with the Fewest Squares", "algo_input": "Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.\n\n \nExample 1:\n\n\n\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\n\nExample 2:\n\n\n\nInput: n = 5, m = 8\nOutput: 5\n\n\nExample 3:\n\n\n\nInput: n = 11, m = 13\nOutput: 6\n\n\n \nConstraints:\n\n\n\t1 <= n, m <= 13\n\n", "solution_py": "class Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n # try brute force backtracking?\n board = [[0 for _ in range(n)] for _ in range(m)]\n\n ans = math.inf\n def bt(counts):\n nonlocal ans\n if counts >= ans:\n return\n \n pos = None\n found = False\n for row in range(m):\n for col in range(n):\n if board[row][col] == 0:\n pos = (row, col)\n found = True\n break\n if found:\n break\n if not found:\n ans = min(ans, counts)\n return\n\n # see how many difference size of squares we can place from this spot\n r, c = pos\n offset = 0\n while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n offset += 1\n # max can place size is offset\n for row in range(r, r + offset):\n for col in range(c, c + offset):\n board[row][col] = 1\n # do bt and shrink\n while offset > 0:\n bt(counts + 1)\n # shrink\n for row in range(r, r + offset):\n board[row][c + offset - 1] = 0\n for col in range(c, c + offset):\n board[r + offset - 1][col] = 0\n offset -= 1\n\n bt(0)\n return ans", "solution_js": "var tilingRectangle = function(n, m) {\n const queue = [[new Array(n).fill(0), 0]];\n while (true) {\n const [curr, numSquares] = queue.shift();\n let min = { height: Infinity, start: Infinity, end: Infinity }\n for (let i = 0; i < n; i++) {\n if (curr[i] < min.height) {\n min.height = curr[i];\n min.start = i;\n min.end = i + 1;\n } else if (curr[i] === min.height && min.end === i) {\n min.end++\n }\n }\n if (min.height === m) return numSquares;\n const largestSquare = Math.min(m - min.height, min.end - min.start);\n for (let sqWidth = largestSquare; sqWidth; sqWidth--) {\n const next = curr.slice();\n for (let i = min.start; i < min.start + sqWidth; i++) {\n next[i] += sqWidth;\n }\n queue.push([next, numSquares + 1]);\n }\n }\n};", "solution_java": "class Solution {\n int ret; // store the final result\n int m, n; // m is the height, and n is the width\n\t\n\t// Note: original signature is changed from n,m to m,n\n public int tilingRectangle(int m, int n) { \n this.m = m;\n this.n = n;\n this.ret = m * n; // initilize the result as m*n if cut rectangle to be all 1*1 squares\n int[][] mat = new int[m][n]; // record the status of every location, 0 means not covered, 1 means covered\n backtrack(mat, 0); // start backtracking\n return ret;\n }\n \n\t// the size means how many squares cut now\n public void backtrack(int[][] mat, int size) {\n if (size > ret) return; // if we already have more squares than the min result, no need to go forward\n \n\t\t// find out the leftmost and topmost postion where is not covered yet\n int x = -1, y = -1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if (mat[i][j] == 0) {\n x = i;\n y = j;\n break;\n }\n }\n if (x != -1 && y != -1) break;\n }\n\t\t// if not found, we know that all positions are covered\n if (x == -1 && y == -1) {\n\t\t // update the result\n ret = Math.min(size, ret);\n }\n else {\n int len = findWidth(x, y, mat); // find the maximum width to cut the square\n while(len >= 1) {\n cover(x, y, len, mat, 1); // cover the current square\n backtrack(mat, size + 1);\n cover(x, y, len, mat, 0); // uncover the previous result\n len--; // decrement the square width by 1\n }\n }\n }\n \n public int findWidth(int x, int y, int[][] mat) {\n int len = 1;\n while(x + len < m && y + len < n) {\n boolean flag = true; // flag means the len is reachable\n for (int i = 0; i <= len; i++) {\n\t\t\t // check the right i-th column and the bottom i-th row away from (x, y) \n if (mat[x + i][y + len] == 1 || mat[x + len][y + i] == 1) {\n flag = false;\n break;\n }\n }\n if (!flag) break;\n len++;\n }\n return len;\n }\n \n public void cover(int x, int y, int len, int[][] mat, int val) {\n for (int i = x; i < x + len; i++) {\n for (int j = y; j < y + len; j++) {\n mat[i][j] = val;\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int solve(int n, int m, vector>& dp) {\n if(n<0 || m<0) return 0;\n if(m==n) return 1;\n \n // this is special case\n if((m==13 && n==11) || (m==11 && n==13)) return dp[n][m]=6;\n \n if(dp[n][m]!=0) return dp[n][m];\n \n int hz=1e9;\n for(int i=1;i<=n/2;i++) {\n hz = min(hz, solve(i,m,dp) + solve(n-i,m,dp));\n }\n \n int vert = 1e9;\n for(int i=1;i<=m/2;i++) {\n vert = min(vert, solve(n,m-i,dp) + solve(n,i,dp));\n }\n \n return dp[n][m] = min(hz,vert);\n }\n \n int tilingRectangle(int n, int m) {\n vector> dp (n+1,vector (m+1,0));\n return solve(n,m,dp);\n }\n};" }, { "title": "Minimum Moves to Convert String", "algo_input": "You are given a string s consisting of n characters which are either 'X' or 'O'.\n\nA move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.\n\nReturn the minimum number of moves required so that all the characters of s are converted to 'O'.\n\n \nExample 1:\n\nInput: s = \"XXX\"\nOutput: 1\nExplanation: XXX -> OOO\nWe select all the 3 characters and convert them in one move.\n\n\nExample 2:\n\nInput: s = \"XXOX\"\nOutput: 2\nExplanation: XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's.\n\nExample 3:\n\nInput: s = \"OOOO\"\nOutput: 0\nExplanation: There are no 'X's in s to convert.\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 1000\n\ts[i] is either 'X' or 'O'.\n\n", "solution_py": "class Solution:\n def minimumMoves(self, s: str) -> int:\n i, m = 0, 0\n l = len(s)\n\n while i < l:\n if s[i] != 'X':\n i += 1\n elif 'X' not in s[i:i+1]:\n i += 2\n elif 'X' in s[i:i+2]:\n m += 1\n i += 3\n return m", "solution_js": "var minimumMoves = function(s) {\n let move = 0;\n let i = 0;\n while(i int:\n\n dictx = {}\n\n for each in nums:\n if each not in dictx:\n dictx[each] = 1\n else:\n return each", "solution_js": "var findDuplicate = function(nums) {\n let dup = new Map();\n\n for(let val of nums){\n if(dup.has(val)){\n dup.set(val, dup.get(val) + 1);\n return val;\n }\n else\n dup.set(val, 1);\n }\n};", "solution_java": "class Solution {\n public int findDuplicate(int[] nums) {\n int i = 0; \n while (i < nums.length) {\n\n if (nums[i] != i + 1) {\n int correct = nums[i] - 1;\n if (nums[i] != nums[correct]) {\n swap(nums, i , correct);\n } else {\n return nums[i];\n }\n } else {\n i++;\n }\n }\n return -1;\n }\n static void swap(int[] arr, int first, int second) {\n int temp = arr[first];\n arr[first] = arr[second];\n arr[second] = temp;\n }\n }", "solution_c": " // Please upvote if it helps\nclass Solution {\npublic:\n int findDuplicate(vector& nums) {\n int low = 1, high = nums.size() - 1, cnt;\n\n while(low <= high)\n {\n int mid = low + (high - low) / 2;\n cnt = 0;\n // cnt number less than equal to mid\n for(int n : nums)\n {\n if(n <= mid)\n ++cnt;\n }\n // binary search on left\n if(cnt <= mid)\n low = mid + 1;\n else\n // binary search on right\n high = mid - 1;\n\n }\n return low;\n }\n // for github repository link go to my profile.\n};" }, { "title": "Length of Last Word", "algo_input": "Given a string s consisting of words and spaces, return the length of the last word in the string.\n\nA word is a maximal substring consisting of non-space characters only.\n\n \nExample 1:\n\nInput: s = \"Hello World\"\nOutput: 5\nExplanation: The last word is \"World\" with length 5.\n\n\nExample 2:\n\nInput: s = \" fly me to the moon \"\nOutput: 4\nExplanation: The last word is \"moon\" with length 4.\n\n\nExample 3:\n\nInput: s = \"luffy is still joyboy\"\nOutput: 6\nExplanation: The last word is \"joyboy\" with length 6.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of only English letters and spaces ' '.\n\tThere will be at least one word in s.\n\n", "solution_py": "class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n return len(s.strip().split()[-1])", "solution_js": "var lengthOfLastWord = function(s) {\n s = s.split(\" \");\n if(s[s.length-1] == ``)\n {\n for(var i = s.length-1; i >= 0; i-- )\n {\n if(s[i].length > 0)\n {\n return s[i].length;\n }\n }\n }\n else\n {\n return s[s.length-1].length;\n }\n};", "solution_java": "class Solution {\n public int lengthOfLastWord(String s) {\n int j=s.length()-1,len=0; boolean flag=true;\n while(j>=0 && (flag || (!flag && s.charAt(j)!=' ')))\n if(s.charAt(j--)!=' '){\n flag=false;\n len++;\n }\n return len;\n }\n}", "solution_c": "class Solution {\npublic:\n int lengthOfLastWord(string s) {\n int count = 0;\n int n = s.size();\n int i = n-1;\n while(i>=0){\n if(s[i]==' '){\n i--;\n if(count >0){\n break;\n }\n }\n else{\n count++;\n i--;\n }\n }\n return count;\n }\n};" }, { "title": "Minimum Average Difference", "algo_input": "You are given a 0-indexed integer array nums of length n.\n\nThe average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.\n\nReturn the index with the minimum average difference. If there are multiple such indices, return the smallest one.\n\nNote:\n\n\n\tThe absolute difference of two numbers is the absolute value of their difference.\n\tThe average of n elements is the sum of the n elements divided (integer division) by n.\n\tThe average of 0 elements is considered to be 0.\n\n\n \nExample 1:\n\nInput: nums = [2,5,3,9,5,3]\nOutput: 3\nExplanation:\n- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.\n\n\nExample 2:\n\nInput: nums = [0]\nOutput: 0\nExplanation:\nThe only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\n", "solution_py": "from itertools import accumulate\n\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n size = len(nums)\n\n nums[::] = list(accumulate(nums))\n total = nums[-1]\n \n min_tuple = [0, sys.maxsize]\n \n for (i, n) in enumerate(nums):\n i = i + 1\n avg_i = floor(n/i)\n \n diff = size - i\n total_avg = floor((total - n) / (diff if diff>0 else 1))\n\n avg = abs( avg_i - total_avg) \n if min_tuple[1] > avg:\n min_tuple[1] = avg\n min_tuple[0] = i - 1\n \n return min_tuple[0]", "solution_js": "```/**\n * @param {number[]} nums\n * @return {number}\n */\n var minimumAverageDifference = function(nums) {\n if (nums.length == 1) return 0;\n let mins = 100000, resultIndex, leftTotal = 0;\n let rightTotal = nums.reduce((a,b)=>a + b);\n let numLength = nums.length;\n nums.forEach((data, index)=> {\n leftTotal += data;\n rightTotal -= data;\n let currentAverageDiff = Math.abs(Math.floor(leftTotal/(index+1)) - Math.floor(rightTotal/(numLength-index-1) || 0));\n if (currentAverageDiff < mins) {\n resultIndex = index;\n mins = currentAverageDiff;\n }\n });\n return resultIndex;\n};", "solution_java": "class Solution {\n public int minimumAverageDifference(int[] nums) {\n if(nums.length == 1){\n return 0;\n }\n int idx = -1;\n long min = Integer.MAX_VALUE;\n long suml = nums[0];\n long sumr = 0;\n for(int i = 1; i < nums.length; i++){\n sumr += nums[i];\n }\n int i = 1;\n int calc = 0;\n int left = 1;\n int right = nums.length - left;\n long[] arr = new long[nums.length];\n while(i < nums.length){\n long diff = Math.abs((suml/left) - (sumr/right));\n arr[calc] = diff;\n if(diff < min){\n min = diff;\n idx = calc;\n }\n suml += nums[i];\n sumr -= nums[i];\n left++;\n right--;\n calc++;\n i++;\n }\n arr[calc] = suml/nums.length;\n if(arr[calc] < min){\n min = arr[calc];\n idx = nums.length - 1;\n }\n // for(i = 0; i < nums.length; i++){\n // System.out.println(arr[i]);\n // }\n return (int)idx;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumAverageDifference(vector& nums) {\n\n int n(size(nums)), minAverageDifference(INT_MAX), index;\n\n long long sumFromFront(0), sumFromEnd(0);\n for (auto& num : nums) sumFromEnd += num;\n\n for (int i=0; i int:\n d,count={},0\n for num in nums:\n d[num] = 0\n\n while head:\n if head.val in d:\n head = head.next\n while head and head.val in d:\n head = head.next\n count += 1\n else:\n head = head.next\n return count", "solution_js": "var numComponents = function(head, nums) {\n let broken = true, count = 0;\n\n while (head) {\n if (nums.includes(head.val) && broken) {\n count++;\n broken = false;\n }\n else if (!nums.includes(head.val)) {\n broken = true;\n }\n\n // reset head as next\n head = head.next\n }\n\n // result\n return count;\n};", "solution_java": "class Solution {\n public int numComponents(ListNode head, int[] nums) {\n int count=0;\n HashSet set=new HashSet();\n for(int i=0;i& nums)\n {\n unordered_set s;\n for(auto &x:nums)\n s.insert(x);\n int count=0;\n while(head!=NULL)\n {\n if(s.find(head->val)!=s.end()) count++;\n while(head!=NULL && s.find(head->val)!=s.end())\n {\n head=head->next;\n }\n if(head!=NULL)\n head=head->next;\n }\n return count;\n }\n};" }, { "title": "Replace All Digits with Characters", "algo_input": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.\n\nThere is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.\n\n\n\tFor example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.\n\n\nFor every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).\n\nReturn s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.\n\n \nExample 1:\n\nInput: s = \"a1c1e1\"\nOutput: \"abcdef\"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'\n\nExample 2:\n\nInput: s = \"a1b2c3d4e\"\nOutput: \"abbdcfdhe\"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists only of lowercase English letters and digits.\n\tshift(s[i-1], s[i]) <= 'z' for all odd indices i.\n\n", "solution_py": "class Solution(object):\n def replaceDigits(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n res = []\n\n for i in range(len(s)):\n if i % 2 == 0:\n res.append(s[i])\n if i % 2 == 1:\n res.append( chr(ord(s[i-1]) + int(s[i])) )\n\n return ''.join(res)", "solution_js": "var replaceDigits = function(s) {\n let res = ''\n for(let i = 0; i < s.length; i++){\n if(i % 2 !== 0){\n res += String.fromCharCode(s[i - 1].charCodeAt() + parseInt(s[i]))\n } else{\n res += s[i]\n }\n\n }\n return res;\n};", "solution_java": "class Solution {\n public String replaceDigits(String s) {\n char[] str = s.toCharArray();\n\n for(int i=0;i bool:\n if self.node[num] == -2:\n self.user[user].add(num)\n self.node[num] = user\n return True\n return False \n\n def unlock(self, num: int, user: int) -> bool:\n if self.node[num] == user: \n del self.node[num]\n self.user[user].remove(num)\n return True\n return False \n\n def upgrade(self, num: int, user: int) -> bool:\n if self.node[num] != -2: return False\n if not self.has_locked_descendant(num): return False\n if self.has_locked_ancester(num): return False\n self.lock(num, user)\n self.unlock_descendant(num)\n return True\n \n def has_locked_descendant(self, num): #function to check if alteast one desendent is lock or not \n has = False\n for child in self.c[num]:\n if self.node[child] != -2:\n return True\n has |= self.has_locked_descendant(child)\n return has \n \n def has_locked_ancester(self, num): # function to check if no parent is locked \n if num == -1: return False\n if self.node[self.p[num]] != -2:\n return True\n return self.has_locked_ancester(self.p[num])\n\n def unlock_descendant(self, num): # function fro unlocking all desendents \n for child in self.c[num]:\n if child in self.node:\n user = self.node[child]\n del self.node[child]\n if user in self.user:\n self.user[user].remove(child)\n self.unlock_descendant(child)", "solution_js": "var LockingTree = function(parent) {\n this.parents = parent;\n this.children = [];\n this.locked = new Map();\n \n for (let i = 0; i < this.parents.length; ++i) {\n this.children[i] = [];\n }\n \n for (let i = 1; i < this.parents.length; ++i) {\n const parent = this.parents[i];\n \n this.children[parent].push(i);\n }\n};\n\nLockingTree.prototype.lock = function(num, user) {\n if (this.locked.has(num)) return false;\n\n this.locked.set(num, user);\n \n return true;\n};\n\nLockingTree.prototype.unlock = function(num, user) {\n if (!this.locked.has(num) || this.locked.get(num) != user) return false;\n \n this.locked.delete(num);\n \n return true;\n};\n\nLockingTree.prototype.upgrade = function(num, user) {\n let isLocked = traverseUp(num, this.parents, this.locked);\n\n if (isLocked) return false;\n\n const queue = [];\n\n isLocked = false;\n\n queue.push(num);\n\n while (queue.length > 0) {\n const node = queue.shift();\n\n if (node != num && this.locked.has(node)) {\n isLocked = true;\n this.locked.delete(node);\n }\n\n for (let i = 0; i < this.children[node].length; ++i) {\n queue.push(this.children[node][i]);\n }\n } \n\n if (!isLocked) return false;\n\n this.locked.set(num, user);\n\n return true;\n\n\n function traverseUp(num, parents, locked) {\n if (locked.has(num)) return true;\n if (num === 0) return false;\n\n const parentIdx = parents[num];\n\n return traverseUp(parentIdx, parents, locked);\n }\n};", "solution_java": "class LockingTree {\n int[] p;\n Map map = new HashMap<>();\n Map> children = new HashMap<>();\n public LockingTree(int[] parent) {\n p = parent;\n for(int i = 0; i < p.length; i ++) {\n children.put(i, new ArrayList<>());\n }\n for(int i = 1; i < p.length; i ++) {\n children.get(p[i]).add(i);\n }\n }\n \n public boolean lock(int num, int user) {\n if(!map.containsKey(num)) {\n map.put(num, user);\n return true;\n } \n return false;\n }\n \n public boolean unlock(int num, int user) {\n if(map.containsKey(num) && map.get(num) == user) {\n map.remove(num);\n return true;\n }\n return false;\n }\n \n public boolean upgrade(int num, int user) {\n //check the node\n if(map.containsKey(num)) return false;\n //check Ancestor\n int ori = num;\n while(p[num] != -1) {\n if(map.get(p[num]) != null) return false;\n num = p[num];\n }\n //check Decendant\n Queue q = new LinkedList<>();\n List child = children.get(ori);\n if(child != null) {\n for(int c : child) q.offer(c);\n }\n boolean lock = false;\n while(!q.isEmpty()) {\n int cur = q.poll();\n if(map.get(cur) != null) {\n lock = true;\n map.remove(cur); // unlock\n }\n List cc = children.get(cur);\n if(cc != null) {\n for(int c : cc) q.offer(c);\n }\n } \n if(!lock) return false;\n map.put(ori, user); // lock the original node\n return true;\n }\n}", "solution_c": "class LockingTree {\npublic:\n \n unordered_map locks_aquired;\n vector> graph;\n unordered_map parents;\n \n LockingTree(vector& parent)\n { \n int n=parent.size();\n graph = vector >(n);\n parents[0] = -1 ; // since parent of node 0 is always -1 \n\n for(int i=1; ilock(num,user);\n * bool param_2 = obj->unlock(num,user);\n * bool param_3 = obj->upgrade(num,user);\n */" }, { "title": "Design Parking System", "algo_input": "Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.\n\nImplement the ParkingSystem class:\n\n\n\tParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.\n\tbool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.\n\n\n \nExample 1:\n\nInput\n[\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n[[1, 1, 0], [1], [2], [3], [1]]\nOutput\n[null, true, true, false, false]\n\nExplanation\nParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.\n\n\n \nConstraints:\n\n\n\t0 <= big, medium, small <= 1000\n\tcarType is 1, 2, or 3\n\tAt most 1000 calls will be made to addCar\n\n", "solution_py": "class ParkingSystem:\n def __init__(self, big: int, medium: int, small: int):\n self.vehicle =[big,medium,small]\n\n def addCar(self, carType: int) -> bool:\n if carType == 1 :\n if self.vehicle[0] > 0:\n self.vehicle[0]-=1\n return True\n elif carType == 2:\n if self.vehicle[1] > 0:\n self.vehicle[1]-=1\n return True\n elif carType == 3:\n if self.vehicle[2] > 0:\n self.vehicle[2]-=1\n return True\n return False", "solution_js": "var ParkingSystem = function(big, medium, small) {\n this.count = [big, medium, small];\n};\n\n/** \n * @param {number} carType\n * @return {boolean}\n */\nParkingSystem.prototype.addCar = function(carType) {\n return this.count[carType - 1]-- > 0;\n};\n\n/** \n * Your ParkingSystem object will be instantiated and called as such:\n * var obj = new ParkingSystem(big, medium, small)\n * var param_1 = obj.addCar(carType)\n */", "solution_java": "class ParkingSystem {\n private int[] size;\n public ParkingSystem(int big, int medium, int small) {\n this.size = new int[]{big, medium, small};\n }\n \n public boolean addCar(int carType) {\n return size[carType-1]-->0;\n }\n}", "solution_c": "class ParkingSystem {\npublic: vector vehicle;\npublic:\n ParkingSystem(int big, int medium, int small) {\n vehicle = {big, medium, small};\n }\n\n bool addCar(int carType) {\n return vehicle[carType - 1]-- > 0;\n }" }, { "title": "Number of Good Pairs", "algo_input": "Given an array of integers nums, return the number of good pairs.\n\nA pair (i, j) is called good if nums[i] == nums[j] and i < j.\n\n \nExample 1:\n\nInput: nums = [1,2,3,1,1,3]\nOutput: 4\nExplanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.\n\n\nExample 2:\n\nInput: nums = [1,1,1,1]\nOutput: 6\nExplanation: Each pair in the array are good.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i] <= 100\n\n", "solution_py": "from itertools import combinations\nclass Solution:\n def numIdenticalPairs(self, nums) -> int:\n res = 0\n\t\tnums_set = set(nums)\n nums_coppy = nums\n for number in nums_set:\n number_found = []\n deleted = 0\n while True:\n try:\n found = nums_coppy.index(number)\n nums_coppy.remove(number)\n if deleted > 0:\n number_found.append(found + deleted)\n else:\n number_found.append(found + deleted)\n deleted += 1\n except:\n comb = list(combinations(number_found, 2))\n res += len(comb)\n break\n return res", "solution_js": "var numIdenticalPairs = function(nums) {\n let counter = 0;\n let map = {};\n for(let num of nums) {\n if(map[num]) {\n counter += map[num];\n map[num]++;\n } else {\n map[num] = 1;\n }\n }\n return counter;\n};", "solution_java": "class Solution {\n public int numIdenticalPairs(int[] nums) {\n int len =nums.length;\n int counter=0;\n for (int i =0;i& nums) {\n\n int cnt = 0;\n for(int i=0 ; i Optional[ListNode]:\n group = 2\n tail = head # tail of previous group\n while tail and tail.next:\n cnt = 1 # actual size of the current group\n cur = tail.next # first node of the current group\n while cur.next and cnt < group:\n cur = cur.next\n cnt += 1\n pre, cur = tail, tail.next\n if cnt % 2 == 0: # if group size is even\n while cnt and cur:\n nxt = cur.next\n cur.next = pre\n pre = cur\n cur = nxt\n cnt -= 1\n first = tail.next # first node of the original group\n first.next = cur\n tail.next = pre\n tail = first\n else:\n while cnt and cur:\n pre, cur = cur, cur.next\n cnt -= 1\n tail = pre\n group += 1\n return head", "solution_js": "var reverseEvenLengthGroups = function(head) {\n let groupSize = 2;\n\n let start = head;\n\n let prev = head;\n let curr = head.next;\n\n let count = 0;\n \n while (curr != null) {\n if (count === groupSize) {\n if (groupSize % 2 === 0) { // we only reverse when it is even\n const end = curr;\n const tail = start.next; // the starting node of the reverse linked list will be the tail after the reverse takes place\n reverseList(start, end, count); // we need to reverse everything in the middle of start and end \n start = tail; // we set the new start to the end of the reversed linked list\n }\n else { // when groupSize is even we don't need to reverse, but need to set the new start to the prev node\n start = prev;\n }\n count = 0; // whenever we reached the group size we need to reset our count and up our groupSize\n ++groupSize;\n }\n else { // just a normal traversal when we haven't hit our groupSize\n prev = curr; \n curr = curr.next;\n ++count;\n }\n }\n \n if (count % 2 === 0) { // in the case where we ended early on even count\n reverseList(start, null, count);\n }\n \n return head;\n \n \n function reverseList(start, end, count) {\n if (start.next == null) return start; // for case when we have a single node\n \n let prev = start;\n \n let curr = start.next;\n let tail = start.next;\n \n for (let i = 0; i < count; ++i) {\n const next = curr.next;\n curr.next = prev;\n prev = curr;\n curr = next;\n }\n \n start.next = prev;\n tail.next = end;\n \n return ;\n }\n};", "solution_java": "// This Question can be solved easily using two standard methods of LinkedList\n// 1) addFirst (it adds node in front of the LinkedList)\n// 2) addLast (it adds node in end of the LinkedList)\n\nclass Solution {\n\n static ListNode oh;\n static ListNode ot;\n static ListNode th;\n static ListNode tt;\n\n public ListNode reverseEvenLengthGroups(ListNode head) {\n\n oh = null;\n ot = null;\n th = null;\n tt = null;\n\n if(head == null || head.next == null)\n return head;\n\n int size = length(head);\n int idx = 1;\n ListNode curr = head;\n int group = 1;\n\n while(curr!=null)\n {\n int temp = size - idx + 1;\n if((temp>=group && group%2 == 0) || (temp0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addFirst(curr);\n curr = t;\n idx++;\n }\n }\n else\n {\n int k = group;\n while(k-->0 && curr!=null)\n {\n ListNode t = curr.next;\n curr.next = null;\n addLast(curr);\n curr = t;\n idx++;\n }\n }\n\n if(oh==null && ot==null)\n {\n oh = th;\n ot = tt;\n }\n else\n {\n ot.next = th;\n ot = tt;\n }\n\n th = null;\n tt = null;\n group++;\n }\n\n return oh;\n }\n\n public int length (ListNode head)\n {\n if(head==null) return 0;\n ListNode curr = head;\n int k = 0;\n while(curr!=null)\n {\n k++;\n curr = curr.next;\n }\n return k;\n }\n\n public void addFirst(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n head.next = th;\n th = head;\n }\n }\n\n public void addLast(ListNode head)\n {\n if(tt == null && th == null)\n {\n th = head;\n tt = head;\n }\n else\n {\n tt.next = head;\n tt = head;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n\n // Function to reverse a linked list\n ListNode* reverseList(ListNode* head) {\n if(!head)\n return head;\n ListNode* prev = NULL;\n while(head) {\n ListNode* temp = head -> next;\n head -> next = prev;\n prev = head;\n head = temp;\n }\n\n return prev;\n }\n\n ListNode* reverseEvenLengthGroups(ListNode* head) {\n // Creating a dummy node to avoid adding checks for the first node\n ListNode* dummy = new ListNode();\n dummy -> next = head;\n\n ListNode* prev = dummy;\n\n // Loop to determine the lengths of groups\n for(int len = 1; len < 1e5 && head; len++) {\n ListNode* tail = head;\n ListNode* nextHead;\n\n // Determining the length of the current group\n // Its maximum length can be equal to len\n int j = 1;\n while(j < len && tail && tail -> next) {\n tail = tail -> next;\n j++;\n }\n\n // Head of the next group\n nextHead = tail -> next;\n\n if((j % 2) == 0) {\n // If even sized group is found\n // Reversing the group and setting prev and head appropriately\n tail -> next = NULL;\n prev -> next = reverseList(head);\n prev = head;\n head -> next = nextHead;\n head = nextHead;\n } else {\n // If group is odd sized, then simply going towards the next group\n prev = tail;\n head = nextHead;\n }\n }\n\n // Returning the head\n return dummy -> next;\n }\n};" }, { "title": "Find the Highest Altitude", "algo_input": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.\n\nYou are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point.\n\n \nExample 1:\n\nInput: gain = [-5,1,5,0,-7]\nOutput: 1\nExplanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\n\n\nExample 2:\n\nInput: gain = [-4,-3,-2,-1,4,3,2]\nOutput: 0\nExplanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n\n\n \nConstraints:\n\n\n\tn == gain.length\n\t1 <= n <= 100\n\t-100 <= gain[i] <= 100\n\n", "solution_py": "class Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n return max(accumulate([0]+gain))", "solution_js": "var largestAltitude = function(gain) {\n let points = [0]\n let highest = 0\n\n for (let i = 0; i < gain.length; i++) {\n let point = points[i] + gain[i]\n points.push(point)\n if (point > highest) highest = point\n }\n\n return highest\n};", "solution_java": "class Solution {\n public int largestAltitude(int[] gain) {\n int max_alt=0;\n int curr_alt=0;\n for(int i=0;i& gain) {\n int maxAltitude = 0;\n int currentAltitude = 0;\n \n for (int i = 0; i < gain.size(); i++) {\n currentAltitude += gain[i];\n maxAltitude = max(maxAltitude, currentAltitude);\n }\n \n return maxAltitude;\n }\n};" }, { "title": "Largest Plus Sign", "algo_input": "You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.\n\nReturn the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.\n\nAn axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.\n\n \nExample 1:\n\nInput: n = 5, mines = [[4,2]]\nOutput: 2\nExplanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\n\n\nExample 2:\n\nInput: n = 1, mines = [[0,0]]\nOutput: 0\nExplanation: There is no plus sign, so return 0.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 500\n\t1 <= mines.length <= 5000\n\t0 <= xi, yi < n\n\tAll the pairs (xi, yi) are unique.\n\n", "solution_py": "class Solution:\n\n def orderOfLargestPlusSign(self, n: int, mines: list[list[int]]) -> int:\n matrix = [1] * n\n aux = {}\n hasOne = False\n for i in range(0,n):\n matrix[i] = [1] * n\n for mine in mines:\n matrix[mine[0]][mine[1]] = 0\n for i in range(0,n):\n for j in range(0,n):\n if(matrix[i][j] == 1):\n hasOne = True\n if((i,j) not in aux):\n aux[(i,j)] = {\"t\":0,\"l\":0,\"r\":0,\"b\":0}\n if(j>0 and matrix[i][j] == 1 and matrix[i][j-1] == 1):\n aux[(i,j)][\"l\"] = aux[(i,j-1)][\"l\"] + 1 \n if(i>0 and matrix[i][j] == 1 and matrix[i-1][j] == 1):\n aux[(i,j)][\"t\"] = aux[(i-1,j)][\"t\"] + 1\n \n maxOrder = 0 \n for i in range(n-1,-1,-1):\n if(i new Array(n).fill(n));\n\n // insert `0` to the grid in table according the position in mines\n mines.forEach(a => t[a[0]][a[1]] = 0);\n\n // loop each rows and cols\n // - for rows: calculate non-zero grid from left to right\n // - for cols: calculate non-zero grid from top to bottom\n // - when the loop is completed, all of non-zero values will be calculated by four directions\n // - and these grids value will be updated by comparing. then we can obtain the minimum value of the four directions caculation, which is the maximum of the grid\n for (let i = 0; i < n; i++) {\n // save the maximum value of non-zeros with for directions\n let [l, r, u, d] = [0, 0, 0, 0];\n\n // l: left, loop row i from left to right\n // r: right, loop row i from right to left\n // u: up, loop col i from top to bottom\n // d: down, loop col i from bottom to top\n for (let j = 0, k = n - 1; j < n; j++, k--) {\n // if the value is `0`, then set variable to `0`, and indicates it's broken\n l = t[i][j] && l + 1;\n r = t[i][k] && r + 1;\n u = t[j][i] && u + 1;\n d = t[k][i] && d + 1;\n\n // if current value is less than origin value\n // one possibility: the origin value is default\n // another possibility: the length of non-zero in a centain direction is langer than in the current direction, which the minimum value we need\n if (l < t[i][j]) t[i][j] = l;\n if (r < t[i][k]) t[i][k] = r;\n if (u < t[j][i]) t[j][i] = u;\n if (d < t[k][i]) t[k][i] = d;\n }\n }\n\n // return maximum value be saved by all cells\n return Math.max(...t.map(v => Math.max(...v)));\n}", "solution_java": "class Solution {\n public int orderOfLargestPlusSign(int n, int[][] mines) {\n // Create the matrix\n int[][] arr = new int[n][n];\n for(int[] subArray : arr) {\n Arrays.fill(subArray, 1);\n }\n\n for(int i = 0; i < mines.length; i++) {\n arr[mines[i][0]][mines[i][1]] = 0;\n }\n\n // Prefix Count DP arrays\n int[][] dpTop = new int[arr.length][arr.length];\n int[][] dpLeft = new int[arr.length][arr.length];\n int[][] dpRight = new int[arr.length][arr.length];\n int[][] dpBottom = new int[arr.length][arr.length];\n\n // Prefix count of 1 cells on top and left directions\n for(int i = 0; i < arr.length; i++) {\n for(int j = 0; j < arr.length; j++) {\n if(i - 1 >= 0 && arr[i - 1][j] == 1) {\n dpTop[i][j] = 1 + dpTop[i - 1][j];\n }\n\n if(j - 1 >= 0 && arr[i][j - 1] == 1) {\n dpLeft[i][j] = 1 + dpLeft[i][j - 1];\n }\n }\n }\n\n // Prefix count of 1 cells on bottom and right directions\n for(int i = arr.length - 1; i >= 0; i--) {\n for(int j = arr.length - 1; j >= 0; j--) {\n if(i + 1 < arr.length && arr[i + 1][j] == 1) {\n dpBottom[i][j] = 1 + dpBottom[i + 1][j];\n }\n\n if(j + 1 < arr.length && arr[i][j + 1] == 1) {\n dpRight[i][j] = 1 + dpRight[i][j + 1];\n }\n }\n }\n\n int maxPlusSignLength = 0;\n for(int i = 0; i < arr.length; i++) {\n for(int j = 0; j < arr.length; j++) {\n if(arr[i][j] == 0) continue;\n\n // Minimum adjacent 1 cell count from all four directions to ensure symmetry\n int minAdjacentOnes = Math.min(Math.min(dpTop[i][j], dpBottom[i][j]), Math.min(dpLeft[i][j], dpRight[i][j]));\n maxPlusSignLength = Math.max(maxPlusSignLength, minAdjacentOnes + 1);\n }\n }\n\n return maxPlusSignLength;\n }\n}", "solution_c": "class Solution {\npublic:\n int orderOfLargestPlusSign(int n, vector>& mines) {\n //jai shri ram\n int ans=0;\n vectorblock(25*int(1e4)+1,0);\n vector>dp(n,vector(n,0));\n for(auto x:mines){\n int a=x[0],b=x[1];\n block[a*n+b]=true;\n }\n for(int i=0;i=0;j--){\n int sum=0;\n for(int i=n-1;i>=0;i--){\n if(block[i*n+j]){\n sum=0;\n }else sum+=1;\n dp[i][j]=min(dp[i][j],sum);\n }\n }\n for(int i=n-1;i>=0;i--){\n int sum=0;\n for(int j=n-1;j>=0;j--){\n if(block[i*n+j]){\n sum=0;\n }else sum+=1;\n dp[i][j]=min(dp[i][j],sum);\n ans=max(ans,dp[i][j]);\n }\n }\n return ans;\n }\n};" }, { "title": "Find Target Indices After Sorting Array", "algo_input": "You are given a 0-indexed integer array nums and a target element target.\n\nA target index is an index i such that nums[i] == target.\n\nReturn a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.\n\n \nExample 1:\n\nInput: nums = [1,2,5,2,3], target = 2\nOutput: [1,2]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.\n\n\nExample 2:\n\nInput: nums = [1,2,5,2,3], target = 3\nOutput: [3]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.\n\n\nExample 3:\n\nInput: nums = [1,2,5,2,3], target = 5\nOutput: [4]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i], target <= 100\n\n", "solution_py": "class Solution:\n def targetIndices(self, nums, target):\n ans = []\n for i,num in enumerate(sorted(nums)):\n if num == target: ans.append(i)\n return ans", "solution_js": "function binarySearch(lists, sorted, low, high, target){\n if(low > high) return;\n\n const mid = low + Math.floor((high - low) / 2);\n\n if(sorted[mid] === target){\n lists.push(mid);\n }\n\n binarySearch(lists, sorted, low, mid-1, target);\n binarySearch(lists, sorted, mid+1, high, target);\n}\n\nvar targetIndices = function(nums, target) {\n let result = [];\n nums.sort((a,b)=>a-b);\n if(!nums.includes(target)) return [];\n\n binarySearch(result, nums, 0 , nums.length-1, target);\n return result.sort((a,b) => a-b);\n}", "solution_java": "class Solution {\n /** Algorithm:\n - Parse the array once and count how many are lesser than target and how many are equal\n - DO NOT sort the array as we don't need it sorted.\n Just to know how many are lesser and how many are equal. O(N) better than O(NlogN - sorting)\n - The response list will have a size = with the number of equal elements (as their positions)\n - Loop from smaller to smaller+equal and add the values into the list. Return the list\n */\n public List targetIndices(int[] nums, int target) {\n int smaller = 0;\n int equal = 0;\n for (int num : nums) {\n if (num < target) {\n smaller++;\n } else if (num == target) {\n equal++;\n }\n }\n List indices = new ArrayList<>(equal);\n for (int i = smaller; i < smaller + equal; i++) {\n indices.add(i);\n }\n return indices;\n }\n}", "solution_c": "class Solution {\npublic:\n vector targetIndices(vector& nums, int target) {\n vector result;\n sort(nums.begin(),nums.end());\n for(int i=0;i int:\n if self.heap:\n return heapq.heappop(self.heap)\n self.index += 1\n return self.index-1\n\n def addBack(self, num: int) -> None:\n if self.index > num and num not in self.heap:\n heapq.heappush(self.heap,num)", "solution_js": "var SmallestInfiniteSet = function() {\n const s = new Set();\n this.s = s;\n for(let i = 1; i <= 1000; i++) s.add(i);\n};\n\n/**\n * @return {number}\n */\nSmallestInfiniteSet.prototype.popSmallest = function() {\n const min = Math.min(...Array.from(this.s));\n this.s.delete(min);\n return min;\n};\n\n/**\n * @param {number} num\n * @return {void}\n */\nSmallestInfiniteSet.prototype.addBack = function(num) {\n this.s.add(num);\n};\n\n/**\n * Your SmallestInfiniteSet object will be instantiated and called as such:\n * var obj = new SmallestInfiniteSet()\n * var param_1 = obj.popSmallest()\n * obj.addBack(num)\n */", "solution_java": "class SmallestInfiniteSet {\n private PriorityQueue q;\n private int index;\n public SmallestInfiniteSet() {\n q = new PriorityQueue();\n index = 1;\n }\n \n public int popSmallest() {\n if (q.size()>0){\n return q.poll();\n }\n return index++;\n }\n \n private boolean is_in_q(int num){\n for(int i : q){\n if (i == num){\n return true;\n }\n }\n return false;\n }\n \n public void addBack(int num) {\n if( num < index && !is_in_q(num)){\n q.add(num);\n }\n }\n}", "solution_c": "class SmallestInfiniteSet {\npublic:\n int cur;\n set s;\n SmallestInfiniteSet() {\n cur=1;\n }\n\n int popSmallest() {\n if(s.size()){\n int res=*s.begin(); s.erase(res);\n return res;\n }else{\n cur+=1;\n return cur-1;\n }\n }\n\n void addBack(int num) {\n if(cur>num) s.insert(num);\n }\n};" }, { "title": "Transform to Chessboard", "algo_input": "You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.\n\nReturn the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.\n\nA chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.\n\n \nExample 1:\n\nInput: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput: 2\nExplanation: One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.\n\n\nExample 2:\n\nInput: board = [[0,1],[1,0]]\nOutput: 0\nExplanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\n\n\nExample 3:\n\nInput: board = [[1,0],[1,0]]\nOutput: -1\nExplanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n\n\n \nConstraints:\n\n\n\tn == board.length\n\tn == board[i].length\n\t2 <= n <= 30\n\tboard[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution(object):\n def movesToChessboard(self, board):\n N = len(board)\n ans = 0\n # For each count of lines from {rows, columns}...\n for count in (collections.Counter(map(tuple, board)), # get row\n collections.Counter(zip(*board))): #get column\n\n # If there are more than 2 kinds of lines,\n # or if the number of kinds is not appropriate ...\n if len(count) != 2 or sorted(count.values()) != [N/2, (N+1)/2]:\n return -1\n\n # If the lines are not opposite each other, impossible\n line1, line2 = count\n if not all(x ^ y for x, y in zip(line1, line2)):\n return -1\n\n # starts = what could be the starting value of line1\n # If N is odd, then we have to start with the more\n # frequent element\n starts = [int(line1.count(1) * 2 > N)] if N%2 else [0, 1]\n\n # To transform line1 into the ideal line [i%2 for i ...],\n # we take the number of differences and divide by two\n ans += min(sum((x-i) % 2 for i, x in enumerate(line1, start))\n for start in starts) / 2 \n\n return ans", "solution_js": "/**\n * @param {number[][]} board\n * @return {number}\n */\nvar movesToChessboard = function(board) {\n const boardSize = board.length;\n const boardSizeIsEven = boardSize % 2 === 0;\n\n if(!canBeTransformed(board)) return -1;\n\n // to convert to 010101\n let rowSwap = 0;\n let colSwap = 0;\n\n // to convert to 101010\n let rowSwap2 = 0;\n let colSwap2 = 0;\n\n for(let i=0; i a+b);\n if(boardSizeIsEven && sum != boardSize/2) return false;\n if(!boardSizeIsEven && sum > ((boardSize + 1)/2)) return false;\n\n let first = board[0].join('');\n let opposite = board[0].map((item) => item === 1 ? 0 : 1).join('');\n // each row should be equal to first or opposite\n let counter = [0,0];\n for(let i=0; i (N + 1) / 2) {\n return -1;\n }\n if (colOneCnt < N / 2 || colOneCnt > (N + 1) / 2) {\n return -1;\n }\n if (N % 2 == 1) {\n // we cannot make it when ..ToMove is odd\n if (colToMove % 2 == 1) {\n colToMove = N - colToMove;\n }\n if (rowToMove % 2 == 1) {\n rowToMove = N - rowToMove;\n }\n } else {\n colToMove = Math.min(colToMove, N - colToMove);\n rowToMove = Math.min(rowToMove, N - rowToMove);\n }\n return (colToMove + rowToMove) / 2;\n }\n\n}", "solution_c": "class Solution {\n const int inf = 1e9;\n void transpose(vector>& board) {\n const int n = board.size();\n for (int i = 0; i < n; i++)\n for (int j = 0; j < i; j++)\n swap(board[i][j], board[j][i]);\n }\n \n bool isSame(vector &r1, vector& r2) {\n const int n = r1.size();\n for (int i = 0; i < n; i++)\n if (r1[i] != r2[i])\n return false;\n return true;\n }\n \n bool isOpposite(vector &r1, vector& r2) {\n const int n = r1.size();\n for (int i = 0; i < n; i++)\n if (r1[i] == r2[i])\n return false;\n return true;\n }\n \n int getSteps(vector> &&confusionMatrix) {\n int steps = inf;\n \n if (confusionMatrix[0][1] == confusionMatrix[1][0])\n steps = confusionMatrix[0][1];\n \n if (confusionMatrix[0][0] == confusionMatrix[1][1])\n steps = min(steps, confusionMatrix[0][0]);\n \n return steps;\n }\n \n vector> getConfusionMatrix(vector& rowType) {\n const int n = rowType.size();\n vector> confusionMatrix(2, vector(2, 0));\n for (int i = 0; i < n; i++)\n confusionMatrix[rowType[i]][i & 1]++;\n return confusionMatrix;\n }\n \n int solve1d(vector &arr) {\n return getSteps(getConfusionMatrix(arr));\n }\n \n int makeColumnsAlternating(vector>& board) {\n const int n = board.size();\n vector rowType(n, 0);\n for (int i = 1; i < n; i++)\n if (isOpposite(board[0], board[i]))\n rowType[i] = 1;\n else if (!isSame(board[0], board[i]))\n return inf;\n return solve1d(rowType);\n }\npublic:\n int movesToChessboard(vector>& board) {\n int steps = makeColumnsAlternating(board);\n transpose(board);\n steps += makeColumnsAlternating(board);\n if (steps >= inf)\n return -1;\n return steps;\n }\n};" }, { "title": "Tree of Coprimes", "algo_input": "There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.\n\nTo represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.\n\nTwo values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.\n\nAn ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.\n\nReturn an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n\n \nExample 1:\n\n\n\nInput: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput: [-1,0,0,1]\nExplanation: In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.\n\n\nExample 2:\n\n\n\nInput: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput: [-1,0,-1,0,0,0,-1]\n\n\n \nConstraints:\n\n\n\tnums.length == n\n\t1 <= nums[i] <= 50\n\t1 <= n <= 105\n\tedges.length == n - 1\n\tedges[j].length == 2\n\t0 <= uj, vj < n\n\tuj != vj\n\n", "solution_py": "class Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n \n gcdset = [set() for i in range(51)]\n for i in range(1,51):\n for j in range(1,51):\n if math.gcd(i,j) == 1:\n gcdset[i].add(j)\n gcdset[j].add(i)\n \n graph = defaultdict(list)\n for v1, v2 in edges:\n graph[v1].append(v2)\n graph[v2].append(v1)\n \n ans = [-1]*len(nums)\n q = [[0, {}]]\n seen = set([0])\n depth = 0\n while q:\n temp = []\n for node, ancestors in q:\n index_depth = (-1,-1)\n for anc in list(ancestors.keys()):\n if anc in gcdset[nums[node]]:\n index, d = ancestors[anc]\n if d > index_depth[1]:\n index_depth = (index,d)\n ans[node] = index_depth[0]\n \n copy = ancestors.copy()\n copy[nums[node]] = (node,depth)\n \n for child in graph[node]:\n if child not in seen:\n seen.add(child)\n temp.append([child, copy])\n q = temp\n depth += 1\n return ans", "solution_js": "var getCoprimes = function(nums, edges) {\n \n const node = {}\n const ans = Array(nums.length).fill(null)\n \n function addNode(f, t){\n if(!node[f]){\n node[f]=[]\n }\n node[f].push(t)\n }\n \n edges.forEach(([f, t])=>{\n addNode(f, t)\n addNode(t, f)\n })\n \n function gcd(a, b){\n while(b) [a, b] = [b, a % b];\n return a;\n }\n \n const map = []\n for(let i=0; i<51; i++){\n map[i]=[]\n for(let j=0; j<51; j++){\n map[i][j]= gcd(i,j)\n }\n }\n\n let pi=-1\n let path=Array(nums.length)\n function check(v){\n if(ans[v]!==null) return\n ans[v] = -1\n let a = nums[v]\n for(let k=pi; k>=0; k--){\n let b = nums[path[k]]\n if(map[a][b]===1){\n ans[v]=path[k]\n break\n }\n }\n if(node[v]) {\n path[++pi]=v\n node[v].forEach(child=>check(child))\n pi--\n }\n }\n \n for(let i=0; i child;\n public TreeNode(int id,int val){\n this.id=id;this.val=val;child=new ArrayList<>();\n }\n }\n public int[] getCoprimes(int[] nums, int[][] edges) {\n // making tree/graph with edges\n TreeNode[] tr=new TreeNode[nums.length];\n for(int i=0;i adj[100009];\n vector d[55];\n int dis[100009];\n void dfs(vector& nums,vector &ans,int i,int p,int h1)\n {\n int h=nums[i];\n dis[i]=h1;\n ans[i]=-1;\n int val=-1;\n for(int w=1;w<=50;w++)\n {\n if(__gcd(h,w)==1)\n {\n if(d[w].size())\n {\n int u=d[w].back();\n if(dis[u]>val)\n {\n val=dis[u];\n ans[i]=u;\n }\n }\n }\n }\n d[h].push_back(i);\n for(auto x:adj[i])\n {\n if(x==p) continue;\n dfs(nums,ans,x,i,h1+1);\n }\n d[h].pop_back();\n }\n vector getCoprimes(vector& nums, vector>& edges) {\n int n=nums.size();\n for(int i=0;i ans(n);\n dfs(nums,ans,0,-1,0);\n return ans;\n }\n};" }, { "title": "Minimized Maximum of Products Distributed to Any Store", "algo_input": "You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.\n\nYou need to distribute all products to the retail stores following these rules:\n\n\n\tA store can only be given at most one product type but can be given any amount of it.\n\tAfter distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.\n\n\nReturn the minimum possible x.\n\n \nExample 1:\n\nInput: n = 6, quantities = [11,6]\nOutput: 3\nExplanation: One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.\n\n\nExample 2:\n\nInput: n = 7, quantities = [15,10,10]\nOutput: 5\nExplanation: One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.\n\n\nExample 3:\n\nInput: n = 1, quantities = [100000]\nOutput: 100000\nExplanation: The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.\n\n\n \nConstraints:\n\n\n\tm == quantities.length\n\t1 <= m <= n <= 105\n\t1 <= quantities[i] <= 105\n\n", "solution_py": "class Solution:\n def minimizedMaximum(self, n: int, quantities: List[int]) -> int:\n def cond(m, n):\n return sum([(q // m) + (q % m > 0) for q in quantities]) <= n\n \n l, r = 1, max(quantities)\n while l < r:\n m = (l + r) // 2\n if cond(m, n):\n r = m\n else:\n l = m + 1\n return l", "solution_js": "var minimizedMaximum = function(n, quantities) {\n const MAX = Number.MAX_SAFE_INTEGER;\n const m = quantities.length;\n\n let left = 1;\n let right = quantities.reduce((acc, num) => acc + num, 0);\n\n let minRes = MAX;\n\n while (left <= right) {\n const mid = (left + right) >> 1;\n\n if (canDistribute(mid)) {\n minRes = Math.min(minRes, mid);\n right = mid - 1;\n }\n else {\n left = mid + 1;\n }\n }\n\n return minRes;\n\n function canDistribute(minGiven) {\n const clonedQ = [...quantities];\n\n let j = 0;\n let i = 0;\n\n for (; i < n && j < m; ++i) {\n const remQ = clonedQ[j];\n\n if (remQ > minGiven) {\n clonedQ[j] -= minGiven;\n }\n else {\n ++j;\n }\n }\n\n return j === m;\n }\n};", "solution_java": "class Solution {\n public int minimizedMaximum(int n, int[] quantities) {\n \n int lo = 1;\n int hi = (int)1e5;\n \n int ans = -1;\n \n while(lo <= hi){\n \n int mid = (lo + hi)/2;\n \n if(isItPossible(mid, quantities, n)){\n ans = mid;\n hi = mid-1;\n }else{\n lo = mid+1;\n }\n }\n \n return ans;\n }\n \n private boolean isItPossible(int x, int[] quantities, int n){\n \n // isItPossible to distribute <= x products to each of the n shops\n for(int i=0; i& quantities){\n int temp = 0;\n for(int id = 0; temp <= n && id != quantities.size(); id++)\n temp += quantities[id] / N + (quantities[id] % N ? 1 : 0);\n \n return temp <= n;\n }\n \n int minimizedMaximum(int n, vector& quantities) {\n int l = 1, r = *max_element(quantities.begin(), quantities.end());\n \n for(int m = (l + r)>>1; l <= r; m = (l + r)>>1) \n func(m, n , quantities) ? r = m - 1 : l = m + 1; \n \n return l;\n }\n};" }, { "title": "Linked List Random Node", "algo_input": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.\n\nImplement the Solution class:\n\n\n\tSolution(ListNode head) Initializes the object with the head of the singly-linked list head.\n\tint getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.\n\n\n \nExample 1:\n\nInput\n[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 3, 2, 2, 3]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the linked list will be in the range [1, 104].\n\t-104 <= Node.val <= 104\n\tAt most 104 calls will be made to getRandom.\n\n\n \nFollow up:\n\n\n\tWhat if the linked list is extremely large and its length is unknown to you?\n\tCould you solve this efficiently without using extra space?\n\n", "solution_py": "class Solution:\n\n def __init__(self, head: Optional[ListNode]):\n self.lst = []\n while head:\n self.lst.append(head.val)\n head = head.next\n\n def getRandom(self) -> int:\n return random.choice(self.lst)", "solution_js": "var Solution = function(head) {\n this.res = [];\n let curr = head;\n\n while(curr !== null) {\n this.res.push(curr)\n curr = curr.next;\n }\n this.length = this.res.length;\n};\n\nSolution.prototype.getRandom = function() {\n //Math.random() will generate a random number b/w 0 & 1.\n //then multiply it with the array size, as i have all the value in the list, i know the size of the list\n //take only the integer part which is a random index.\n //return the element at that random index.\n return this.res[Math.floor(Math.random() * this.length)].val\n};", "solution_java": "class Solution {\n int N = 0;\n ListNode head = null;\n public Solution(ListNode head) {\n this.head = head;\n }\n \n public int getRandom() {\n ListNode p = this.head;\n int i = 1, ans = 0;\n while (p != null) {\n if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i\n p = p.next;\n i ++;\n }\n return ans;\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vectorv;\n Solution(ListNode* head) {\n while(head!=NULL) {\n v.push_back(head->val);\n head=head->next;\n }\n\n }\n\n int getRandom() {\n return v[rand()%v.size()];\n }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution* obj = new Solution(head);\n * int param_1 = obj->getRandom();\n */" }, { "title": "Maximum Score Words Formed by Letters", "algo_input": "Given a list of words, list of  single letters (might be repeating) and score of every character.\n\nReturn the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).\n\nIt is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.\n\n \nExample 1:\n\nInput: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput: 23\nExplanation:\nScore a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.\n\nExample 2:\n\nInput: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput: 27\nExplanation:\nScore a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.\n\nExample 3:\n\nInput: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput: 0\nExplanation:\nLetter \"e\" can only be used once.\n\n \nConstraints:\n\n\n\t1 <= words.length <= 14\n\t1 <= words[i].length <= 15\n\t1 <= letters.length <= 100\n\tletters[i].length == 1\n\tscore.length == 26\n\t0 <= score[i] <= 10\n\twords[i], letters[i] contains only lower case English letters.\n\n", "solution_py": "from itertools import combinations \n\nclass Solution:\n def createNewWord(self, wordList) : \n ans = ''\n for word in wordList :\n ans += word \n \n charList = [i for i in ans]\n return charList \n \n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n score_dict = {}\n ord_a = 97 \n for i in range(len(score)) : \n score_dict[chr(ord_a + i)] = score[i]\n \n max_count, sum_list, to_remove = 0, [], []\n for word in words : \n char_list = [i for i in word]\n max_num = 0\n for char in set(char_list) : \n if char_list.count(char) > letters.count(char) : \n max_num = 0\n to_remove.append(word)\n break \n else : \n max_num += score_dict[char]*char_list.count(char)\n\n if max_num > 0 :\n sum_list.append(max_num)\n \n if max_num > max_count : \n max_count = max_num \n \n new_word = [i for i in words if i not in to_remove]\n # print(new_word)\n for i in range(2, len(sum_list)+1) :\n comb = combinations(new_word, i)\n for c in comb : \n combinedWord = self.createNewWord(c)\n totalNum = 0\n for char in set(combinedWord) : \n if combinedWord.count(char) > letters.count(char) : \n totalNum = 0\n break \n else : \n totalNum += score_dict[char]*combinedWord.count(char)\n if totalNum > max_count : \n max_count = totalNum \n \n return max_count ", "solution_js": "var maxScoreWords = function(words, letters, score) {\n // unique chars\n let set = new Set();\n for (let w of words)\n for (let c of w)\n set.add(c)\n\n // score of unique chars\n let map = new Map();\n for (let c of set)\n map.set(c, score[c.charCodeAt() - 'a'.charCodeAt()])\n\n // letter count\n let map_letters = new Map();\n for (let c of letters)\n map_letters.set(c, map_letters.has(c) ? map_letters.get(c) + 1 : 1);\n\n // score of words\n let SW = [];\n for (let w of words) {\n let s = 0;\n for (let c of w)\n s += map.get(c)\n SW.push(s)\n }\n\n const sortStr = (s) => s.split(\"\").sort().join(\"\")\n const combineStrings_fromArrayAndIndexes = (A, I) => I.reduce((s, i) => (s + A[i]), '')\n const getFreqMapFromStr = (s) => s.split(\"\").reduce((m, c) => (m.set(c, m.has(c) ? m.get(c) + 1 : 1), m), new Map())\n const isMapSubOfAnotherMap = (m1, m2) => {\n for (let [c, count] of m1)\n if (!m2.has(c) || count > m2.get(c))\n return false\n return true\n }\n\n let max1 = -Infinity;\n const takeOrNot = (i, take, indexes, A, n) => {\n if (i === n) {\n if (isMapSubOfAnotherMap(\n getFreqMapFromStr(\n combineStrings_fromArrayAndIndexes(words, indexes)\n ),\n map_letters\n )) {\n let mm = indexes.reduce((sum, i) => sum + SW[i], 0)\n max1 = Math.max(max1, mm);\n }\n return\n }\n takeOrNot(i + 1, take, indexes, A, n)\n takeOrNot(i + 1, take, [...indexes, i], A, n);\n }\n takeOrNot(0, true, [], SW, SW.length);\n return max1;\n};", "solution_java": "class Solution {\n int[] memo;\n public int maxScoreWords(String[] words, char[] letters, int[] score) {\n memo = new int[words.length];\n Arrays.fill(memo,-1);\n HashMap hm = new HashMap<>();\n for(char c : letters){\n int t = hm.getOrDefault(c,0);\n t++;\n hm.put(c,t);\n }\n //return dp(words,hm,score,0,0);\n int res = dp(words,hm,score,0,0);\n //for(int i : memo) System.out.println(i);\n return res;\n }\n\n public int dp(String[] words, Map hm, int[] score, int index, int cs){//cs-current Score\n if(index==words.length) return cs;\n if(memo[index]!=-1) return memo[index];\n HashMap temp = new HashMap<>(hm);\n int tcs=cs; //tcs = temporory current score\n\n for(char c : words[index].toCharArray()){\n int t = temp.getOrDefault(c,0);\n t--;\n if(t<0){\n return dp(words,hm,score,index+1,cs);\n // memo[index] = dp(words,hm,score,index+1,cs);\n // return memo[index];\n }\n tcs+=score[c-'a'];\n temp.put(c,t);\n }\n return Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // memo[index] = Math.max(dp(words,hm,score,index+1,cs),dp(words,temp,score,index+1,tcs));\n // return memo[index];\n }\n}", "solution_c": "class Solution {\npublic:\n int calc(vector& words,map&m,vector& score,int i){ \n int maxi=0;\n if(i==words.size())\n return 0;\n mapm1=m;//Creating a duplicate in case the given word does not satisfy our answer\n int c=0;//Store the score\n for(int j=0;j& words, vector& letters, vector& score) {\n mapm; \n for(auto i:letters)\n m[i]++;\n return calc(words,m,score,0); \n }\n};" }, { "title": "Can Make Palindrome from Substring", "algo_input": "You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.\n\nIf the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.\n\nReturn a boolean array answer where answer[i] is the result of the ith query queries[i].\n\nNote that each letter is counted individually for replacement, so if, for example s[lefti...righti] = \"aaa\", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.\n\n \nExample :\n\nInput: s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput: [true,false,false,true,true]\nExplanation:\nqueries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.\n\n\nExample 2:\n\nInput: s = \"lyb\", queries = [[0,1,0],[2,2,1]]\nOutput: [false,true]\n\n\n \nConstraints:\n\n\n\t1 <= s.length, queries.length <= 105\n\t0 <= lefti <= righti < s.length\n\t0 <= ki <= s.length\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n hash_map = {s[0]: 1}\n x = hash_map\n prefix = [hash_map]\n for i in range(1, len(s)):\n x = x.copy()\n x[s[i]] = x.get(s[i], 0) + 1\n prefix.append(x)\n \n result = []\n for query in queries:\n cnt = 0\n for key, value in prefix[query[1]].items():\n if query[0] > 0:\n x = value - prefix[query[0]-1].get(key, 0)\n else:\n x = value\n if x % 2:\n cnt+=1\n if cnt - 2 * query[2] > 1:\n result.append(False)\n else:\n result.append(True)\n return result", "solution_js": "const getBitCount = (n) => {\n let cnt = 0;\n while(n > 0) {\n cnt += n & 1;\n n >>= 1;\n }\n return cnt;\n}\n\nvar canMakePaliQueries = function(s, queries) {\n const masks = [0], base = 'a'.charCodeAt(0);\n let mask = 0;\n for(let c of s) {\n mask ^= (1 << (c.charCodeAt(0) - base));\n masks.push(mask);\n }\n return queries.map(([l, r, k]) => {\n const cnt = getBitCount(masks[l] ^ masks[r+1]);\n return cnt - 1 <= 2 * k\n });\n};", "solution_java": "class Solution \n{\n public List canMakePaliQueries(String s, int[][] queries) \n {\n List list = new ArrayList<>();\n \n int n = s.length();\n int[][] map = new int[n+1][26];\n \n for(int i=0;i canMakePaliQueries(string s, vector>& queries) {\n vector>table(s.size(), vector(26,0));\n vectorans;\n\n table[0][s[0]-'a']++;\n for(int i = 1; i != s.size(); i++){\n for(int j = 0; j != 26; j++) table[i][j] = table[i-1][j];\n table[i][s[i]-'a']++;\n }\n\n for(auto &q: queries){\n int odd = 2 + (q[2]<<1);\n for(int i = 0; i != 26; i++){\n int val = table[q[1]][i] - (q[0] ? table[q[0]-1][i] : 0);\n if( (val & 1) && --odd == 0){ans.push_back(false); goto mark;}\n }\n\n ans.push_back(true);\n mark:;\n }\n\n return ans;\n }\n};" }, { "title": "Longest Chunked Palindrome Decomposition", "algo_input": "You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:\n\n\n\tsubtexti is a non-empty string.\n\tThe concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).\n\tsubtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).\n\n\nReturn the largest possible value of k.\n\n \nExample 1:\n\nInput: text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput: 7\nExplanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n\n\nExample 2:\n\nInput: text = \"merchant\"\nOutput: 1\nExplanation: We can split the string on \"(merchant)\".\n\n\nExample 3:\n\nInput: text = \"antaprezatepzapreanta\"\nOutput: 11\nExplanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 1000\n\ttext consists only of lowercase English characters.\n\n", "solution_py": "class Solution:\n def longestDecomposition(self, text: str) -> int:\n left, right = 0, len(text) - 1\n sol, last_left = 0, 0\n a, b = deque(), deque()\n while right > left:\n a.append(text[left])\n b.appendleft(text[right])\n if a == b:\n sol += 2\n last_left = left\n a, b = deque(), deque()\n right -= 1\n left += 1\n if left == right or left > last_left + 1:\n sol += 1\n return max(sol, 1)", "solution_js": "var longestDecomposition = function(text) {\n var i = 1\n var output = 0\n while(i < text.length)\n {\n if(text.substring(0,i) == text.substring(text.length-i))\n {\n output += 2 //add 2 to simulate adding to both sides of output array\n text = text.substring(i,text.length-i) //cut text to simulate popping off of both sides\n i=1\n } else {\n i++\n }\n }\n \n return text ? output + 1 : output //if there's any text leftover that didn't have a match, it's the middle and would add 1 to output array\n}", "solution_java": "class Solution {\n\n public int longestDecomposition(String text) {\n int n = text.length(); \n for (int i = 0; i < n/2; i++) \n if (text.substring(0, i + 1).equals(text.substring(n-1-i, n))) \n return 2+longestDecomposition(text.substring(i+1, n-1-i));\n return (n==0)?0:1;\n}\n}", "solution_c": "class Solution {\npublic:\n int longestDecomposition(string text) {\n if(text.size() == 0)\n return 0;\n int i = 0;\n deque sFront;\n deque sBack;\n while(i < text.size() / 2){\n sFront.push_back(text[i]);\n sBack.push_front(text[text.size() - 1 - i]);\n if(sFront == sBack)\n return 2 + longestDecomposition(text.substr(i + 1, text.size() - 2*(i+1)));\n i++;\n }\n return 1;\n }\n};" }, { "title": "Sum Root to Leaf Numbers", "algo_input": "You are given the root of a binary tree containing digits from 0 to 9 only.\n\nEach root-to-leaf path in the tree represents a number.\n\n\n\tFor example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.\n\n\nReturn the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.\n\nA leaf node is a node with no children.\n\n \nExample 1:\n\nInput: root = [1,2,3]\nOutput: 25\nExplanation:\nThe root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25.\n\n\nExample 2:\n\nInput: root = [4,9,0,5,1]\nOutput: 1026\nExplanation:\nThe root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 <= Node.val <= 9\n\tThe depth of the tree will not exceed 10.\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 sumNumbers(self, root: Optional[TreeNode]) -> int:\n \n int_list = []\n \n def traverse(node, input_string):\n \n nonlocal int_list\n \n if not node:\n return int_list\n \n input_string = input_string + str(node.val)\n\n if not (node.left or node.right):\n int_list.append(int(input_string))\n \n traverse(node.left, input_string)\n traverse(node.right, input_string)\n \n traverse(root, \"\")\n return sum(int_list)\n ", "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 sumNumbers = function(root) {\n return dfs(root)\n};\n\nconst dfs = (root, path = '') => {\n if (!root.left && !root.right) return +(path + root.val)\n \n const left = root.left ? dfs(root.left, path + root.val) : 0\n const right = root.right ? dfs(root.right, path + root.val) : 0\n \n return left + right\n}", "solution_java": "class Solution {\n int res;\n public int sumNumbers(TreeNode root) {\n res = 0;\n getSum(root, 0);\n \n return res;\n }\n \n public void getSum(TreeNode root, int sum){\n \n if(root.left == null && root.right == null) {\n res += (sum*10+root.val);\n }\n \n if(root.left != null)\n getSum(root.left, sum*10+root.val);\n \n \n if(root.right != null)\n getSum(root.right, sum*10+root.val);\n }\n}", "solution_c": "class Solution {\npublic:\n int ans=0;\n void dfs(TreeNode* root, string s){\n if(!root->left && !root->right){\n s+=to_string(root->val);\n ans+=stoi(s);\n return;\n }\n string o = s;\n s+=to_string(root->val);\n if(root->left) dfs(root->left,s);\n if(root->right) dfs(root->right,s);\n s=o;\n\n }\n int sumNumbers(TreeNode* root) {\n if(!root) return ans;\n string s = \"\";\n dfs(root,s);\n return ans;\n }\n};" }, { "title": "Contains Duplicate III", "algo_input": "Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.\n\n \nExample 1:\nInput: nums = [1,2,3,1], k = 3, t = 0\nOutput: true\nExample 2:\nInput: nums = [1,0,1,1], k = 1, t = 2\nOutput: true\nExample 3:\nInput: nums = [1,5,9,1,5,9], k = 2, t = 3\nOutput: false\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t-231 <= nums[i] <= 231 - 1\n\t0 <= k <= 104\n\t0 <= t <= 231 - 1\n\n", "solution_py": "from sortedcontainers import SortedList\nclass Solution:\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n sl = SortedList()\n for i in range(len(nums)):\n if i > k: sl.remove(nums[i-k-1])\n idxl = sl.bisect_left(nums[i]-t)\n idxr = sl.bisect_right(nums[i]+t)\n if idxl != idxr: return True\n sl.add(nums[i])\n return False", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @param {number} t\n * @return {boolean}\n */\nvar containsNearbyAlmostDuplicate = function(nums, k, t) {\n for(let i=0;i buckets = new HashMap<>();\n // The bucket size is t+1 as the ranges are from 0..t, t+1..2t+1, ..\n long bucketSize = (long) t + 1;\n\n for (int i = 0; i < nums.length; i++) {\n // Making sure only K buckets exists in map.\n if (i > k) {\n long lastBucket = ((long) nums[i - k - 1] - Integer.MIN_VALUE) / bucketSize;\n buckets.remove(lastBucket);\n }\n\n long remappedNum = (long) nums[i] - Integer.MIN_VALUE;\n long bucket = remappedNum / bucketSize;\n\n // If 2 numbers belong to same bucket\n if (buckets.containsKey(bucket)) {\n return true;\n }\n\n // If numbers are in adjacent buckets and the difference between them is at most\n // t.\n if (buckets.containsKey(bucket - 1) && remappedNum - buckets.get(bucket - 1) <= t) {\n return true;\n }\n if (buckets.containsKey(bucket + 1) && buckets.get(bucket + 1) - remappedNum <= t) {\n return true;\n }\n\n buckets.put(bucket, remappedNum);\n }\n\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool containsNearbyAlmostDuplicate(vector& nums, int indexDiff, int valueDiff) {\n int i=0;\n map mp;\n int n=nums.size();\n for(int j=0;jfirst-nums[j])<=valueDiff){\n return true;\n }\n if(val!=mp.begin()){\n val--;\n if(abs(val->first-nums[j])<=valueDiff){\n return true;\n }\n }\n mp[nums[j]]++;\n if((j-i)==indexDiff){\n mp[nums[i]]--;\n if(mp[nums[i]]==0){\n mp.erase(nums[i]);\n }\n i++;\n }\n }\n return false;\n }\n};" }, { "title": "Count Equal and Divisible Pairs in an Array", "algo_input": "Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.\n \nExample 1:\n\nInput: nums = [3,1,2,2,2,1,3], k = 2\nOutput: 4\nExplanation:\nThere are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4], k = 1\nOutput: 0\nExplanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i], k <= 100\n\n", "solution_py": "class Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n n=len(nums)\n c=0\n for i in range(0,n):\n for j in range(i+1,n):\n if nums[i]==nums[j] and ((i*j)%k==0):\n c+=1\n return c", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar countPairs = function(nums, k) {\n var count = 0;\n for(let i=0; i> hMap = new HashMap<>();\n int count = 0;\n for(int i = 0 ; i < nums.length ; i++){\n if(!hMap.containsKey(nums[i])){\n List l = new ArrayList<>();\n l.add(i);\n hMap.put(nums[i],l);\n }else{\n List v = hMap.get(nums[i]);\n for(Integer j : v){\n if((i*j)%k == 0) count++;\n }\n v.add(i);\n hMap.put(nums[i],v);\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countPairs(vector& nums, int k) {\n int count=0;\n for(int i=0;i int:\n dp = []\n dp.append(t[0])\n \n r = len(t)\n answer = float('inf')\n for i in range(1, r):\n c = len(t[i])\n dp.append([])\n for j in range(0, c):\n if j == 0:\n val = dp[i - 1][j] + t[i][j]\n elif j == c - 1:\n val = dp[i - 1][j - 1] + t[i][j]\n else:\n val = min(dp[i - 1][j], dp[i - 1][j - 1]) + t[i][j]\n if i == r - 1:\n answer = min(answer, val)\n dp[i].append(val)\n return answer if r > 1 else t[0][0]", "solution_js": "var minimumTotal = function(triangle) {\n const memo = {};\n \n function minPath(row, col) {\n let key = `${row}:${col}`;\n \n if (key in memo) {\n return memo[key];\n }\n \n let path = triangle[row][col];\n \n if (row < triangle.length - 1) {\n path += Math.min(minPath(row + 1, col), minPath(row + 1, col + 1));\n }\n \n memo[key] = path;\n \n return path;\n }\n \n return minPath(0, 0);\n};", "solution_java": "class Solution {\n public int minimumTotal(List> triangle) {\n\n int n = triangle.get( triangle.size() - 1).size();\n int dp[] = new int[n + 1];\n\n for(int i = triangle.size() - 1; i>=0; i--)\n {\n for(int j = 0; j>& tr , int lvl , int ind) {\n \n if(ind >= tr[lvl].size()) // To check if we are going out of bound \n return INT_MAX;\n \n if(lvl == tr.size() - 1) { // Return if we are on last line\n return tr[lvl][ind];\n }\n \n int s = travel(tr , lvl + 1, ind ); // Go South\n int se = travel(tr , lvl + 1 , ind + 1); // Go South East \n \n\t\t// Return the minimum of south and south east + cost of the index we are currently at.\n\t\t\n return min(s , se) + tr[lvl][ind]; \n \n }\n \n \n int minimumTotal(vector>& triangle) {\n return travel(triangle , 0 , 0);\n }\n};" }, { "title": "Binary Search Tree to Greater Sum Tree", "algo_input": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\n\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than 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 = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\nExample 2:\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 100].\n\t0 <= Node.val <= 100\n\tAll the values in the tree are unique.\n\n\n \nNote: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/\n", "solution_py": "class Solution:\n def bstToGst(self, root):\n self.total = 0\n def dfs(n):\n if n:\n dfs(n.right)\n self.total += n.val\n n.val = self.total\n dfs(n.left)\n dfs(root)\n return root", "solution_js": "var bstToGst = function(root) {\n let sum = 0;\n const traverse = (r = root) => {\n if(!r) return null;\n traverse(r.right);\n let temp = r.val;\n r.val += sum;\n sum += temp;\n traverse(r.left);\n }\n traverse();\n return root;\n};", "solution_java": "class Solution {\n int sum=0;\n public TreeNode bstToGst(TreeNode root) {\n if(root!=null){\n bstToGst(root.right);\n sum += root.val;\n root.val = sum;\n bstToGst(root.left);\n }\n return root;\n }\n\n \n \n}", "solution_c": "class Solution {\npublic:\n\n int s = 0;\n\n void solve(TreeNode* root){\n if(!root) return;\n solve(root->right);\n\n root->val = s + root->val;\n s = root->val;\n\n solve(root->left);\n return;\n }\n\n TreeNode* bstToGst(TreeNode* root) {\n if(!root) return NULL;\n solve(root);\n return root;\n }\n};" }, { "title": "Complete Binary Tree Inserter", "algo_input": "A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.\n\nDesign an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.\n\nImplement the CBTInserter class:\n\n\n\tCBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.\n\tint insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode.\n\tTreeNode get_root() Returns the root node of the tree.\n\n\n \nExample 1:\n\nInput\n[\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n[[[1, 2]], [3], [4], []]\nOutput\n[null, 1, 2, [1, 2, 3, 4]]\n\nExplanation\nCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3); // return 1\ncBTInserter.insert(4); // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree will be in the range [1, 1000].\n\t0 <= Node.val <= 5000\n\troot is a complete binary tree.\n\t0 <= val <= 5000\n\tAt most 104 calls will be made to insert and get_root.\n\n", "solution_py": "class CBTInserter:\n\n def __init__(self, root: Optional[TreeNode]):\n self.root = root\n self.queue = Queue()\n self.queue.put(self.root)\n self.parent_of_last_inserted = None\n \n def insert(self, val: int) -> int:\n if self.parent_of_last_inserted is not None and self.parent_of_last_inserted.right is None:\n self.parent_of_last_inserted.right = TreeNode(val)\n self.queue.put(self.parent_of_last_inserted.right)\n return self.parent_of_last_inserted.val\n \n while not self.queue.empty():\n node = self.queue.get()\n if node.left is None:\n node.left = TreeNode(val)\n self.queue.put(node.left)\n self.parent_of_last_inserted = node\n return node.val\n else:\n self.queue.put(node.left)\n if node.right is None:\n node.right = TreeNode(val)\n self.queue.put(node.right)\n self.parent_of_last_inserted = node\n return node.val\n else:\n self.queue.put(node.right)\n \n\n def get_root(self) -> Optional[TreeNode]:\n return self.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 {TreeNode} root\n */\nvar CBTInserter = function(root) {\n this.root = root;\n};\n\n/** \n * @param {number} val\n * @return {number}\n */\nCBTInserter.prototype.insert = function(val) {\n let cur = this.root;\n let queue = [cur];\n while(queue.length){\n let updatedQueue = [];\n while(queue.length){\n let node = queue.shift();\n if(!node.left) {\n node.left = new TreeNode(val);\n return node.val;\n }\n else updatedQueue.push(node.left);\n if(!node.right) {\n node.right = new TreeNode(val);\n return node.val;\n }\n else updatedQueue.push(node.right);\n }\n queue = updatedQueue ;\n }\n \n};\n\n/**\n * @return {TreeNode}\n */\nCBTInserter.prototype.get_root = function() {\n return this.root;\n};\n\n/** \n * Your CBTInserter object will be instantiated and called as such:\n * var obj = new CBTInserter(root)\n * var param_1 = obj.insert(val)\n * var param_2 = obj.get_root()\n */", "solution_java": "class CBTInserter {\n\n private TreeNode root;\n private int total;\n\n private int count(TreeNode root) {\n if (root == null) return 0;\n return 1+count(root.left)+count(root.right);\n }\n\n public CBTInserter(TreeNode root) {\n this.root = root;\n total = count(root);\n }\n\n private int insertBinary(int val, int k, int right) {\n int left = 0;\n var ptr = root;\n while (left < right) {\n if (left == right -1) {\n if (ptr.left == null) ptr.left = new TreeNode(val);\n else ptr.right = new TreeNode(val);\n return ptr.val;\n }\n int mid = (right-left) / 2 + left;\n if (mid >= k ) {\n ptr = ptr.left;\n right = mid;\n } else if (mid < k) {\n left = mid+1;\n ptr = ptr.right;\n }\n }\n return 0;\n }\n\n public int insert(int val) {\n int depth = 0;\n int n = total;\n while(n > 0) {\n depth++;\n n /= 2;\n }\n if ((1< arr;\n\n CBTInserter(TreeNode* root) {\n\n arr.push_back(root);\n queue q;\n q.push(root);\n while(!q.empty()){\n\n if(q.front() -> left != NULL){\n arr.push_back(q.front() -> left);\n q.push(q.front() -> left);\n }\n if(q.front() -> right != NULL){\n arr.push_back(q.front() -> right);\n q.push(q.front() -> right);\n }\n q.pop();\n\n }\n }\n\n int insert(int val) {\n\n TreeNode* new_node = new TreeNode(val);\n arr.push_back(new_node);\n int parent_index = (arr.size()-2)/2;\n if(2*parent_index +1 == arr.size()-1){arr[parent_index] -> left = new_node;}\n else{arr[parent_index] -> right = new_node;}\n return arr[parent_index] -> val;\n }\n\n TreeNode* get_root() {\n return arr[0];\n }\n};\n\n/**\n * Your CBTInserter object will be instantiated and called as such:\n * CBTInserter* obj = new CBTInserter(root);\n * int param_1 = obj->insert(val);\n * TreeNode* param_2 = obj->get_root();\n */" }, { "title": "Number of Lines To Write String", "algo_input": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.\n\nYou are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.\n\nReturn an array result of length 2 where:\n\n\n\tresult[0] is the total number of lines.\n\tresult[1] is the width of the last line in pixels.\n\n\n \nExample 1:\n\nInput: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: [3,60]\nExplanation: You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.\n\nExample 2:\n\nInput: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput: [2,4]\nExplanation: You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.\n\n \nConstraints:\n\n\n\twidths.length == 26\n\t2 <= widths[i] <= 10\n\t1 <= s.length <= 1000\n\ts contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def numberOfLines(self, w: List[int], s: str) -> List[int]:\n r=[0]*2\n px=0\n l=1\n for i in range(len(s)):\n px+=w[ord(s[i])-97]\n if px>100:\n l+=1\n px=w[ord(s[i])-97]\n \n print(ord(s[i]))\n r[0]=l\n r[1]=px\n return r\n ", "solution_js": "var numberOfLines = function(widths, s) {\n let pixel=100, line=1;\n for(let i=0; i=widths[s[i].charCodeAt()-97]){\n pixel-=widths[s[i].charCodeAt()-97];\n }else{\n // this word should be written in NEXT line, so it CANNOT count.\n i--; line++; pixel=100;\n }\n }\n // 100-pixel = space used in this line.\n return [line, 100-pixel];\n};", "solution_java": "class Solution {\n public int[] numberOfLines(int[] widths, String s) {\n int sum=0,count=0;\n for(int j=0;j100)\n {\n j--;\n count++;\n sum=0;\n continue;\n }\n }\n int[] arr = new int[2];\n arr[0]=count+1;\n arr[1]=sum;\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector numberOfLines(vector& widths, string s) {\n vectorans(2);\n int lines =0;\n int calc = 0;\n int i =0;\n while(i100){\n i-=1;\n calc-=widths[s[i]-'a'];\n }\n lines++;\n // cout< str:\n charValue = [0] * 26\n for i in range(len(order)):\n idx = ord(order[i]) - ord('a')\n charValue[idx] = 26 - i\n\n arrS = []\n n = 0\n for c in s:\n arrS.append(c)\n n += 1\n\n sorted = False\n while not sorted:\n sorted = True\n for i in range(n - 1):\n if charValue[ord(arrS[i]) - ord('a')] < charValue[ord(arrS[i + 1]) - ord('a')]:\n sorted = False\n arrS[i], arrS[i + 1] = arrS[i + 1], arrS[i]\n\n return ''.join(arrS)", "solution_js": "var customSortString = function(order, s) {\n const hm = new Map();\n for(let c of s) {\n if(!hm.has(c)) hm.set(c, 0);\n hm.set(c, hm.get(c) + 1);\n }\n \n let op = \"\";\n for(let c of order) {\n if(hm.has(c)) {\n op += \"\".padStart(hm.get(c), c);\n hm.delete(c);\n }\n }\n for(let [c, occ] of hm) {\n op += \"\".padStart(hm.get(c), c);\n hm.delete(c);\n }\n return op;\n};", "solution_java": "class Solution {\n public String customSortString(String order, String s) {\n if(s.length() <= 1) return s;\n \n StringBuilder finalString = new StringBuilder();\n HashMap hm = new HashMap<>();\n \n for(int i = 0; i < s.length(); i++) {\n char actualChar = s.charAt(i);\n \n if(order.indexOf(actualChar) == -1) {\n finalString.append(actualChar);\n } else {\n hm.put(actualChar, hm.getOrDefault(actualChar, 0) + 1);\n }\n }\n \n for(int i = 0; i < order.length(); i++) {\n char actualChar = order.charAt(i);\n \n if (hm.get(actualChar) != null){\n for(int j = 0; j < hm.get(actualChar); j++) {\n finalString.append(actualChar);\n }\n }\n }\n \n return finalString.toString(); \n }\n}", "solution_c": "class Solution {\npublic:\n string customSortString(string order, string s) {\n\n mapmp;\n\n for(int i =0 ; i > p;\n int x=200;\n for(int i =0 ; i < s.size(); i++)\n {\n if(mp[s[i]]!=0)\n p.push_back(make_pair(mp[s[i]],s[i]));\n else\n p.push_back(make_pair(x--,s[i]));\n\n }\n\n sort(p.begin(),p.end());\n string ans=\"\";\n for(int i =0 ;i < p.size(); i++)\n {\n ans+=p[i].second;\n }\n return ans;\n }\n};" }, { "title": "Number of Atoms", "algo_input": "Given a string formula representing a chemical formula, return the count of each atom.\n\nThe atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\n\nOne or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.\n\n\n\tFor example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible.\n\n\nTwo formulas are concatenated together to produce another formula.\n\n\n\tFor example, \"H2O2He3Mg4\" is also a formula.\n\n\nA formula placed in parentheses, and a count (optionally added) is also a formula.\n\n\n\tFor example, \"(H2O2)\" and \"(H2O2)3\" are formulas.\n\n\nReturn the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\n\nThe test cases are generated so that all the values in the output fit in a 32-bit integer.\n\n \nExample 1:\n\nInput: formula = \"H2O\"\nOutput: \"H2O\"\nExplanation: The count of elements are {'H': 2, 'O': 1}.\n\n\nExample 2:\n\nInput: formula = \"Mg(OH)2\"\nOutput: \"H2MgO2\"\nExplanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n\n\nExample 3:\n\nInput: formula = \"K4(ON(SO3)2)2\"\nOutput: \"K4N2O14S4\"\nExplanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n\n\n \nConstraints:\n\n\n\t1 <= formula.length <= 1000\n\tformula consists of English letters, digits, '(', and ')'.\n\tformula is always valid.\n\n", "solution_py": "from collections import Counter, deque\n\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n \"\"\"\n parser:\n formula: elem {count} formula\n elem: term | ( formula )\n term: [A-Z](a-z)+\n count: [0-9]+\n \"\"\"\n \n \n def parse_formula(dq, allCount=Counter()):\n lhs = parse_elem(dq)\n count = 1\n while dq and dq[0].isdigit():\n count = parse_count(dq)\n for k in lhs.keys():\n allCount[k] += lhs[k] * count\n\n if dq and dq[0] not in ')':\n return parse_formula(dq, allCount)\n else:\n return allCount\n\n def parse_elem(dq):\n if dq and dq[0] == '(':\n dq.popleft()\n res = parse_formula(dq, Counter())\n dq.popleft()\n return res\n else:\n elem = ''\n if dq and dq[0].isupper():\n elem += dq.popleft()\n while dq and dq[0].islower():\n elem += dq.popleft()\n return {elem: 1}\n\n def parse_count(dq):\n c = 0\n while dq and dq[0].isdigit():\n c = c * 10 + int(dq.popleft())\n return c\n\n formula = deque(formula)\n count_result = parse_formula(formula)\n result = ''\n for k in sorted(count_result.keys()):\n v = count_result[k]\n if v == 1:\n result += k\n else:\n result += f\"{k}{count_result[k]}\"\n return result", "solution_js": "var countOfAtoms = function(formula) {\n function getElementCount(flatFormula) {\n const reElementCount = /([A-Z][a-z]*)(\\d*)/g;\n let matches = flatFormula.matchAll(reElementCount);\n \n let output = new Map();\n \n for (let [match, element, count] of matches) {\n count = count === '' ? 1 : +count;\n \n if (output.has(element)) {\n output.set(element, output.get(element) + count);\n } else {\n output.set(element, count);\n }\n }\n \n return output;\n }\n \n function flattenElementCount(elCountMap) {\n let arr = [...elCountMap.entries()].sort();\n \n return arr.reduce( (str, item) => {\n let num = item[1] === 1 ? '' : item[1];\n return str + item[0] + num;\n }, '' );\n }\n \n function unnest(fullMatch, innerFormula, multiplier) {\n let elementCount = getElementCount(innerFormula);\n multiplier = multiplier === '' ? 1 : +multiplier;\n \n for (let [element, count] of elementCount) {\n elementCount.set(element, elementCount.get(element) * multiplier);\n }\n \n return flattenElementCount(elementCount);\n }\n \n function flattenFormula(formula) {\n const reNested = /\\((\\w+)\\)(\\d*)/g;\n \n while (reNested.test(formula)) {\n formula = formula.replaceAll(reNested, unnest);\n }\n \n return formula;\n }\n \n let flatFormula = flattenFormula(formula); \n \n return flattenElementCount(getElementCount(flatFormula));\n};", "solution_java": "class Solution {\n public String countOfAtoms(String formula) {\n Deque multiplier = new ArrayDeque<>();\n Map map = new HashMap<>();\n int lastValue = 1;\n \n multiplier.push(1);\n \n\t\t// Iterate from right to left\n for (int i = formula.length() - 1; i >= 0; i--) {\n if (Character.isDigit(formula.charAt(i))) { // Case of a digit - Get full number and save\n StringBuilder sb = new StringBuilder();\n\t\t\t\t\n while (Character.isDigit(formula.charAt(i-1))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n lastValue = Integer.parseInt(sb.reverse().toString());\n } else if (formula.charAt(i) == ')') { // Start parenthesis - push next multiplier to stack\n multiplier.push(lastValue * multiplier.peek());\n lastValue = 1;\n } else if (formula.charAt(i) == '(') { // End parenthesis - pop last multiplier\n multiplier.pop();\n } else { // Case of an element name - construct name, update count based on multiplier\n StringBuilder sb = new StringBuilder();\n \n while (Character.isLowerCase(formula.charAt(i))) {\n sb.append(formula.charAt(i));\n i--;\n }\n sb.append(formula.charAt(i));\n \n String element = sb.reverse().toString();\n map.put(element, map.getOrDefault(element, 0) + lastValue * multiplier.peek());\n lastValue = 1;\n }\n }\n \n\t\t// Sort map keys\n List elements = new ArrayList<>(map.keySet());\n StringBuilder sb = new StringBuilder();\n Collections.sort(elements);\n \n\t\t// Construct output\n for (String element : elements) {\n sb.append(element);\n if (map.get(element) > 1) {\n sb.append(map.get(element)); \n }\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n // helper functions\n bool isUpper(char ch) {\n return ch >= 65 && ch <= 90;\n }\n\n bool isLower(char ch) {\n return ch >= 97 && ch <= 122;\n }\n\n bool isLetter(char ch) {\n return isUpper(ch) || isLower(ch);\n }\n\n bool isNumber(char ch) {\n return ch >= 48 && ch <= 57;\n }\n\n void addKey(map& count, string key, long int value) {\n if(count.find(key) != count.end()) {\n count[key] = count[key] + value;\n }\n else {\n count[key] = value;\n }\n }\n\n // very specific utility function\n string buildName(string formula, int& i) {\n string name = \"\";\n name.push_back(formula[i]);\n if(isUpper(formula[i])) {\n return name;\n }\n if(i == formula.length()-1) {\n return name;\n }\n while(isLower(formula[i-1])) {\n name.push_back(formula[i-1]);\n i--;\n }\n name.push_back(formula[i-1]);\n i--;\n reverse(name.begin(), name.end());\n return name;\n }\n\n // very specific utility function\n long int buildCount(string formula, int& i, vector& stack) {\n long int num = formula[i] - '0';\n long int place = 1;\n if(i == 0) {\n return num;\n }\n while(isNumber(formula[i-1])) {\n place = place * 10;\n num = (formula[i-1]-'0') * place + num;\n i--;\n }\n return num;\n }\n\n string countOfAtoms(string formula) {\n string ans;\n map count;\n vector stack;\n long int factor = 1;\n string name = \"\";\n long int num = -1; // -1 indicates a number reset, ie, count = 1\n\n // iterator i is passed by reference to keep track of\n // the substrings that are builded, ie, atom\n // names or numbers\n int i = formula.length()-1;\n while (i >= 0) {\n // here we need the number after the bracket close. This is\n // either 1 or num depending on whether we built a number before\n if(formula[i] == ')') {\n if(i+1 <= formula.length()-1 && isNumber(formula[i+1])) {\n stack.push_back(num);\n factor = factor * num;\n num = -1;\n }\n else {\n stack.push_back(1);\n }\n }\n // here is why we need a stack. Remove latest factor that was added.\n else if(formula[i] == '(') {\n factor = factor / stack.back();\n stack.pop_back();\n }\n // once we detect a letter, we know it can only be a word. num gives us the atom subscript\n // and factor gives us the molecular count.\n else if(isLetter(formula[i])) {\n name = buildName(formula, i);\n if(num == -1) {\n addKey(count, name, 1 * factor);\n }\n else {\n addKey(count, name, num * factor);\n }\n num = -1; // reset number\n }\n else if(isNumber(formula[i])) {\n num = buildCount(formula, i, stack);\n }\n i--;\n }\n\n // arrange name and count in a string\n map::iterator it;\n for (it = count.begin(); it != count.end(); it++)\n {\n ans = ans + it->first;\n if(it->second != 1) {\n ans = ans + to_string(it->second);\n }\n }\n return ans;\n }\n};" }, { "title": "Merge Intervals", "algo_input": "Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n\n \nExample 1:\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n\n\nExample 2:\n\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nExplanation: Intervals [1,4] and [4,5] are considered overlapping.\n\n\n \nConstraints:\n\n\n\t1 <= intervals.length <= 104\n\tintervals[i].length == 2\n\t0 <= starti <= endi <= 104\n\n", "solution_py": "class Solution:\n def merge(self, A: List[List[int]]) -> List[List[int]]:\n\t#sort array wrt its 0'th index\n A.sort(key=lambda x:x[0])\n i=0\n while i<(len(A)-1):\n if A[i][1]>=A[i+1][0]:\n A[i][1]=max(A[i+1][1],A[i][1])\n A.pop(i+1)\n else:\n i+=1\n return(A)\n ", "solution_js": "/**\n * @param {number[][]} intervals\n * @return {number[][]}\n */\n\nvar merge = function(intervals) {\n // sorting the intervals array first is a general good first step\n intervals.sort((a,b) => a[0] - b[0]);\n const result = [];\n // i am using the result array as a way to compare previous and next intervals\n result.push(intervals[0])\n for (let i=1; i= interval[0]) {\n // overlap detected\n const [ l, r ] = result.pop();\n // if overlap, merge intervals by taking min/max of both boundaries\n const newL = Math.min(l, interval[0])\n const newR = Math.max(r, interval[1])\n result.push([newL, newR])\n } else {\n result.push(intervals[i])\n }\n }\n return result\n};", "solution_java": "class Solution {\n public int[][] merge(int[][] intervals) {\n // sort\n // unknown size of ans = use ArrayList\n // insert from back\n // case 1 : Merging\n // start of new interval is less that end of old interval\n // new end = Math.max(new intervals end, old intervals end)\n // case 2 : Non-merging\n // seperate interval\n // convert ArrayList to array and return\n\n Arrays.sort(intervals, (a,b) -> a[0]-b[0]);\n ArrayList list = new ArrayList<>();\n for(int i = 0; i < intervals.length; i++) {\n if(i == 0) {\n list.add(intervals[i]);\n } else {\n int[] prev = list.get(list.size()-1);\n int[] curr = intervals[i];\n if(curr[0] <= prev[1]) {\n prev[1] = Math.max(curr[1], prev[1]);\n }else {\n list.add(curr);\n }\n }\n }\n return list.toArray(new int[list.size()][2]);\n }\n}", "solution_c": "class Solution {\npublic:\n vector> merge(vector>& intervals) {\n sort(intervals.begin(), intervals.end());\n vector> res;\n int i=0;\n while(i<=intervals.size()-1){\n int start=intervals[i][0];\n int end=intervals[i][1];\n while(i=intervals[i+1][0]){\n i++;\n if(end str:\n if k>1:\n s=list(c for c in s)\n s.sort()\n return ''.join(s)\n s1=s\n for i in range(len(s)):\n s=s[1:]+s[0]\n s1=min(s1,s)\n return s1", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar orderlyQueue = function(s, k) {\n // rotate the string one by one, and check which is lexographically smaller\n if (k === 1) {\n let temp = `${s}`;\n let smallest = `${s}`;\n let count = 0;\n while (count < s.length) {\n temp = temp.substring(1, s.length) + temp.charAt(0);\n if (temp < smallest) {\n smallest = temp;\n }\n count++;\n }\n return smallest;\n }\n \n // if k is greater than 1, any permutation is possilbe\n // so we simply return the sorted string (convert to array -> sort -> back to string)\n if (k > 1) {\n return [...s].sort().join('');\n }\n \n return s;\n};", "solution_java": "// Time O(n)\n// Space O(n)\nclass Solution {\n public String orderlyQueue(String s, int k) {\n int n = s.length();\n String ans = \"\";\n if (k == 1){\n s+=s; // add itself again\n for (int i = 0; i < n; i++) if (ans.isEmpty() || s.substring(i, i+n).compareTo(ans) < 0){\n ans = s.substring(i, i+n);\n }\n }else{\n char[] arr = s.toCharArray();\n Arrays.sort(arr);\n ans = String.valueOf(arr);\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\nstring orderlyQueue(string s, int k) {\n \nif(k>1){\n sort(s.begin(),s.end());\n return s;\n }\n else{\n string res=s;\n \n for(int i=0;i 3 and (val - 1) % 3 == 0 and index != len(n) - 1:\n result += dot\n val = 1 \n index += 1\n\n return result", "solution_js": "var thousandSeparator = function(n) {\n let ans = \"\";\n\n if(n >= 1000){\n const arr = String(n).split('');\n for(let i=0;i temp || temp === 6 && arr.length > temp || temp === 9 && arr.length > temp || temp === 12 && arr.length > temp){\n ans += '.';\n }\n ans += arr[i];\n }\n }else{\n ans += n;\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public String thousandSeparator(int n) {\n \n StringBuffer str = new StringBuffer(Integer.toString(n));\n int index = str.length() - 3;\n \n while(index >= 1){\n str.insert(index , '.');\n index = index - 3;\n }\n \n return str.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string thousandSeparator(int n) {\n string s=\"\";\n int a=0;\n if(n==0)return \"0\";\n while(n>0){\n s+=char(n%10+48);\n a++;\n n/=10;\n if(a==3&&n!=0)\n {\n a=0;\n s+=\".\";\n }\n }\n reverse(s.begin(),s.end());\n return s;\n }\n};" }, { "title": "Avoid Flood in The City", "algo_input": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.\n\nGiven an integer array rains where:\n\n\n\trains[i] > 0 means there will be rains over the rains[i] lake.\n\trains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.\n\n\nReturn an array ans where:\n\n\n\tans.length == rains.length\n\tans[i] == -1 if rains[i] > 0.\n\tans[i] is the lake you choose to dry in the ith day if rains[i] == 0.\n\n\nIf there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\n\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.\n\n \nExample 1:\n\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.\n\n\nExample 2:\n\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\n\n\nExample 3:\n\nInput: rains = [1,2,0,1,2]\nOutput: []\nExplanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.\n\n\n \nConstraints:\n\n\n\t1 <= rains.length <= 105\n\t0 <= rains[i] <= 109\n\n", "solution_py": "from bisect import bisect_left\n\nclass Solution:\n def avoidFlood(self, rains):\n full_lakes, dry_dates = {}, []\n ans = [-1] * len(rains)\n\n for date, rain_lake in enumerate(rains):\n if rain_lake == 0: # no rain, we can dry one lake\n dry_dates.append(date) # keep dry date, we'll decide later\n continue\n\n if rain_lake in full_lakes: # the lake is already full\n # BS find out earliest day we can use to dry that lake | greedy\n dry_day = bisect_left(dry_dates, full_lakes[rain_lake])\n\n if dry_day >= len(dry_dates): return [] # can not find a date to dry this lake\n\n ans[dry_dates.pop(dry_day)] = rain_lake # dry this lake at the date we choose\n\n # remember latest rain on this lake\n full_lakes[rain_lake] = date\n\n # we may have dry dates remain, on these days, rain > 0, we can not use -1, just choose day 1 to dry (maybe nothing happend)\n for dry_day in dry_dates:\n ans[dry_day] = 1\n\n return ans", "solution_js": "var avoidFlood = function(rains) {\n const n = rains.length;\n const filledLakes = new Map();\n const res = new Array(n).fill(-1);\n const dryDays = [];\n\n for (let i = 0; i < n; i++) {\n const lake = rains[i]; // lake to rain on\n\n if (lake === 0) {\n // It is a dry day\n dryDays.push(i);\n }\n else if (!filledLakes.has(lake)) {\n // The lake is not filled yet, so we let it be filled (we just don't want it to be rained on again and be flooded)\n filledLakes.set(lake, i);\n }\n else {\n // The lake is already filled. We want to see if a dry day was available after the lake was previously rained on so that we can empty the lake\n const lake_index = filledLakes.get(lake); //\n const dry_index = binarySearch(lake_index);\n\n if (dry_index === dryDays.length) return []; // there was no dry day after the lake was previouly filled\n\n res[dryDays[dry_index]] = lake; // mark the earliest dry day that was used in our result array\n filledLakes.set(lake, i); // we need to update the day that the lake is rained on again\n dryDays.splice(dry_index, 1); // remove the dry day that was used (this is not very efficient, but it just makes our code cleaner)\n }\n }\n\n dryDays.forEach((day) => res[day] = 1);\n\n return res;\n\n function binarySearch(target) {\n let left = 0;\n let right = dryDays.length - 1;\n\n while (left <= right) {\n const mid = left + Math.floor((right - left) / 2);\n\n if (dryDays[mid] < target) left = mid + 1;\n else right = mid - 1;\n }\n\n return left;\n }\n};", "solution_java": "class Solution {\n public int[] avoidFlood(int[] rains) {\n // the previous appeared idx of rains[i]\n Map map = new HashMap<>();\n TreeSet zeros = new TreeSet<>();\n int[] res = new int[rains.length];\n for (int i = 0; i < rains.length; i++) {\n if (rains[i] == 0) {\n zeros.add(i);\n } else {\n if (map.containsKey(rains[i])) {\n // find the location of zero that can be used to empty rains[i]\n Integer next = zeros.ceiling(map.get(rains[i]));\n if (next == null) return new int[0];\n res[next] = rains[i];\n zeros.remove(next);\n }\n res[i] = -1;\n\t\t\t\tmap.put(rains[i], i);\n }\n }\n for (int i : zeros) res[i] = 1;\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector avoidFlood(vector& rains) {\n vector ans(rains.size() , -1) ;\n unordered_map indices ; //store the lake and its index \n set st ; //stores the indices of zeros \n \n for(int i = 0 ; i < rains.size() ; ++i ){\n if(!rains[i]) st.insert(i) ;\n else{\n if(indices.find(rains[i]) == end(indices)) indices[rains[i]] = i ;\n else{\n int prevDay = indices[rains[i]] ;\n auto it = st.upper_bound(prevDay) ;\n if(it == end(st)) return {} ;\n ans[*it] = rains[i] ;\n indices[rains[i]] = i ;\n st.erase(it);\n }\n }\n }\n \n for(int i = 0 ; i < ans.size(); ++i ){\n if(!rains[i] and ans[i] == -1) ans[i] = 1 ;\n }\n return ans ;\n }\n};" }, { "title": "Shortest Palindrome", "algo_input": "You are given a string s. You can convert s to a palindrome by adding characters in front of it.\n\nReturn the shortest palindrome you can find by performing this transformation.\n\n \nExample 1:\nInput: s = \"aacecaaa\"\nOutput: \"aaacecaaa\"\nExample 2:\nInput: s = \"abcd\"\nOutput: \"dcbabcd\"\n\n \nConstraints:\n\n\n\t0 <= s.length <= 5 * 104\n\ts consists of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def shortestPalindrome(self, s: str) -> str:\n \n end = 0\n \n # if the string itself is a palindrome return it\n if(s == s[::-1]):\n return s\n \n # Otherwise find the end index of the longest palindrome that starts\n # from the first character of the string\n \n for i in range(len(s)+1):\n if(s[:i]==s[:i][::-1]):\n end=i-1\n \n # return the string with the remaining characters other than\n # the palindrome reversed and added at the beginning\n \n return (s[end+1:][::-1])+s", "solution_js": "var shortestPalindrome = function(s) {\n const rev = s.split('').reverse().join('');\n const slen = s.length;\n\n const z = s + '$' + rev;\n const zlen = z.length;\n\n const lpt = new Array(zlen).fill(0);\n\n for(let i = 1; i < zlen; i++) {\n let j = lpt[i-1];\n\n while(j > 0 && z.charAt(i) != z.charAt(j))\n j = lpt[j-1];\n\n if(z.charAt(i) == z.charAt(j))\n j++;\n\n lpt[i] = j;\n }\n\n return rev.slice(0, slen - lpt.at(-1)) + s;\n};", "solution_java": "class Solution {\n public String shortestPalindrome(String s) {\n for(int i=s.length()-1; i >= 0; i--){\n if(isPalindrome(s, 0, i)){\n String toAppend = s.substring(i+1);\n String result = new StringBuilder(toAppend).reverse().append(s).toString();\n return result;\n }\n }\n String result = new StringBuilder(s).reverse().append(s).toString();\n return result; \n }\n \n boolean isPalindrome(String s, int left, int right){\n while(left < right){\n if(s.charAt(left) != s.charAt(right))\n return false;\n left++;\n right--;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n string shortestPalindrome(string s) {\n \n int BASE = 26, MOD = 1e9+7;\n int start = s.size()-1;\n \n // Calculate hash values from front and back\n long front = 0, back = 0;\n long power = 1;\n \n for(int i=0; i= 0){\n\t\t\t// Taking character from ending \n int ch = (s[end]-'a'+1);\n \n new_front = (new_front*BASE + ch*power) % MOD;\n new_back = (ch*new_power + new_back) % MOD;\n new_power = (new_power*BASE) % MOD;\n \n int final_front = (new_front + front) % MOD;\n\t\t\tback = (back*BASE) % MOD;\n int final_back = (new_back + back) % MOD;\n \n\t\t\t// Storing it in separate string\n ans += s[end];\n end--;\n \n\t\t\t// Both hashes are same\n if(final_front == final_back){\n break;\n }\n }\n return ans+s;\n }\n};" }, { "title": "Ways to Make a Fair Array", "algo_input": "You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.\n\nFor example, if nums = [6,1,7,4,1]:\n\n\n\tChoosing to remove index 1 results in nums = [6,7,4,1].\n\tChoosing to remove index 2 results in nums = [6,1,4,1].\n\tChoosing to remove index 4 results in nums = [6,1,7,4].\n\n\nAn array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.\n\nReturn the number of indices that you could choose such that after the removal, nums is fair. \n\n \nExample 1:\n\nInput: nums = [2,1,6,4]\nOutput: 1\nExplanation:\nRemove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.\n\n\nExample 2:\n\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can remove any index and the remaining array is fair.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: You cannot make a fair array after removing any index.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 104\n\n", "solution_py": "class Solution:\n\tdef waysToMakeFair(self, nums: List[int]) -> int:\n\t\tif len(nums) == 1:\n\t\t\treturn 1\n\n\t\tif len(nums) == 2:\n\t\t\treturn 0\n\n\t\tprefixEven = sum(nums[2::2])\n\t\tprefixOdd = sum(nums[1::2])\n\t\tresult = 0\n\n\t\tif prefixEven == prefixOdd and len(set(nums)) == 1:\n\t\t\tresult += 1\n\n\t\tfor i in range(1,len(nums)):\n\t\t\tif i == 1:\n\t\t\t\tprefixOdd, prefixEven = prefixEven, prefixOdd \n\n\t\t\tif i > 1:\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tprefixEven -= nums[i-1]\n\t\t\t\t\tprefixEven += nums[i-2]\n\n\t\t\t\telse:\n\t\t\t\t\tprefixOdd -= nums[i-1]\n\t\t\t\t\tprefixOdd += nums[i-2]\n\n\t\t\tif prefixOdd == prefixEven:\n\t\t\t\tresult += 1\n\n\t\treturn result", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar waysToMakeFair = function(nums) {\n let oddSum = 0; \n let evenSum = 0 ;\n let count = 0;\n \n for (let i = 0; i < nums.length; i++) {\n if (i % 2 === 0) {\n evenSum += nums[i];\n } else {\n oddSum += nums[i];\n }\n }\n \n \n for (let i = 0; i < nums.length; i++) {\n if (i % 2 === 0) {\n evenSum -= nums[i];\n if (evenSum === oddSum) {\n count++; \n }\n oddSum += nums[i];\n } else {\n oddSum -= nums[i];\n if (evenSum === oddSum) {\n count++;\n }\n evenSum += nums[i]\n }\n }\n \n return count;\n};", "solution_java": "class Solution {\n public int waysToMakeFair(int[] nums) {\n \n /*\n Idea - \n \n have left (odd & even) & right (odd & even) odd & even sums separately\n \n as we move each element subtract & add appropriately\n */\n int count = 0;\n \n int evenLeft = 0;\n int oddLeft = 0;\n \n int evenRight = 0;\n int oddRight = 0;\n \n // calculate the right odd & even initially since we move from 0->n\n for(int i=0;i n\n for(int i=0;i0)\n {\n // add previous element to left count\n if(i%2 == 0)\n {\n oddLeft +=nums[i-1];\n } else{\n evenLeft+=nums[i-1];\n }\n }\n \n // subtract current element value from right counts so we get right count excluding the current element\n if(i%2 == 0)\n {\n evenRight-=nums[i];\n } else{\n oddRight-=nums[i];\n }\n \n // if at any point we have below condition true increment count\n // notice here we are adding even & odd of opposite sides here since on excluding the current element the right counterpart sum switches\n // i.e if it was odd before it becomes even, else if it was even becomes odd\n if(evenLeft+oddRight == oddLeft+evenRight)\n {\n count++;\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int waysToMakeFair(vector& nums) {\n //it looks a quite complicated problem but actually it is not\n //the main observation here is when a element is deleted the odd sum after the element becomes the evensum and vice versa\n //so we maintain two vectors left and right\n vector left(2,0);\n vector right(2,0);\n \n //left[0],right[0] stores the sum of even indices elements to the left and right side of the element respectively\n //left[1] right[1] stores the sum of odd indices elements to the left and right side of the element respectively\n \n int ans=0; //stores the result\n //first store the odd sum and even sum in right\n for(int i=0;i str:\n \tstack = []\n \t\n \ti = 0\n while i < len(path):\n if path[i] == '/':\n i += 1\n continue\n\n else:\n cur = ''\n while i < len(path) and path[i] != '/':\n cur += path[i]\n i += 1\n\n if cur == '..':\n if stack:\n stack.pop()\n elif cur == '.' or cur == '':\n i += 1\n continue\n else:\n stack.append(cur)\n\n return '/' + '/'.join(stack)", "solution_js": "var simplifyPath = function(path) {\n let stack=[];\n path=path.split(\"/\")\n for(let i=0;i st=new Stack<>();\n for(String dir:paths){\n if(dir.equals(\".\") || dir.length()==0) continue;\n else{\n if(!st.isEmpty() && dir.equals(\"..\"))\n st.pop();\n else if(st.isEmpty() && dir.equals(\"..\"))\n continue;\n else st.push(dir);\n }\n }\n StringBuilder sb=new StringBuilder();\n if(st.isEmpty()) return \"/\";\n for(String s:st){\n sb.append(\"/\"); sb.append(s);\n }\n return sb.toString();\n }\n}", "solution_c": " // Please upvote if it helps\nclass Solution {\npublic:\n string simplifyPath(string path) {\n\n stack st;\n string res;\n\n for(int i = 0; i int:\n nextSmaller = self.nextSmallerElement(nums)\n previousSmaller = self.previousSmallerElement(nums)\n\n score = 0\n for idx, num in enumerate(nums):\n\t\t\t# previousSmaller[idx] (let's say i) and nextSmaller[idx] (let's say j) ensures that the element present at idx is the minimum in range (i -> j)\n i = previousSmaller[idx]\n i += 1\n j = nextSmaller[idx]\n if j == -1:\n j = len(nums)\n j -= 1\n if i <= k <= j:\n score = max(score, num * (j-i+1))\n \n return score\n ", "solution_js": "/*\n\n\tJAVASCRIPT\n\n */\nvar maximumScore = function(nums, k) {\n // iterate to the left to update the minimum value at each index\n let min = nums[k];\n for (let i = k - 1; i >= 0; i--) {\n min = Math.min(min, nums[i]);\n nums[i] = min;\n }\n\n // iterate to the right to update the minimum value at each index\n min = nums[k];\n for (let i = k + 1; i < nums.length; i++) {\n min = Math.min(min, nums[i]);\n nums[i] = min;\n }\n \n // start with 2 pointers at opposite ends of nums\n let left = 0;\n let right = nums.length - 1;\n let bestScore = 0;\n\n while (left <= right) {\n bestScore = Math.max(bestScore, Math.min(nums[left], nums[right]) * (right - left + 1));\n \n // first to check if either pointer is at k\n // if it is at k then we must move the other pointer inwards\n if (left === k) {\n right--;\n } else if (right === k) {\n left++\n \n // if neither index is at k move the pointer\n // that is smaller inwards\n } else if (nums[left] < nums[right]) {\n left++;\n } else {\n right--;\n }\n }\n return bestScore;\n};", "solution_java": "class Solution {\n public int maximumScore(int[] nums, int k) {\n int n = nums.length;\n int i = k - 1, j = k + 1;\n int min = nums[k];\n int ans = min;\n\n while(i >= 0 || j < n) {\n int v1 = 0, v2 = 0;\n int min1 = min, min2 = min;\n\n if(i >= 0) {\n min1 = Math.min(min, nums[i]);\n v1 = min1 * (j - i);\n }\n\n if(j < n) {\n min2 = Math.min(min, nums[j]);\n v2 = min2 * (j - i);\n }\n\n if(v1 > v2) {\n --i;\n ans = Math.max(v1, ans);\n min = Math.min(min1, min);\n }\n else {\n ++j;\n ans = Math.max(ans, v2);\n min = Math.min(min, min2);\n }\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumScore(vector& nums, int k) {\n nums.push_back(0);\n stack st ;\n int n = nums.size(), res = 0;\n for(int i=0; i= nums[i]){\n int height = nums[st.top()];\n st.pop();\n int left = st.empty() ? -1: st.top();\n if(k < i && k > left) res = max(height* (i-left-1), res);\n }\n st.push(i);\n }\n return res;\n }\n};" }, { "title": "Least Number of Unique Integers after K Removals", "algo_input": "Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\n\n\n\n\n \nExample 1:\n\nInput: arr = [5,5,4], k = 1\nOutput: 1\nExplanation: Remove the single 4, only 5 is left.\n\nExample 2:\n\nInput: arr = [4,3,1,1,3,3,2], k = 3\nOutput: 2\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 10^5\n\t1 <= arr[i] <= 10^9\n\t0 <= k <= arr.length\n", "solution_py": "from heapq import heappop, heapify\n\n\n\nclass Solution:\n\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\n counter = collections.Counter(arr)\n\n min_heap = [(count, num) for num, count in counter.items()]\n\n\n\n heapify(min_heap)\n\n\n\n while k > 0:\n\n count, num = min_heap[0]\n\n\n\n if count > k:\n\n break\n\n\n\n heappop(min_heap)\n\n k -= count\n\n\n\n return len(min_heap)", "solution_js": "var findLeastNumOfUniqueInts = function(arr, k) {\n var hsh = {};\n var instance = {}; // store set with index # of occurence\n var count = 0;\n for (var i = 0; i < arr.length; i++)\n {\n if (hsh[arr[i]] == null)\n {\n count ++;\n hsh[arr[i]] = 1;\n if (instance[1] == null)\n {\n var intro = new Set();\n intro.add(arr[i]);\n instance[1] = intro;\n }\n else\n {\n instance[1].add(arr[i]);\n }\n }\n else\n {\n hsh[arr[i]] ++;\n var numTimes = hsh[arr[i]];\n instance[numTimes - 1].delete(arr[i]);\n \n if (instance[numTimes] == null)\n {\n instance[numTimes] = new Set();\n instance[numTimes].add(arr[i]);\n }\n else\n {\n instance[numTimes].add(arr[i]);\n }\n }\n }\n \n var removenum = 0;\n \n for (key in instance)\n {\n var instanceKey = instance[key].size;\n if (k == 0)\n {\n break;\n }\n else if (k >= key*instanceKey)\n {\n k -= key*instanceKey;\n count -= instanceKey;\n }\n else\n {\n count -= Math.floor(k/key);\n break;\n }\n \n }\n return count;\n};", "solution_java": "class Solution {\n public int findLeastNumOfUniqueInts(int[] arr, int k) {\n Map freqMap = new HashMap<>();\n for(int a: arr) freqMap.put(a, freqMap.getOrDefault(a,0)+1);\n PriorityQueue pq = new PriorityQueue<>((i1,i2)->Integer.compare(freqMap.get(i1), freqMap.get(i2)));\n pq.addAll(freqMap.keySet());\n while(k>0 && !pq.isEmpty()){\n int element = pq.poll();\n int toBeDeleted = Math.min(k,freqMap.get(element));\n k-=toBeDeleted;\n if(toBeDeleted& arr, int k) {\n\n int ans;\n\n unordered_map mp;\n\n for(int i=0; i, greater> pq;\n\n for(auto it : mp){\n\n pq.push(it.second);\n\n }\n\n\n\n while(k>0){\n\n k-= pq.top(); \n\n if(k>=0){\n\n pq.pop(); \n\n }\n\n }\n\n return pq.size();\n\n }\n\n};" }, { "title": "Minimum Time to Type Word Using Special Typewriter", "algo_input": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.\n\nEach second, you may perform one of the following operations:\n\n\n\tMove the pointer one character counterclockwise or clockwise.\n\tType the character the pointer is currently on.\n\n\nGiven a string word, return the minimum number of seconds to type out the characters in word.\n\n \nExample 1:\n\nInput: word = \"abc\"\nOutput: 5\nExplanation: \nThe characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.\n\n\nExample 2:\n\nInput: word = \"bza\"\nOutput: 7\nExplanation:\nThe characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.\n\n\nExample 3:\n\nInput: word = \"zjpc\"\nOutput: 34\nExplanation:\nThe characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.\n\n\n \nConstraints:\n\n\n\t1 <= word.length <= 100\n\tword consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def minTimeToType(self, word: str) -> int:\n prev = \"a\"\n res = 0\n for c in word:\n gap = abs(ord(c)-ord(prev))\n res += min(gap, 26 - gap)\n prev = c\n return res + len(word)", "solution_js": "var minTimeToType = function(word) {\n let ops = 0;\n let cur = 'a';\n \n for(const char of word) {\n const diff = Math.abs(cur.charCodeAt(0) - char.charCodeAt(0));\n if(diff > 13) {\n ops += 26 - diff + 1;\n } else {\n ops += diff + 1;\n }\n \n cur = char;\n }\n \n return ops;\n};", "solution_java": "class Solution {\n public int minTimeToType(String word) {\n char prevChar = 'a';\n int totalTime = word.length();\n for(int i = 0; i < word.length(); i++){\n char currChar = word.charAt(i);\n int diff = Math.abs(currChar - prevChar);\n totalTime += Math.min(diff, 26 - diff);\n prevChar = currChar;\n }\n \n return totalTime;\n }\n}", "solution_c": "class Solution {\npublic:\n int minTimeToType(string word) {\n int res = word.size(), point = 'a';\n for (auto ch : word) {\n res += min(abs(ch - point), 26 - abs(point - ch));\n point = ch;\n }\n return res;\n }\n};" }, { "title": "Equal Row and Column Pairs", "algo_input": "Given a 0-indexed n x n integer matrix grid, return the number of pairs (Ri, Cj) such that row Ri and column Cj are equal.\n\nA row and column pair is considered equal if they contain the same elements in the same order (i.e. an equal array).\n\n \nExample 1:\n\nInput: grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput: 1\nExplanation: There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]\n\n\nExample 2:\n\nInput: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput: 3\nExplanation: There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]\n\n\n \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 <= n <= 200\n\t1 <= grid[i][j] <= 105\n\n", "solution_py": "class Solution:\n def equalPairs(self, grid: List[List[int]]) -> int:\n m = defaultdict(int)\n cnt = 0\n\n for row in grid:\n m[str(row)] += 1\n \n for i in range(len(grid[0])):\n col = []\n for j in range(len(grid)):\n col.append(grid[j][i])\n cnt += m[str(col)]\n return cnt", "solution_js": "var equalPairs = function(grid) {\n let n = grid.length\n let count = 0;\n\n let map = new Map()\n\n //making rowArray\n for(let row = 0; row < n; row++){\n let temp = []\n for(let col = 0; col < n; col++){\n temp.push(grid[row][col])\n }\n\n temp = temp.join()\n\n if(map.has(temp)){\n let tempCount = map.get(temp)\n map.set(temp, tempCount+1)\n }\n else{\n map.set(temp, 1)\n }\n }\n\n for(let col = 0; col < n; col++){\n let temp = []\n for(let row = 0; row < n; row++){\n temp.push(grid[row][col])\n }\n\n temp = temp.join()\n\n if(map.has(temp)){\n count += map.get(temp)\n }\n }\n\n return count;\n};", "solution_java": "class Solution {\n public int equalPairs(int[][] grid) {\n HashMap map = new HashMap<>();\n int row = grid.length;\n int col = grid.length;\n for(int i = 0; i < row; i++){\n String res = \"\";\n for(int j = 0; j < col; j++){\n res += \"-\" + grid[i][j];\n }\n map.put(res, map.getOrDefault(res, 0) + 1);\n }\n int cnt = 0;\n for(int j = 0; j < col; j++){\n String res = \"\";\n for(int i = 0; i < row; i++){\n res += \"-\" + grid[i][j];\n }\n cnt += map.getOrDefault(res, 0);\n }\n return cnt;\n }\n}", "solution_c": "class Solution {\npublic:\n int equalPairs(vector>& grid) \n {\n // Number to store the count of equal pairs.\n int ans = 0;\n map, int> mp;\n // Storing each row int he map\n for (int i = 0; i < grid.size(); i++)\n mp[grid[i]]++;\n \n for (int i = 0; i < grid[0].size(); i++)\n {\n vector v;\n // extracting column in a vector.\n for (int j = 0; j < grid.size(); j++)\n v.push_back(grid[j][i]);\n // Add the number of times that column appeared as a row.\n ans += mp[v];\n }\n // Return the number of count\n return ans;\n }\n};" }, { "title": "Magical String", "algo_input": "A magical string s consists of only '1' and '2' and obeys the following rules:\n\n\n\tThe string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.\n\n\nThe first few elements of s is s = \"1221121221221121122……\". If we group the consecutive 1's and 2's in s, it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1's or 2's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\". You can see that the occurrence sequence is s itself.\n\nGiven an integer n, return the number of 1's in the first n number in the magical string s.\n\n \nExample 1:\n\nInput: n = 6\nOutput: 3\nExplanation: The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\n", "solution_py": "class Solution:\n def magicalString(self, n: int) -> int:\n queue, ans, i = deque([2]), 1, 1\n\n while i <= n - 2:\n m = queue.popleft()\n ans += (m == 1)\n queue.extend([1 + (i % 2 == 0)] * m)\n i += 1\n\n return ans", "solution_js": "var magicalString = function(n) {\n const stack = ['1', '2', '2'];\n let magic = 2;\n\n while (stack.length < n) {\n const count = stack[magic++];\n const last = stack[stack.length - 1];\n const addStr = last === '1' ? '2' : '1';\n\n for (let n = 1; n <= count; n++) stack.push(addStr);\n }\n return stack.slice(0, n).filter(str => str === '1').length;\n};", "solution_java": "class Solution {\n public int magicalString(int n) {\n if(n <= 3)\n return 1;\n Magical m = new Magical();\n int ans = 1;\n for(int i = 3; i < n; ++i)\n if(m.next() == 1)\n ++ans;\n return ans;\n }\n}\n\nclass Magical{\n\n private Deque nums;\n private int n;\n\n public Magical(){\n nums = new ArrayDeque<>();\n nums.offerLast(1);\n nums.offerLast(1);\n n = 1;\n }\n\n public int next(){\n if(n-- < 0){\n int c = nums.pollFirst();\n n = c - 2;\n int curr = 3 - nums.peekLast();\n for(; c > 0; --c)\n nums.offerLast(curr);\n return curr;\n }\n return nums.peekLast();\n }\n}", "solution_c": "class Solution {\npublic:\n int magicalString(int n) {\n string s=\"122\";\n int sz=3;\n int start=2,lastDig=2;\n while(sz None:\n self.s = self.s[:self.cursor] + text + self.s[self.cursor:]\n self.cursor += len(text)\n\n def deleteText(self, k: int) -> int:\n new_cursor = max(0, self.cursor - k)\n noOfChars = k if self.cursor - k >= 0 else self.cursor\n self.s = self.s[:new_cursor] + self.s[self.cursor:]\n self.cursor = new_cursor\n return noOfChars\n\n def cursorLeft(self, k: int) -> str:\n self.cursor = max(0, self.cursor - k)\n start = max(0, self.cursor-10)\n return self.s[start:self.cursor]\n\n def cursorRight(self, k: int) -> str:\n self.cursor = min(len(self.s), self.cursor + k)\n start = max(0, self.cursor - 10)\n return self.s[start:self.cursor]", "solution_js": "var TextEditor = function() {\n this.forward = [];\n this.backward = [];\n};\n\n/** \n * @param {string} text\n * @return {void}\n */\nTextEditor.prototype.addText = function(text) {\n for (let letter of text) {\n this.forward.push(letter);\n }\n};\n\n/** \n * @param {number} k\n * @return {number}\n */\nTextEditor.prototype.deleteText = function(k) {\n let deleted = 0;\n while (this.forward.length && deleted < k) {\n this.forward.pop();\n deleted++;\n }\n return deleted;\n};\n\n/** \n * @param {number} k\n * @return {string}\n */\nTextEditor.prototype.cursorLeft = function(k) {\n let moved = 0;\n while (this.forward.length && moved < k) {\n this.backward.push(this.forward.pop());\n moved++;\n }\n return toTheLeft(this.forward);\n};\n\n/** \n * @param {number} k\n * @return {string}\n */\nTextEditor.prototype.cursorRight = function(k) {\n let moved = 0;\n while (moved < k && this.backward.length) {\n this.forward.push(this.backward.pop());\n moved++;\n }\n return toTheLeft(this.forward);\n};\n\n\nfunction toTheLeft (arr) {\n let letters = [];\n for (let i = Math.max(0, arr.length - 10); i < arr.length; i++) {\n letters.push(arr[i]);\n }\n let res = letters.join(\"\");\n return res; \n}", "solution_java": "class TextEditor {\n StringBuilder res;\n int pos=0;\n\n public TextEditor() {\n res = new StringBuilder();\n }\n\n public void addText(String text) {\n res.insert(pos,text);\n pos += text.length();\n }\n\n public int deleteText(int k) {\n int tmp = pos;\n pos -= k;\n if(pos<0) pos=0;\n res.delete(pos,tmp);\n return tmp-pos;\n }\n\n public String cursorLeft(int k) {\n pos-=k;\n if(pos<0) pos = 0;\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n\n public String cursorRight(int k) {\n pos+=k;\n if(pos>res.length()) pos = res.length();\n if(pos<10) return res.substring(0,pos);\n return res.substring(pos-10,pos);\n }\n}", "solution_c": "class TextEditor {\n stack left;\n stack right;\npublic:\n TextEditor() {\n\n }\n\n void addText(string text) {\n for(auto &c : text){\n left.push(c);\n }\n }\n\n int deleteText(int k) {\n int cnt=0;\n while(!left.empty() and k>0){\n left.pop();\n cnt++;\n k--;\n }\n return cnt;\n }\n\n string cursorLeft(int k) {\n while(!left.empty() and k>0){\n char c = left.top();left.pop();\n right.push(c);\n k--;\n }\n // returning the last min(10, len) characters to the left of the cursor\n return cursorShiftString();\n }\n\n string cursorRight(int k) {\n while(!right.empty() and k>0){\n char c = right.top();right.pop();\n left.push(c);\n k--;\n }\n // returning the last min(10, len) characters to the left of the cursor\n return cursorShiftString();\n }\n\n // function to return the last min(10, len) characters to the left of the cursor\n string cursorShiftString(){\n string rtn = \"\";\n int cnt=10;\n while(!left.empty() and cnt>0){\n char c = left.top();left.pop();\n rtn += c;\n cnt--;\n }\n reverse(rtn.begin(),rtn.end());\n for(int i=0;i List[int]:\n ans = [0] * 2\n c = Counter(nums)\n \n for v in c.values():\n ans[0] += (v // 2)\n ans[1] += (v % 2)\n \n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @return {number[]}\n */\nvar numberOfPairs = function(nums) {\n let pairs = 0;\n const s = new Set();\n for (const num of nums) {\n if (s.has(num)) {\n pairs += 1;\n s.delete(num);\n } else {\n s.add(num);\n }\n }\n return [pairs, nums.length - pairs * 2];\n};", "solution_java": "class Solution {\n public int[] numberOfPairs(int[] nums) {\n\n if(nums.length == 1)\n return new int[]{0,1};\n\n HashSet set = new HashSet<>();\n\n int pairs=0;\n for(int i : nums){\n if(!set.contains(i)){\n set.add(i); // No pair present\n }else{\n set.remove(i); // Pair found\n pairs++;\n }\n }\n\n return new int[]{pairs,set.size()};\n }\n}", "solution_c": "class Solution {\npublic:\n\t//store the frequency of each of the number in the map and\n\t//then return the answer as sum all the values dividing 2 and \n\t//sum all by taking reminder of 2\n vector numberOfPairs(vector& nums) {\n unordered_map mp;\n for(auto i: nums) mp[i]++;\n int c1 = 0, c2 = 0;\n for(auto m: mp){\n c1 += m.second/2;\n c2 += m.second%2;\n }\n return {c1, c2};\n }\n};" }, { "title": "Best Time to Buy and Sell Stock with Transaction Fee", "algo_input": "You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.\n\nFind the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.\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 = [1,3,2,8,4,9], fee = 2\nOutput: 8\nExplanation: The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n\n\nExample 2:\n\nInput: prices = [1,3,7,5,10,3], fee = 3\nOutput: 6\n\n\n \nConstraints:\n\n\n\t1 <= prices.length <= 5 * 104\n\t1 <= prices[i] < 5 * 104\n\t0 <= fee < 5 * 104\n\n", "solution_py": "class Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n n = len(prices)\n lookup = {}\n def f(ind, buy, lookup):\n \n if ind == n: return 0\n \n if (ind, buy) in lookup: return lookup[(ind, buy)]\n profit = 0\n if buy:\n profit = max(-prices[ind] + f(ind+1,0,lookup), f(ind+1, 1,lookup))\n else:\n profit = max(prices[ind] + f(ind+1,1,lookup) - fee, f(ind+1, 0,lookup))\n \n lookup[(ind,buy)] = profit\n return lookup[(ind,buy)]\n \n return f(0, 1,lookup)", "solution_js": "/**\n * @param {number[]} prices\n * @param {number} fee\n * @return {number}\n */\nvar maxProfit = function(prices, fee) {\n let purchase = -1*prices[0];//If we purchase on 0th day\n let sell=0;//If we sell on 0th day\n let prevPurchase;\n for(let i=1;i&prices,int i,int buy,vector>&dp,int fee){\n if(i==prices.size())return 0;\n if(dp[i][buy]!=-1)return dp[i][buy];\n int take=0;\n if(buy){\n take=max(-prices[i]+f(prices,i+1,0,dp,fee),f(prices,i+1,1,dp,fee));\n }\n else{\n take=max(prices[i]+f(prices,i+1,1,dp,fee)-fee,f(prices,i+1,0,dp,fee));\n }return dp[i][buy]=take;\n }\n int maxProfit(vector& prices, int fee) {\n vector>dp(prices.size(),vector(2,-1));\n return f(prices,0,1,dp,fee);\n }\n};" }, { "title": "Goat Latin", "algo_input": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.\n\nWe would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:\n\n\n\tIf a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append \"ma\" to the end of the word.\n\n\t\n\t\tFor example, the word \"apple\" becomes \"applema\".\n\t\n\t\n\tIf a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\".\n\t\n\t\tFor example, the word \"goat\" becomes \"oatgma\".\n\t\n\t\n\tAdd one letter 'a' to the end of each word per its word index in the sentence, starting with 1.\n\t\n\t\tFor example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.\n\t\n\t\n\n\nReturn the final sentence representing the conversion from sentence to Goat Latin.\n\n \nExample 1:\nInput: sentence = \"I speak Goat Latin\"\nOutput: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\nExample 2:\nInput: sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n\n \nConstraints:\n\n\n\t1 <= sentence.length <= 150\n\tsentence consists of English letters and spaces.\n\tsentence has no leading or trailing spaces.\n\tAll the words in sentence are separated by a single space.\n\n", "solution_py": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n wordList, result, index = sentence.split(' '), \"\", 1\n for word in wordList:\n if index > 1:\n result += \" \"\n firstLetter = word[0]\n if firstLetter in 'aeiouAEIOU':\n result += word + \"ma\"\n else:\n result += word[1:] + firstLetter + \"ma\"\n for i in range(index):\n result += 'a'\n index += 1\n return result", "solution_js": "/**\n * @param {string} S\n * @return {string}\n */\nvar toGoatLatin = function(S) {\n let re = /[aeiou]/gi\n let word = S.split(' ')\n let add = 0\n let arr = []\n \n for(let i= 0; i < word.length; i++) {\n if(!word[i].substring(0,1).match(re)) {\n arr = word[i].split('')\n let letter = arr.shift()\n arr.push(letter)\n word[i] = arr.join('')\n }\n \n // have to append 'ma' regardless if it starts with a vowel\n word[i] += 'ma'\n \n // append 'a' number of times as the index + 1\n add = i+1\n while(add >0) {\n word[i] += 'a'\n add--\n }\n }\n \n return word.join(' ')\n};", "solution_java": "class Solution {\n public String toGoatLatin(String sentence) {\n StringBuffer sb = new StringBuffer();\n StringBuffer temp = new StringBuffer(\"a\"); // temporary stringbuffer\n\n for(String str : sentence.split(\" \")) {\n if(beginsWithConsonant(str)) {\n sb.append(str.substring(1)); // removing the first letter\n sb.append(str.charAt(0)); // appending it to the end\n } else {\n sb.append(str);\n }\n\n sb.append(\"ma\"); // appending \"ma\" to the end of the word (common operation)\n sb.append(temp); // adding one letter 'a' to the end of each word\n\n // the first word gets \"a\" added to the end,\n // the second word gets \"aa\" added to the end,\n // and so on.\n temp.append(\"a\"); // increasing the a's for every word\n sb.append(\" \"); // to put space between words\n }\n\n return sb.toString().trim(); // using trim() to remove the one extra space from the end of string.\n }\n\n public boolean beginsWithConsonant(String str) {\n return \"aeiou\".indexOf(str.toLowerCase().charAt(0)) == -1;\n }\n}", "solution_c": "class Solution {\npublic:\n string toGoatLatin(string sentence) {\n sentence += ' ';\n vector Words;\n string TEMP, SOL, A = \"a\";\n for (int i = 0; i < sentence.size(); ++i)\n {\n if (sentence[i] == ' ')\n {\n Words.push_back(TEMP);\n TEMP = \"\";\n }\n else\n TEMP += sentence[i];\n }\n for (string V : Words)\n {\n char TMP = tolower(V[0]);\n if (TMP == 'a' || TMP == 'e' || TMP == 'i' || TMP == 'o' || TMP == 'u')\n V += \"ma\";\n else\n {\n TMP = V[0];\n V.erase(0, 1);\n V += TMP;\n V += \"ma\";\n }\n V += A;\n A += 'a';\n SOL += V + ' ';\n }\n SOL.erase(SOL.size() - 1, 1);\n return SOL;\n }\n};" }, { "title": "Minimum Absolute Difference in BST", "algo_input": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.\n\n \nExample 1:\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\nExample 2:\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 104].\n\t0 <= Node.val <= 105\n\n\n \nNote: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/\n", "solution_py": "class Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n cur, stack, minDiff, prev = root, [], 10**5, -10**5\n \n while stack or cur:\n while cur:\n stack.append(cur)\n cur = cur.left\n node = stack.pop()\n minDiff = min(minDiff, node.val - prev)\n prev = node.val\n cur = node.right\n \n return minDiff", "solution_js": "var getMinimumDifference = function(root) {\n let order = inOrder(root, []);\n let diff = Math.abs(order[1] - order[0]);\n for(let i=0;i {\n if(!root) return null;\n inOrder(root.left, order);\n order.push(root.val);\n inOrder(root.right, order);\n return order;\n}", "solution_java": "class Solution {\n public int getMinimumDifference(TreeNode root) {\n Queue queue=new PriorityQueue<>();\n Queue nodesQueue=new LinkedList<>();\n int min=Integer.MAX_VALUE;\n if(root==null)\n return 0;\n nodesQueue.add(root);\n while(!nodesQueue.isEmpty())\n {\n TreeNode node=nodesQueue.poll();\n queue.add(node.val);\n if(node.left!=null)\n { \n nodesQueue.add(node.left);\n }\n if(node.right!=null)\n { \n nodesQueue.add(node.right);\n }\n }\n int prev=queue.poll();\n while(!queue.isEmpty())\n {\n int current=queue.poll();\n int absValue=Math.abs(current-prev);\n prev=current;\n min=Math.min(min,absValue);\n \n } \n return min;\n }\n}", "solution_c": "class Solution {\n TreeNode* pre = nullptr;\n int minimum = std::numeric_limits:: max();\npublic:\n void inorder(TreeNode* node) {\n if (!node) return;\n inorder(node->left);\n if(pre) {\n minimum = min(node->val - pre->val, minimum);\n }\n pre = node;\n inorder(node->right);\n }\n int getMinimumDifference(TreeNode* root) {\n inorder(root);\n return minimum;\n }\n\n};" }, { "title": "Serialize and Deserialize BST", "algo_input": "Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.\n\nThe encoded string should be as compact as possible.\n\n \nExample 1:\nInput: root = [2,1,3]\nOutput: [2,1,3]\nExample 2:\nInput: root = []\nOutput: []\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t0 <= Node.val <= 104\n\tThe input tree is guaranteed to be a binary search tree.\n\n", "solution_py": "class Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n \"\"\"Encodes a tree to a single string.\n \"\"\"\n if not root:\n return \"\"\n res = []\n def dfs(node):\n res.append(str(node.val))\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n dfs(root)\n return ','.join(res)\n def deserialize(self, data: str) -> Optional[TreeNode]:\n \"\"\"Decodes your encoded data to tree.\n \"\"\"\n if len(data) == 0:\n return []\n splitdata = data.split(\",\") \n preorder = []\n for item in splitdata:\n preorder.append(int(item)) \n inorder = sorted(preorder)\n hash_map = {} \n for i in range(len(inorder)):\n hash_map[inorder[i]] = i\n def helper(preorder, pstart, pend, inorder, istart, iend):\n if pstart > pend:\n return None\n elif pstart == pend:\n return TreeNode(preorder[pstart])\n\n root = TreeNode(preorder[pstart])\n \n rootindex = hash_map[preorder[pstart]]\n \n numleft = rootindex - istart\n \n root.left = helper(preorder, pstart+1, pstart + numleft, inorder, istart,rootindex-1 )\n root.right = helper(preorder, pstart + numleft +1, pend, inorder, rootindex +1, iend)\n \n return root\n \n return (helper(preorder, 0, len(preorder)-1, inorder, 0, len(inorder)-1))", "solution_js": ";/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n\n/**\n * Encodes a tree to a single string.\n *\n * @param {TreeNode} root\n * @return {string}\n */\nvar serialize = function(root) {\n // Using Preorder traversal to create a string of BST\n // Preorder works in following way\n // root -> left -> right\n let preorder = [];\n \n function dfs(node) {\n if (node === null) return;\n // Get root value\n preorder.push(node.val);\n\n // Get All the Left values\n dfs(node.left);\n\n // Get all the right values\n dfs(node.right);\n }\n\n // call it with root\n dfs(root)\n\n // Turn into string and return it\n return preorder.join(',')\n};\n\n/**\n * Decodes your encoded data to tree.\n *\n * @param {string} data\n * @return {TreeNode}\n */\nvar deserialize = function(data) {\n if (data === \"\") return null;\n\n // Get numbers array from a string\n const preorder = data.split(',').map(Number);\n\n // using -Infinity and +Infinity as placeholder check\n function recur(lower = -Infinity, upper = Infinity) {\n // This condition useful for when we are filling left side of tree it'll avoid all the values greater then then its upper value by putting null init.\n if (preorder[0] < lower || preorder[0] > upper) return null;\n\n // If preorder become empty\n if (preorder.length === 0) return null;\n\n // Create a root node [shift method will change the original array]\n const root = new TreeNode(preorder.shift());\n\n // Here for left side of tree, we are using current root node's value as 'upper bound' (so higher values ignored).\n root.left = recur(lower, root.val);\n\n // Same as above for right side we are using root node's values as 'lower bound' (so lower values ignored);\n root.right = recur(root.val, upper);\n\n return root;\n }\n\n // Final root will be out BST\n return recur();\n};\n\n/**\n * Your functions will be called as such:\n * deserialize(serialize(root));\n */", "solution_java": "public class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n StringBuilder string = new StringBuilder();\n traverse(root, string);\n return string.toString();\n }\n\n private void traverse(TreeNode root, StringBuilder string){\n if(root == null) return;\n string.append(root.val).append(\",\");\n traverse(root.left, string);\n traverse(root.right, string);\n }\n\n // Decodes your encoded data to tree.\n public TreeNode deserialize(String data) {\n if(data.isEmpty()) return null;\n\n String[] dataArr = data.split(\",\");\n\n TreeNode root = new TreeNode(Integer.parseInt(dataArr[0]));\n\n for(int i = 1; i < dataArr.length; i++)\n insert(Integer.parseInt(dataArr[i]), root);\n\n return root;\n }\n\n private void insert(int digit, TreeNode root){\n\n if(digit > root.val){\n if(root.right != null)\n insert(digit, root.right);\n else\n root.right = new TreeNode(digit);\n } else {\n if(root.left != null)\n insert(digit, root.left);\n else\n root.left = new TreeNode(digit);\n }\n\n }\n}", "solution_c": "class Codec\n{\n public:\n\n string pre(TreeNode * root)\n {\n if(root==NULL)\n return \"\";\n\n int temp = root->val;\n string tempz = to_string(temp);\n\n string l = pre(root->left);\n string r = pre(root->right);\n\n return (tempz + \",\" + l + \",\" + r);\n }\n\n vector parse_string(string data)\n {\n vector ans;\n string temp = \"\";\n int n=data.size();\n\n for(int i=0;i& preorder, int min_val, int max_val, int& preorder_idx, int n)\n {\n if(preorder_idx == n)\n return NULL;\n int val = preorder[preorder_idx];\n if(min_val <= val and val <= max_val)\n {\n TreeNode * curr = new TreeNode(val);\n preorder_idx++;\n curr->left = make_tree(preorder, min_val, val-1, preorder_idx, n);\n curr->right = make_tree(preorder, val+1, max_val, preorder_idx, n);\n return curr;\n }\n else\n return NULL;\n }\n\n string serialize(TreeNode* root)\n {\n string traversal = pre(root);\n //cout< traversal = parse_string(data);\n\n // for(auto x:traversal)\n // cout< List[int]:\n available = list(range(k)) # already a min-heap\n busy = [] \n res = [0] * k\n for i, a in enumerate(A):\n while busy and busy[0][0] <= a: # these are done, put them back as available\n _, x = heapq.heappop(busy)\n heapq.heappush(available, i + (x-i)%k) # invariant: min(available) is at least i, at most i+k-1\n if available: \n j = heapq.heappop(available) % k\n heapq.heappush(busy, (a+B[i],j))\n res[j] += 1\n a = max(res)\n return [i for i in range(k) if res[i] == a]", "solution_js": "var busiestServers = function(k, arrival, load) {\n let loadMap = {};\n let pq = new MinPriorityQueue({ compare: (a,b) => a[1] - b[1] });\n let availableServers = new Set(new Array(k).fill(0).map((_, index) => index));\n\n for (let i = 0; i < arrival.length; i++) {\n // calc end time\n let end = arrival[i] + load[i];\n \n // bring server back\n while (pq.front()?.[1] <= arrival[i]) {\n const [server] = pq.dequeue();\n availableServers.add(server);\n }\n \n let server = i % k;\n // drop if no available server\n if (availableServers.size === 0) continue;\n \n // find the next avaiable sever\n while (!availableServers.has(server)) {\n server++;\n if (server === k + 1) {\n server = 0;\n }\n }\n \n // record the load\n if (!loadMap[server]) {\n loadMap[server] = 0;\n }\n \n loadMap[server]++;\n \n availableServers.delete(server);\n pq.enqueue([server, end]);\n }\n \n let res = [];\n let sorted = Object.entries(loadMap).sort((a,b) => b[1] - a[1]);\n let max = sorted[0][1];\n let i = 0;\n while (sorted[i]?.[1] === max) {\n res.push(+sorted[i++][0]);\n }\n \n return res;\n};", "solution_java": "class Solution {\n public List busiestServers(int k, int[] arrival, int[] load) {\n\n // use a tree to track available servers\n TreeSet availableServerIdxs = new TreeSet();\n for (int num = 0; num < k; num++) {\n availableServerIdxs.add(num);\n }\n // use a PQ to maintain the availability based on curTime + loadTime and the server index = idx%k\n Queue runningServers = new PriorityQueue<>((a, b)->(a[0] - b[0]));\n\n int[] serverHandledReqCount = new int[k];\n\n for (int idx = 0; idx < arrival.length; idx++) {\n int newTaskCompletionTime = arrival[idx];\n\n // peek if the server's work time is less than or equal to the next task completion time, if it is poll those servers from the running servers queue and add the index of that server to the availableServerIdxs treeSet\n while (!runningServers.isEmpty() && runningServers.peek()[0] <= newTaskCompletionTime) {\n int freedServer = runningServers.poll()[1];\n availableServerIdxs.add(freedServer);\n }\n\n if (availableServerIdxs.size() == 0) continue; // all busy\n\n // to always get the last freed server\n Integer serverIdx = availableServerIdxs.ceiling(idx % k);\n\n if (serverIdx == null) {\n serverIdx = availableServerIdxs.first();\n }\n\n serverHandledReqCount[serverIdx]++;\n availableServerIdxs.remove(serverIdx);\n\n runningServers.offer(new int[] {newTaskCompletionTime + load[idx], serverIdx});\n }\n\n int max = Arrays.stream(serverHandledReqCount).max().getAsInt();\n return IntStream.range(0, k).filter(i -> serverHandledReqCount[i] == max).boxed().collect(Collectors.toList());\n\n //return findMaxesInCounter(counter);\n }\n\n /*\n private List findMaxesInCounter(int[] counter) {\n int max = 0;\n for (int i = 0; i < counter.length; i++) {\n max = Math.max(max, counter[i]);\n }\n List result = new ArrayList<>();\n for (int i = 0; i < counter.length; i++) {\n if (counter[i] == max) {\n result.add(i);\n }\n }\n return result;\n }\n */\n}", "solution_c": "class Solution {\npublic:\n vector busiestServers(int k, vector& arrival, vector& load) {\n int n = (int)arrival.size();\n \n set freeServers;\n for (int i = 0; i < k; i++) freeServers.insert(i);\n \n vector serverTaskCount(k, 0);\n \n set> workingServers; // [end time, server index]\n for (int i = 0; i < n; i++) {\n int startTime = arrival[i];\n \n while (!workingServers.empty() && workingServers.begin()->first <= startTime) {\n auto s = *workingServers.begin();\n workingServers.erase(workingServers.begin());\n freeServers.insert(s.second);\n }\n \n if (freeServers.empty()) continue;\n \n int serverIndex = -1;\n auto it = freeServers.lower_bound(i % k);\n if (it == freeServers.end()) {\n serverIndex = *freeServers.begin();\n freeServers.erase(freeServers.begin());\n } else {\n serverIndex = *it;\n freeServers.erase(it);\n }\n \n workingServers.insert({startTime + load[i], serverIndex});\n \n serverTaskCount[serverIndex]++;\n //printf(\"Task %d (%d, %d) assigned to server %d\\n\", i, startTime, load[i], serverIndex);\n }\n // for (auto x : serverTaskCount) cout << x << \" \";\n // cout << endl;\n \n vector ret;\n int maxVal = *max_element(serverTaskCount.begin(), serverTaskCount.end());\n for (int i = 0; i < k; i++) \n if (maxVal == serverTaskCount[i]) ret.push_back(i);\n \n return ret;\n }\n};" }, { "title": "Array With Elements Not Equal to Average of Neighbors", "algo_input": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.\n\nMore formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].\n\nReturn any rearrangement of nums that meets the requirements.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n\n\nExample 2:\n\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\n\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n for i in range(1, len(nums) -1):\n pre = nums[i-1]\n current = nums[i]\n next = nums[i+1]\n \n # If block will run when we meet 1 2 3 or 6 4 2\n if (pre < current < next) or (pre > current > next):\n # Swap next and current\n # For example: \n # 1 2 3 -> 1 3 2\n # 6 4 2 -> 6 2 4\n nums[i+1], nums[i] = nums[i], nums[i+1]\n \n return nums", "solution_js": "var rearrangeArray = function(nums) {\n let arr=[], res=[]\n for(let q of nums) arr[q]= 1\n\n let l=0, r=arr.length-1\n while(l<=r){\n while(!arr[l])l++\n while(!arr[r])r--\n if(l<=r)res.push(l++)\n if(l<=r)res.push(r--)\n }\n return res\n};", "solution_java": "class Solution {\n public int[] rearrangeArray(int[] nums) {\n Arrays.sort(nums);\n // sort in wave format\n for(int i = 0;i nums[i+1]\n You are good to go.\n\n So, just sort the input and choose wisely to satisfy above condition.\n\n Example :\n [6,2,0,9,7]\n sort it : [0, 2, 6, 7, 9]\n\n result : [0, _, 2, _, 6] - 1st loop (fill alternaltely)\n result : [0, 7, 2, 9, 6] - 2nd loop (fill next larger numbers from nums to result in spaces left)\n\n*/\n\nclass Solution {\npublic:\n vector rearrangeArray(vector& nums) {\n int n = nums.size();\n sort(begin(nums), end(nums));\n\n vector result(n);\n int j = 0;\n int i = 0;\n for(; i < n && j < n; i++, j += 2) //alternately fill so that you leave one space in between for large number\n result[j] = nums[i];\n\n j = 1;\n for(; i < n && j < n; i++, j += 2) //filter the large number in spaces between that we left above\n result[j] = nums[i];\n\n return result;\n }\n};" }, { "title": "Maximum Consecutive Floors Without Special Floors", "algo_input": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.\n\nYou are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.\n\nReturn the maximum number of consecutive floors without a special floor.\n\n \nExample 1:\n\nInput: bottom = 2, top = 9, special = [4,6]\nOutput: 3\nExplanation: The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.\n\n\nExample 2:\n\nInput: bottom = 6, top = 8, special = [7,6,8]\nOutput: 0\nExplanation: Every floor rented is a special floor, so we return 0.\n\n\n \nConstraints:\n\n\n\t1 <= special.length <= 105\n\t1 <= bottom <= special[i] <= top <= 109\n\tAll the values of special are unique.\n\n", "solution_py": "class Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n special.sort()\n special.insert(0, bottom - 1)\n special.append(top + 1)\n \n ans = 0\n for i in range(len(special)-1):\n ans = max(ans, special[i+1] - special[i] - 1)\n return ans", "solution_js": "/**\n * @param {number} bottom\n * @param {number} top\n * @param {number[]} special\n * @return {number}\n */\nvar maxConsecutive = function(bottom, top, special) {\n special.push(top+1);\n special.push(bottom-1);\n special.sort((a, b) => a - b);\n let specialMax = 0;\n for (let i = 1; i < special.length; i++){\n specialMax = Math.max(specialMax, special[i] - special[i-1] - 1)\n }\n return specialMax;\n};", "solution_java": "class Solution {\n public int maxConsecutive(int bottom, int top, int[] special) {\n int max = Integer.MIN_VALUE;\n\n Arrays.sort(special);\n\n // from bottom to the first special floor\n max = Math.max(max, special[0] - bottom);\n\n // middle floors\n for(int i = 1; i < special.length; i++) {\n max = Math.max(max, special[i] - special[i - 1] - 1);\n }\n\n // from last special floor to the top\n max = Math.max(max, top - special[special.length - 1]);\n\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxConsecutive(int bottom, int top, vector& special) {\n\n int res(0), n(size(special));\n sort(begin(special), end(special));\n\n for (int i=1; i bool:\n l=len(word)\n if l==1:\n return True\n if word[0]==word[0].lower() and word[1]==word[1].upper():\n return False\n \n u=False\n if word[0]==word[0].upper():\n if word[1]==word[1].upper():\n u=True\n \n for i in word[2:]:\n if i==i.upper() and u==False:\n return False\n elif i==i.lower() and u==True:\n return False\n return True", "solution_js": "var detectCapitalUse = function(word) {\n if((word.charAt(0)==word.charAt(0).toUpperCase() && word.slice(1)==word.slice(1).toLowerCase()) || (word == word.toUpperCase() \n || word == word.toLowerCase()))\n {\n return true\n }\n else{\n return false\n }\n};", "solution_java": "class Solution {\n public boolean detectCapitalUse(String word) {\n int count = 0;\n for(int i=0; i < word.length(); i++){\n if('A' <= word.charAt(i) && word.charAt(i) <= 'Z')\n count++;\n }\n if(count == 0 || count == word.length() || (count == 1 && ('A' <= word.charAt(0) && word.charAt(0) <= 'Z')))\n return true;\n else\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool detectCapitalUse(string word) {\n int n = word.size();\n\n //if the first letter of the string is lower-case\n if(islower(word[0])){\n int c = 0;\n for(int i=0; i List[int]:\n psum, next, prev = [0] * (len(s) + 1), [inf] * (len(s) + 1), [0] * (len(s) + 1)\n res = []\n for i, ch in enumerate(s):\n psum[i + 1] = psum[i] + (ch == '|')\n prev[i + 1] = i if ch == '|' else prev[i]\n for i, ch in reversed(list(enumerate(s))):\n next[i] = i if ch == '|' else next[i + 1]\n for q in queries:\n l, r = next[q[0]], prev[q[1] + 1]\n res.append(r - l - (psum[r] - psum[l]) if l < r else 0)\n return res", "solution_js": "// time O(N + M) Space O(N) N = s.length M = query.length\nvar platesBetweenCandles = function(s, queries) {\n let platPreFixSum = [...Array(s.length + 1)];\n let leftViewCandle = [...Array(s.length + 1)];\n let rightViewCandle = [...Array(s.length + 1)];\n\n platPreFixSum[0] = 0;\n leftViewCandle[0] = -1;\n rightViewCandle[s.length] = -1;\n\n for(let i = 1; i <= s.length; i++){\n platPreFixSum[i] = s[i-1] == '*' ? platPreFixSum[i - 1] + 1 : platPreFixSum[i - 1];\n leftViewCandle[i] = s[i - 1] == '|' ? i - 1 : leftViewCandle[i - 1];\n rightViewCandle[s.length - i] = s[s.length - i] == '|' ? s.length - i : rightViewCandle[s.length - i + 1];\n }\n\n let result = [];\n\n queries.forEach(([left, right]) => {\n if(rightViewCandle[left] >= 0 && leftViewCandle[right + 1] >= 0 &&\n rightViewCandle[left] < leftViewCandle[right + 1]) {\n result.push(platPreFixSum[leftViewCandle[right + 1]] - platPreFixSum[rightViewCandle[left]]);\n } else {\n result.push(0);\n }\n });\n\n return result;\n\n};", "solution_java": "class Solution {\n // O(sLen + queries.length) time, O(sLen) space\n public int[] platesBetweenCandles(String s, int[][] queries) {\n int sLen = s.length();\n // cumulative number of plates from the left\n int[] numberOfPlates = new int[sLen+1];\n for (int i=0; i=0; i--) {\n if (s.charAt(i) == '|') {\n cand = i;\n }\n candleToTheRight[i] = cand;\n }\n // for each query - count the number of plates between closest candles\n int[] res = new int[queries.length];\n for (int i=0; i= right) {\n res[i] = 0;\n } else {\n res[i] = numberOfPlates[right+1] - numberOfPlates[left];\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector platesBetweenCandles(string s, vector>& queries) {\n vector candlesIndex;\n \n for(int i=0;i ans;\n for(auto q : queries){\n int firstCandleIndex = lower_bound(candlesIndex.begin() , candlesIndex.end() , q[0]) - candlesIndex.begin();\n int lastCandleIndex = upper_bound(candlesIndex.begin() , candlesIndex.end() , q[1]) - candlesIndex.begin() - 1;\n \n if(lastCandleIndex <= firstCandleIndex){\n ans.push_back(0);\n continue;\n }\n \n \n int tempAns = candlesIndex[lastCandleIndex] - candlesIndex[firstCandleIndex] - (lastCandleIndex - firstCandleIndex);\n \n ans.push_back(tempAns);\n }\n return ans;\n }\n};" }, { "title": "Replace Words", "algo_input": "In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"an\" is followed by the successor word \"other\", we can form a new word \"another\".\n\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.\n\nReturn the sentence after the replacement.\n\n \nExample 1:\n\nInput: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\n\n\nExample 2:\n\nInput: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput: \"a a b c\"\n\n\n \nConstraints:\n\n\n\t1 <= dictionary.length <= 1000\n\t1 <= dictionary[i].length <= 100\n\tdictionary[i] consists of only lower-case letters.\n\t1 <= sentence.length <= 106\n\tsentence consists of only lower-case letters and spaces.\n\tThe number of words in sentence is in the range [1, 1000]\n\tThe length of each word in sentence is in the range [1, 1000]\n\tEvery two consecutive words in sentence will be separated by exactly one space.\n\tsentence does not have leading or trailing spaces.\n\n", "solution_py": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};", "solution_js": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};", "solution_java": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};", "solution_c": "class Solution {\npublic:\n class trii{\n public:\n char data;\n trii* dict[26];\n bool isTerminal;\n \n trii(){\n \n }\n \n trii(char d){\n data=d;\n for(int i=0;i<26;i++){\n dict[i]=NULL;\n }\n isTerminal=false;\n }\n };\n \n class tree{\n public:\n trii* root;\n tree(){\n root=new trii('\\0');\n }\n \n void insert(string str,trii* node){\n if(str.size()==0){\n node->isTerminal=true;\n return;\n }\n int index=str[0]-'a';\n if(node->dict[index]==NULL ){\n node->dict[index]=new trii(str[0]);\n }\n insert(str.substr(1),node->dict[index]);\n }\n \n string find(string str,trii* node,string pre){\n if( node->isTerminal==true ){\n return pre; \n } \n int index=str[0]-'a';\n if(str.size()==0 || node->dict[index]==NULL){\n return \"\\0\";\n }\n return find(str.substr(1),node->dict[index],pre+str[0]);\n }\n \n string replaceWith(string word ,trii* node){\n string temp=find(word,node,\"\");\n if(temp!=\"\\0\"){\n word=temp;\n }\n return word;\n }\n };\n \n string replaceWords(vector& dictionary, string sentence) {\n tree* t=new tree();\n for(int i=0;iinsert(dictionary[i],t->root);\n }\n string ans=sentence;\n sentence=\"\";\n for(int i=0;ireplaceWith(word,t->root)+\" \";\n }\n sentence.pop_back();\n return sentence;\n }\n};" }, { "title": "Find the Town Judge", "algo_input": "In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.\n\nIf the town judge exists, then:\n\n\n\tThe town judge trusts nobody.\n\tEverybody (except for the town judge) trusts the town judge.\n\tThere is exactly one person that satisfies properties 1 and 2.\n\n\nYou are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi.\n\nReturn the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.\n\n \nExample 1:\n\nInput: n = 2, trust = [[1,2]]\nOutput: 2\n\n\nExample 2:\n\nInput: n = 3, trust = [[1,3],[2,3]]\nOutput: 3\n\n\nExample 3:\n\nInput: n = 3, trust = [[1,3],[2,3],[3,1]]\nOutput: -1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\t0 <= trust.length <= 104\n\ttrust[i].length == 2\n\tAll the pairs of trust are unique.\n\tai != bi\n\t1 <= ai, bi <= n\n\n", "solution_py": "class Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n possible = set([i for i in range(1,n+1)])\n in_edges = [0] * (n+1)\n \n for first, second in trust:\n possible.discard(first)\n in_edges[second] += 1\n \n if len(possible) != 1:\n return -1\n \n i = possible.pop()\n if in_edges[i] == n-1:\n return i\n return -1", "solution_js": "var findJudge = function(n, trust) {\n const length = trust.length;\n let possibleJudge = [], judgeMap = new Map(), value, judge = -1;\n for(let i = 0; i < length; i++) {\n if(judgeMap.has(trust[i][0])){\n value = judgeMap.get(trust[i][0]);\n value.push(trust[i][1]);\n judgeMap.set(trust[i][0], value);\n }\n else {\n judgeMap.set(trust[i][0], [trust[i][1]]);\n }\n }\n value = [];\n for(let i = 1; i <= n; i++) {\n if(!judgeMap.has(i)) {\n possibleJudge.push(i);\n }\n else {\n value.push([i,judgeMap.get(i)]);\n }\n }\n if(!value.length || value.length !== n-1) {\n if(possibleJudge.length === 1) return possibleJudge[0];\n return judge;\n }\n for(let i = 0; i < possibleJudge.length; i++) {\n judge = possibleJudge[i];\n for(let j = 0; j < value.length; j++) {\n if(value[j][1].indexOf(judge) < 0) {\n judge = -1;\n break;\n }\n }\n if(judge !== -1) break;\n }\n return judge;\n};", "solution_java": "class Solution {\n public int findJudge(int n, int[][] trust) {\n int count=0;\n int x[]=new int[n+1];\n int y[]=new int[n+1];\n Arrays.fill(x, 0);\n Arrays.fill(y, 0);\n for(int i=0;i>& trust) {\n vector> v(n+1,{0,0});\n \n for(auto i : trust){\n v[i[0]].first++;\n v[i[1]].second++;\n }\n \n int ans = -1;\n \n\n for(int i=1;i<=n;i++){\n auto p = v[i];\n if(p.first == 0 && p.second == n-1){\n ans = i;\n break;\n }\n }\n \n return ans;\n }\n};" }, { "title": "Shortest Common Supersequence", "algo_input": "Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.\n\nA string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.\n\n \nExample 1:\n\nInput: str1 = \"abac\", str2 = \"cab\"\nOutput: \"cabac\"\nExplanation: \nstr1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.\n\n\nExample 2:\n\nInput: str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput: \"aaaaaaaa\"\n\n\n \nConstraints:\n\n\n\t1 <= str1.length, str2.length <= 1000\n\tstr1 and str2 consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def shortestCommonSupersequence(self, A, B):\n n, m = len(A), len(B)\n dp = [B[:i] for i in range(m + 1)]\n for i in range(n):\n prev = A[:i]\n dp[0] = A[:i + 1]\n for j in range(m):\n if A[i] == B[j]:\n prev, dp[j + 1] = dp[j + 1], prev + A[i]\n else:\n prev, dp[j + 1] = dp[j + 1], min(dp[j] + B[j], dp[j + 1] + A[i], key = len)\n return dp[-1]", "solution_js": "var shortestCommonSupersequence = function(str1, str2) {\n const lcs = getLCS(str1, str2)\n \n let i = 0\n let j = 0\n\n let result = ''\n for (const c of lcs) {\n while(i < str1.length && str1[i] !== c) {\n result += str1[i]\n i++\n }\n while(j < str2.length && str2[j] !== c) {\n result += str2[j]\n j++\n }\n result += c\n i++\n j++\n }\n while(i < str1.length) {\n result += str1[i]\n i++\n }\n while(j < str2.length) {\n result += str2[j]\n j++\n }\n return result\n};\n\nfunction getLCS (a, b) {\n const t = new Array(a.length + 1).fill(0).map(() => new Array(b.length + 1).fill(0))\n \n for (let i = 1; i <= a.length; i++) {\n for (let j = 1; j <= b.length; j++) {\n if (a[i - 1] === b[j - 1]) {\n t[i][j] = 1 + t[i - 1][j - 1]\n } else {\n t[i][j] = Math.max(t[i - 1][j], t[i][j - 1])\n }\n }\n }\n \n let i = a.length\n let j = b.length\n let result = ''\n while(i > 0 && j > 0) {\n if (a[i-1] === b[j-1]) {\n result += a[i-1]\n i--\n j--\n } else {\n if (t[i-1][j] > t[i][j-1]) {\n i--\n } else {\n j--\n }\n }\n }\n return result.split('').reverse().join('')\n}", "solution_java": "class Solution {\n public String shortestCommonSupersequence(String str1, String str2) {\n int m=str1.length();\n int n=str2.length();\n int[][] dp=new int[m+1][n+1];\n for(int i=1;i0 && j>0){\n if(str1.charAt(i-1)==str2.charAt(j-1)){\n res=str1.charAt(i-1)+res;\n i--;\n j--;\n }else if(dp[i-1][j]>dp[i][j-1]){\n res=str1.charAt(i-1)+res;\n i--;\n }else{\n res=str2.charAt(j-1)+res;\n j--;\n }\n }\n while(i>0){\n res=str1.charAt(i-1)+res;\n i--;\n }\n while(j>0){\n res=str2.charAt(j-1)+res;\n j--;\n }\n return res;\n }\n}", "solution_c": "class Solution\n{\n string LCS(string str1, string str2, int m, int n)\n {\n int t[m+1][n+1];\n string ans = \"\";\n for(int i = 0;i < m+1; ++i)\n {\n for(int j = 0; j< n+1; ++j)\n {\n if(i == 0 || j == 0)\n t[i][j] = 0;\n }\n }\n\n for(int i = 1; i < m+1; ++i)\n {\n for(int j = 1; j < n+1; ++j)\n {\n if(str1[i-1] == str2[j-1])\n t[i][j] = 1 + t[i-1][j-1];\n else\n t[i][j] = max(t[i-1][j], t[i][j-1]);\n }\n }\n int i = m, j = n;\n while(i > 0 && j > 0)\n {\n if(str1[i-1] == str2[j-1])\n {\n ans.push_back(str1[i-1]);\n --i;\n --j;\n }\n\n else if(t[i][j-1] > t[i-1][j])\n {\n ans.push_back(str2[j-1]);\n --j;\n }\n\n else\n {\n ans.push_back(str1[i-1]);\n --i;\n }\n }\n while( i > 0)\n {\n ans.push_back(str1[i-1]);\n --i;\n }\n while( j > 0)\n {\n ans.push_back(str2[j-1]);\n --j;\n }\n reverse(ans.begin(),ans.end());\n return ans;\n }\n\npublic:\n string shortestCommonSupersequence(string str1, string str2) {\n\n int m = str1.length();\n int n = str2.length();\n\n return LCS(str1, str2, m ,n);\n }\n};" }, { "title": "Minimum Speed to Arrive on Time", "algo_input": "You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.\n\nEach train can only depart at an integer hour, so you may need to wait in between each train ride.\n\n\n\tFor example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.\n\n\nReturn the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.\n\nTests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.\n\n \nExample 1:\n\nInput: dist = [1,3,2], hour = 6\nOutput: 1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.\n\n\nExample 2:\n\nInput: dist = [1,3,2], hour = 2.7\nOutput: 3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.\n\n\nExample 3:\n\nInput: dist = [1,3,2], hour = 1.9\nOutput: -1\nExplanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n\n\n \nConstraints:\n\n\n\tn == dist.length\n\t1 <= n <= 105\n\t1 <= dist[i] <= 105\n\t1 <= hour <= 109\n\tThere will be at most two digits after the decimal point in hour.\n\n", "solution_py": "class Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n # the speed upper is either the longest train ride: max(dist),\n # or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).\n # notice: \"hour will have at most two digits after the decimal point\"\n upper = max(max(dist), ceil(dist[-1] / 0.01))\n #\n # the function to calcute total time consumed\n total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)\n # the case of impossible to arrive office on time\n if total(upper) > hour:\n return -1\n #\n # binary search: find the mimimal among \"all\" feasible answers\n left, right = 1, upper\n while left < right:\n mid = left + (right - left) // 2\n if total(mid) > hour:\n left = mid + 1 # should be larger\n else:\n right = mid # should explore a smaller one\n return right", "solution_js": "var minSpeedOnTime = function(dist, hour) {\n let left=1,right=10000000,speed,sum,ans=-1;\n while(left<=right){\n //We need to return the minimum positive integer speed (in kilometers per hour) that all the trains must travel. So speed will always be an integer ranging from 1 to 10000000 as per the question description.\n speed = left + Math.floor((right-left)/2);\n sum=0;\n for(let i=0;i& dist, const double hour, int speed)\n {\n double time = 0;\n for (int i = 0; i < dist.size() - 1; ++i)\n time += ((dist[i] + speed - 1) / speed);\n\n time += ((double)dist.back()) / speed;\n return time <= hour;\n }\n\npublic:\n int minSpeedOnTime(vector& dist, double hour)\n {\n int N = dist.size();\n if (hour <= (double)(N - 1))\n return -1;\n\n int lo = 1, hi = 1e7, mi;\n while (lo < hi)\n {\n mi = (lo + hi) / 2;\n if (canReachInTime(dist, hour, mi))\n hi = mi;\n else\n lo = mi + 1;\n }\n\n return hi;\n }\n};" }, { "title": "How Many Numbers Are Smaller Than the Current Number", "algo_input": "Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].\n\nReturn the answer in an array.\n\n \nExample 1:\n\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \nFor nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n\n\nExample 2:\n\nInput: nums = [6,5,4,8]\nOutput: [2,1,0,3]\n\n\nExample 3:\n\nInput: nums = [7,7,7,7]\nOutput: [0,0,0,0]\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 500\n\t0 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def smallerNumbersThanCurrent(self, nums):\n sortify = sorted(nums)\n return (bisect_left(sortify, i) for i in nums)", "solution_js": "var smallerNumbersThanCurrent = function(nums) {\n let count, ans=[];\n /*Run a loop on each element excluding nums[i]\n and compare it with nums[j] if it's large, then count++\n else break;*/\n \n for(let i=0; inums[j]) count++;\n }\n ans.push(count);\n }\n return ans;\n};\n\n//second way using objects:--->\n\nvar smallerNumbersThanCurrent = function(nums) {\n let arr=[...nums], ans=[];\n arr.sort((a,b)=>a-b);\n let map={};\n map[arr[0]]=0;\n for(let i=1; i=0 && sorted[idx-1] == nums[i]) {\n while (idx >= 0 && sorted[idx] == nums[i]) {\n --idx;\n }\n ++idx;\n }\n //As I said before, array of indices(indexes) will be the answer\n res[i] = idx;\n }\n return res;\n }\n //Just simple iterative binary search\n public static int binarySearch(int[] arr, int target) {\n int s = 0;\n int e = arr.length-1;\n int m = (s+e)/2;\n\n while (s<=e) {\n if (arr[m] == target) {\n return m;\n } else if (arr[m] > target) {\n e = m-1;\n } else {\n s = m+1;\n }\n m = (s+e)/2;\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n vector smallerNumbersThanCurrent(vector& nums) {\n vector ans;\n int i,j,size,count;\n size = nums.size();\n for(i = 0; i int:\n max_1 = 0\n max_2 = 0\n min_1 = 10001\n min_2 = 10001\n for i in nums:\n if i >= max_1:\n max_2,max_1 = max_1,i\n elif i > max_2:\n max_2 = i\n if i <= min_1:\n min_2,min_1 = min_1,i\n elif i < min_2:\n min_2 = i\n \n return max_1*max_2 - min_1*min_2", "solution_js": "var maxProductDifference = function(nums) {\n nums.sort((a,b) => a-b);\n return nums.slice(nums.length - 2).reduce((a,b) => a*b, 1) - nums.slice(0, 2).reduce((a,b) => a*b, 1);\n};", "solution_java": "class Solution {\n public int maxProductDifference(int[] nums) {\n int max1 = Integer.MIN_VALUE;\n int max2 = max1;\n\n int min1 = Integer.MAX_VALUE;\n int min2 = min1;\n for (int i = 0; i < nums.length; i++) {\n if (max1 < nums[i]) {\n max2 = max1;\n max1 = nums[i];\n } else if(nums[i] > max2)\n max2 = nums[i];\n\n if(min1 > nums[i]){\n min2 = min1;\n min1 = nums[i];\n }else if (nums[i] < min2)\n min2 = nums[i];\n }\n \n return (max1 * max2) - (min1 * min2);\n }\n}", "solution_c": "class Solution {\npublic:\n int maxProductDifference(vector& nums) {\n //we have to return the result of\n // (firstMax*secondMax) - (firstMin*secondMin)\n int max1=INT_MIN;\n int max2=INT_MIN;\n int min1=INT_MAX;\n int min2=INT_MAX;\n for(int i=0;imax1)\n {\n //assign the second max to max2\n max2=max1;\n max1=nums[i];\n }\n else if(nums[i]>max2)\n {\n //it can become second max\n max2= nums[i];\n }\n\n //check for the minimum\n if(nums[i] Optional[ListNode]:\n if not head or not head.next:\n return None\n slow = fast = entry = head\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n if slow == fast:\n while slow != entry:\n slow = slow.next\n entry = entry.next\n return entry\n return None", "solution_js": "var detectCycle = function(head) {\n let slowRunner = head\n let fastRunner = head\n\n while(fastRunner) {\n fastRunner = fastRunner.next?.next\n slowRunner = slowRunner.next\n\n if (fastRunner === slowRunner) {\n fastRunner = slowRunner\n slowRunner = head\n\n while (slowRunner !== fastRunner) {\n slowRunner = slowRunner.next\n fastRunner = fastRunner.next\n }\n\n return slowRunner\n }\n }\n\n return null\n};", "solution_java": "public class Solution {\n public ListNode detectCycle(ListNode head) {\n if (head == null) return null;\n ListNode tortoise = head;\n ListNode hare = new ListNode();\n hare.next = head.next;\n while (hare != null && hare.next != null && hare != tortoise) {\n tortoise = tortoise.next;\n hare = hare.next.next;\n }\n if (hare == null || hare.next == null) return null;\n tortoise = head;\n while (tortoise != hare) {\n tortoise = tortoise.next;\n hare = hare.next;\n }\n return hare;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode *detectCycle(ListNode *head) {\n map m;\n int index = 0;\n while (head)\n {\n if (m.find(head) == m.end())\n m[head] = index;\n else \n return (head);\n head = head->next;\n index++; \n }\n return (NULL);\n }\n};" }, { "title": "Minimum Moves to Reach Target Score", "algo_input": "You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.\n\nIn one move, you can either:\n\n\n\tIncrement the current integer by one (i.e., x = x + 1).\n\tDouble the current integer (i.e., x = 2 * x).\n\n\nYou can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.\n\nGiven the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.\n\n \nExample 1:\n\nInput: target = 5, maxDoubles = 0\nOutput: 4\nExplanation: Keep incrementing by 1 until you reach target.\n\n\nExample 2:\n\nInput: target = 19, maxDoubles = 2\nOutput: 7\nExplanation: Initially, x = 1\nIncrement 3 times so x = 4\nDouble once so x = 8\nIncrement once so x = 9\nDouble again so x = 18\nIncrement once so x = 19\n\n\nExample 3:\n\nInput: target = 10, maxDoubles = 4\nOutput: 4\nExplanation: Initially, x = 1\nIncrement once so x = 2\nDouble once so x = 4\nIncrement once so x = 5\nDouble again so x = 10\n\n\n \nConstraints:\n\n\n\t1 <= target <= 109\n\t0 <= maxDoubles <= 100\n\n", "solution_py": "class Solution:\n def minMoves(self, target: int, maxDoubles: int) -> int:\n c=0\n while(maxDoubles>0 and target>1):\n c += target%2\n target //= 2\n c += 1\n maxDoubles -=1\n return c + target-1", "solution_js": "var minMoves = function(target, maxDoubles) {\n if (maxDoubles === 0) return target - 1;\n let count = 0;\n\n while (target > 1) {\n if (target % 2 === 0 && maxDoubles > 0) {\n target /= 2;\n maxDoubles--;\n } else {\n target--;\n }\n\n count++;\n }\n\n return count;\n};", "solution_java": "class Solution {\n public int minMoves(int target, int maxDoubles) {\n int ans = 0;\n for(int i=0;i1 && maxDoubles>0){\n if(target%2==0){\n cnt++;\n maxDoubles--;\n target = target/2;\n }\n else{\n cnt++;\n target--;\n }\n }\n return cnt + (target-1);\n }\n};" }, { "title": "Minimum Number of Days to Eat N Oranges", "algo_input": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:\n\n\n\tEat one orange.\n\tIf the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.\n\tIf the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.\n\n\nYou can only choose one of the actions per day.\n\nGiven the integer n, return the minimum number of days to eat n oranges.\n\n \nExample 1:\n\nInput: n = 10\nOutput: 4\nExplanation: You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.\n\n\nExample 2:\n\nInput: n = 6\nOutput: 3\nExplanation: You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 109\n\n", "solution_py": "from collections import deque\nfrom math import log2, ceil\nclass Solution:\n def minDays(self, n: int) -> int:\n maxd = 2*ceil(log2(n))\n que = deque([(1,1)])\n seen = set()\n while que:\n v, d = que.popleft()\n seen.add(v)\n if v == n:\n return d\n for w in [v+1, 2*v, 3*v]:\n if w not in seen and d <= maxd and w <= n:\n que.append((w,d+1))", "solution_js": "var minDays = function(n) {\n const queue = [ [n,0] ];\n const visited = new Set();\n \n while (queue.length > 0) {\n const [ orangesLeft, days ] = queue.shift();\n \n if (visited.has(orangesLeft)) continue;\n if (orangesLeft === 0) return days;\n \n visited.add(orangesLeft);\n queue.push([orangesLeft - 1, days + 1]);\n \n if (orangesLeft % 2 === 0) {\n queue.push([orangesLeft - orangesLeft / 2, days + 1]);\n }\n \n if (orangesLeft % 3 === 0) {\n queue.push([orangesLeft - 2 * (orangesLeft / 3), days + 1])\n }\n }\n};", "solution_java": "class Solution {\n HashMapmap;\n public int minDays(int n) {\n map = new HashMap<>();\n map.put(0,0);\n map.put(1,1);\n return dp(n);\n }\n public int dp(int n){\n if(map.get(n)!=null)\n return map.get(n);\n int one = 1+(n%2)+dp(n/2);\n int two = 1+(n%3)+dp(n/3);\n map.put(n,Math.min(one,two));\n return map.get(n);\n}\n }\n // int one = 1+(n%2)+cache(n/2);\n // int two = 1+(n%3)+cache(n/3);", "solution_c": "class Solution {\npublic:\n // approach: BFS\n int minDays(int n) {\n int cnt=0;\n queueq;\n q.push(n);\n unordered_sets;\n s.insert(n);\n while(!q.empty()){\n int l=q.size();\n while(l--){\n int a=q.front();\n q.pop();\n if(a==0)\n break;\n if(s.find(a-1)==s.end()){ \n q.push(a-1);\n s.insert(a-1);\n } \n if(!(a&1) && s.find(a>>1)==s.end()){ // if divisible by 2 and a/2 not present in set\n q.push(a>>1);\n s.insert(a>>1);\n }\n if(a%3==0 && s.find(a/3)==s.end()){ // if divisible by 3 and a/3 not present in set\n q.push(a/3);\n s.insert(a/3);\n }\n }\n cnt++;\n if(s.find(0)!=s.end())\n break;\n }\n return cnt;\n }\n};" }, { "title": "Largest Number After Digit Swaps by Parity", "algo_input": "You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).\n\nReturn the largest possible value of num after any number of swaps.\n\n \nExample 1:\n\nInput: num = 1234\nOutput: 3412\nExplanation: Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.\n\n\nExample 2:\n\nInput: num = 65875\nOutput: 87655\nExplanation: Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.\n\n\n \nConstraints:\n\n\n\t1 <= num <= 109\n\n", "solution_py": "class Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res", "solution_js": "/**\n * @param {number} num\n * @return {number}\n */\nvar largestInteger = function(num) {\n var nums = num.toString().split(\"\");//splitting the numbers into an array\n var odd=[];//helps keep a track of odd numbers\n var even =[];//helps keep a track of even numbers\n for(var i=0;ia-b);//sorting the arrays in ascending order\n even.sort((a,b)=>a-b);\n var ans =[];\n for(var i=0;i opq = new PriorityQueue<>();\n PriorityQueue epq = new PriorityQueue<>();\n int bnum = num;\n while(num>0){\n int cur = num%10;\n if(cur%2==1){\n opq.add(cur);\n }else{\n epq.add(cur);\n }\n num /= 10;\n }\n StringBuilder sb = new StringBuilder();\n num = bnum;\n while(num>0){\n int cur = num%10;\n if(cur%2==1)\n sb.insert(0, opq.poll());\n else\n sb.insert(0, epq.poll());\n num /= 10;\n }\n return Integer.parseInt(sb.toString());\n }\n}", "solution_c": "class Solution {\npublic:\n int largestInteger(int num) {\n priority_queue p; // priority queue to store odd digits in descending order\n priority_queue q; // priority queue to store even digits in descending order\n string nums=to_string(num); // converting num to a string for easy access of the digits\n int n=nums.size(); // n stores the number of digits in num\n\n for(int i=0;i List[List[int]]:\n # create a r, c matrix given the rows & cols\n # each element represents a list [r, c] where r is the row & c the col\n # find find the distances of all cells from the center (append to res)\n # sort the result by distance function\n # Time O(M + N) Space O(M + N)\n \n \n def distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n \n matrix = [[i, j] for i in range(rows) for j in range(cols)]\n center = [rCenter, cCenter]\n matrix.sort(key=lambda c: distance(c, center))\n \n return matrix", "solution_js": "var allCellsDistOrder = function(rows, cols, rCenter, cCenter) {\n let distances = []\n let result = []\n\n //create a new \"visited\" cells matrix\n let visited = new Array(rows).fill([])\n for(i=0;i {\n if(row >= rows || col >= cols) return\n if(visited[row][col]) return // don't compute distance again if cell already visited\n visited[row][col] = 1\n\n let distance = Math.abs(rCenter - row) + Math.abs(cCenter - col)\n if(distances[distance]){\n distances[distance].add([row,col])\n }else{\n distances[distance] = new Set()\n distances[distance].add([row,col])\n }\n\n computeDistances(row + 1, col, rCenter, cCenter)\n computeDistances(row, col + 1, rCenter, cCenter)\n }\n\n computeDistances(0, 0, rCenter, cCenter)\n\n distances.forEach(distance => {\n result.push(...distance)\n })\n\n return result\n};", "solution_java": "//--------------------Method 1----------------------\n\nclass Solution {\n public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n int [][]res=new int[rows*cols][2];\n\n int idx=0;\n\n for(int i=0;i{\n int d1=Math.abs(a[0]-rCenter)+Math.abs(a[1]-cCenter);\n int d2=Math.abs(b[0]-rCenter)+Math.abs(b[1]-cCenter);\n\n return d1-d2;\n });\n\n return res;\n }\n}\n\n//--------------------Method 2--------------------\n\n// class Solution {\n// public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n\n// boolean [][]vis=new boolean[rows][cols];\n// int [][]ans=new int[rows*cols][2];\n\n// Queue q=new LinkedList<>();\n// q.add(new Pair(rCenter,cCenter));\n// int idx=0;\n// vis[rCenter][cCenter]=true;\n// int [][]dir={{0,1},{1,0},{-1,0},{0,-1}};\n\n// while(!q.isEmpty()){\n// Pair curr=q.remove();\n// ans[idx][0]=curr.r;\n// ans[idx][1]=curr.c;\n// idx++;\n\n// for(int []d:dir){\n// int nr=curr.r+d[0];\n// int nc=curr.c+d[1];\n\n// if(nr>=0 && nr=0 && nc> allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {\n vector> ans;\n multimap> mp;\n for(int i = 0;i>(abs(i-rCenter)+abs(j-cCenter),{i,j})); //map will sort the value based on key(distance) \n }\n }\n for(auto itr = mp.begin();itr != mp.end();itr++){\n ans.push_back(itr->second);\n }\n return ans;\n }\n};" }, { "title": "Stamping The Sequence", "algo_input": "You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.\n\nIn one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.\n\n\n\tFor example, if stamp = \"abc\" and target = \"abcba\", then s is \"?????\" initially. In one turn you can:\n\n\t\n\t\tplace stamp at index 0 of s to obtain \"abc??\",\n\t\tplace stamp at index 1 of s to obtain \"?abc?\", or\n\t\tplace stamp at index 2 of s to obtain \"??abc\".\n\t\n\tNote that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).\n\n\nWe want to convert s to target using at most 10 * target.length turns.\n\nReturn an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.\n\n \nExample 1:\n\nInput: stamp = \"abc\", target = \"ababc\"\nOutput: [0,2]\nExplanation: Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.\n\n\nExample 2:\n\nInput: stamp = \"abca\", target = \"aabcaca\"\nOutput: [3,0,1]\nExplanation: Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".\n\n\n \nConstraints:\n\n\n\t1 <= stamp.length <= target.length <= 1000\n\tstamp and target consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def movesToStamp(self, S: str, T: str) -> List[int]:\n if S == T: return [0]\n S, T = list(S), list(T)\n slen, tlen = len(S), len(T) - len(S) + 1\n ans, tdiff, sdiff = [], True, True\n while tdiff:\n tdiff = False\n for i in range(tlen):\n sdiff = False\n for j in range(slen):\n if T[i+j] == \"*\": continue\n if T[i+j] != S[j]: break\n sdiff = True\n else: \n if sdiff:\n tdiff = True\n for j in range(i, i + slen): T[j] = \"*\"\n ans.append(i)\n for i in range(len(T)):\n if T[i] != \"*\": return []\n return reversed(ans)", "solution_js": "var movesToStamp = function(stamp, target) {\n var s = target.replace(/[a-z]/g,\"?\")\n var repl = s.substr(0,stamp.length)\n let op = []\n let s1 = target\n\n while(s1 !== s){\n let idx = getIndex()\n if(idx === -1) return []\n op.push(idx)\n }\n return op.reverse()\n \n function getIndex(){\n for(let i=0; i abcdefgh, window = def, \n * next state -> abc???gh \n *\n */\n \n int sLen = stamp.length();\n int tLen = target.length();\n \n //it save the index of reversed charcacter\n Queue reversedCharIndices= new LinkedList();\n \n //it mark Character of target, as reversed\n boolean[] isReversedCharOfThisIndex = new boolean[tLen];\n \n Stack stack = new Stack();\n \n List widowList = new ArrayList();\n \n for(int windowStartIndex = 0; windowStartIndex <= tLen - sLen; windowStartIndex++){\n \n Set matched = new HashSet();\n Set notMatched = new HashSet();\n \n for(int j = 0; j < sLen; j++){\n \n //char index of current window of the target\n int charIndex = windowStartIndex + j;\n \n if(stamp.charAt(j) == target.charAt(charIndex)){\n matched.add(charIndex);\n } else {\n notMatched.add(charIndex);\n }\n }\n \n //add the window\n widowList.add(new Window(matched, notMatched));\n \n //when all char of current window is matched with \n if(notMatched.isEmpty()){\n stack.push(windowStartIndex);\n \n for(int index : matched){\n if(!isReversedCharOfThisIndex[index]){\n \n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n \n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n \n }\n }\n \n \n \n //get all char index, one by once\n //see the impact of reverse char of this index, in ano\n while(!reversedCharIndices.isEmpty()){\n int reversedCharIndex = reversedCharIndices.remove();\n \n int start = Math.max(0, reversedCharIndex - sLen + 1);\n int end = Math.min(reversedCharIndex, tLen - sLen);\n \n for(int windowIndex = start; windowIndex <= end; windowIndex++){\n \n if(widowList.get(windowIndex).notMatched.contains(reversedCharIndex)){\n \n \n //as this char is reversed in another window\n //remove this char index from current window, \n widowList.get(windowIndex).notMatched.remove(reversedCharIndex);\n \n if(widowList.get(windowIndex).notMatched.isEmpty()){\n \n //as all of charcater reversed of current window\n //now add current window index\n stack.push(windowIndex);\n \n for(int index : widowList.get(windowIndex).matched){\n \n if(!isReversedCharOfThisIndex[index]){\n\n //add in queue, so that we can process,\n //another window which is affected by its character get reversed\n reversedCharIndices.add(index);\n\n //mark it reversed\n isReversedCharOfThisIndex[index] = true;\n }\n }\n }\n }\n \n }\n }\n \n \n for(boolean reversed : isReversedCharOfThisIndex){\n if(!reversed){\n return new int[0];\n }\n }\n \n int i = 0;\n int[] result = new int[stack.size()];\n while(!stack.empty()){\n result[i++] = stack.pop();\n }\n \n \n return result;\n \n }\n}\n\nclass Window {\n Set matched;\n Set notMatched;\n \n public Window(Set matched, Set notMatched){\n this.matched = matched;\n this.notMatched = notMatched;\n }\n}", "solution_c": "class Solution {\npublic:\n vector movesToStamp(string stamp, string target) {\n auto isUndone = [](auto it, auto endIt) {\n return all_of(it, endIt, [](char c) { return c == '?'; });\n };\n vector res;\n\n while (!isUndone(begin(target), end(target))) {\n auto prevResSize = size(res);\n\n for (size_t i = 0; i < size(target) - size(stamp) + 1; ++i) {\n auto it = begin(target) + i, endIt = it + size(stamp);\n if (isUndone(it, endIt))\n continue;\n\n size_t j = 0;\n for (; j < size(stamp) && (*(it + j) == stamp[j] || *(it + j) == '?'); ++j);\n\n if (j == size(stamp)) {\n fill(it, endIt, '?');\n res.push_back(i);\n }\n }\n if (prevResSize == size(res))\n return {};\n }\n\n reverse(begin(res), end(res));\n return res;\n }\n};" }, { "title": "Number of Ways Where Square of Number Is Equal to Product of Two Numbers", "algo_input": "Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:\n\n\n\tType 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.\n\tType 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.\n\n\n \nExample 1:\n\nInput: nums1 = [7,4], nums2 = [5,2,8,9]\nOutput: 1\nExplanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). \n\n\nExample 2:\n\nInput: nums1 = [1,1], nums2 = [1,1,1]\nOutput: 9\nExplanation: All Triplets are valid, because 12 = 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\n\n\nExample 3:\n\nInput: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput: 2\nExplanation: There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 1000\n\t1 <= nums1[i], nums2[i] <= 105\n\n", "solution_py": "class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n = len(nums1), len(nums2)\n for i in range(m):\n sqr1[nums1[i]**2] += 1\n for j in range(n):\n sqr2[nums2[j]**2] += 1\n\n res = 0\n for i in range(m-1):\n for j in range(i+1, m):\n if nums1[i]*nums1[j] in sqr2:\n res += sqr2[nums1[i]*nums1[j]]\n\n for i in range(n-1):\n for j in range(i+1, n):\n if nums2[i]*nums2[j] in sqr1:\n res += sqr1[nums2[i]*nums2[j]]\n return res", "solution_js": "var numTriplets = function(nums1, nums2) {\n const nm1 = new Map(), nm2 = new Map();\n const n = nums1.length, m = nums2.length;\n for(let i = 0; i < n; i++) {\n for(let j = i + 1; j < n; j++) {\n const product = nums1[i] * nums1[j];\n if(!nm1.has(product)) nm1.set(product, 0);\n const arr = nm1.get(product);\n nm1.set(product, arr + 1);\n }\n }\n for(let i = 0; i < m; i++) {\n for(let j = i + 1; j < m; j++) {\n const product = nums2[i] * nums2[j];\n if(!nm2.has(product)) nm2.set(product, 0);\n const arr = nm2.get(product);\n nm2.set(product, arr + 1);\n }\n }\n let ans = 0;\n\n for(let num of nums1) {\n const sq = num * num;\n if(nm2.has(sq)) {\n ans += nm2.get(sq);\n }\n }\n for(let num of nums2) {\n const sq = num * num;\n if(nm1.has(sq)) {\n ans += nm1.get(sq);\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int numTriplets(int[] nums1, int[] nums2) {\n Arrays.sort(nums1);\n Arrays.sort(nums2);\n return count(nums1 , nums2) + count(nums2 , nums1);\n }\n\n public int count(int a[] , int b[]){\n int n = a.length;\n int m = b.length;\n int count = 0;\n for(int i=0;ix)\n k--;\n else if(b[j] != b[k]){\n int jNew = j;\n int kNew = k;\n\n while(b[j] == b[jNew])\n jNew++;\n while(b[k] == b[kNew])\n kNew--;\n count += (jNew-j)*(k-kNew);\n j = jNew;\n k = kNew;\n }\n else{\n int q = k-j+1;\n count += (q)*(q-1)/2;\n break;\n }\n }\n }\n return count;\n }\n\n}", "solution_c": "class Solution {\npublic:\n int numTriplets(vector& nums1, vector& nums2) {\n\n unordered_map m1, m2;\n for(int i : nums1) m1[(long long)i*i]++;\n for(int i : nums2) m2[(long long)i*i]++;\n\n int ans = 0;\n\n for(int i=0; i int:\n start=[1]\n end=[n]\n for i in range(2,math.ceil(math.sqrt(n))+1):\n if n%i==0:\n start.append(i)\n if i!=n//i:\n end.append(n//i)\n start=sorted(set(start).union(set(end)))\n if k<=len(start):\n return start[k-1]\n else:\n return -1", "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar kthFactor = function(n, k) {\n const res = [1]\n for(let i=2; i list = new ArrayList<>();\n\n for (int i = 1; i <= n; i++) {\n\n if (n % i == 0){\n list.add(i);\n }\n }\n if (list.size() < k){\n return -1;\n }\n \n return list.get(k-1);\n }\n}", "solution_c": "class Solution {\npublic:\n int kthFactor(int n, int k) {\n vector sol;\n sol.push_back(1);\n for(int i = 2; i <= n / 2; i++) {\n if(n % i == 0) sol.push_back(i);\n }\n if(n != 1) sol.push_back(n);\n if(k > sol.size()) return -1;\n return sol[k - 1];\n }\n};" }, { "title": "Reaching Points", "algo_input": "Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.\n\nThe allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).\n\n \nExample 1:\n\nInput: sx = 1, sy = 1, tx = 3, ty = 5\nOutput: true\nExplanation:\nOne series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)\n\n\nExample 2:\n\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: false\n\n\nExample 3:\n\nInput: sx = 1, sy = 1, tx = 1, ty = 1\nOutput: true\n\n\n \nConstraints:\n\n\n\t1 <= sx, sy, tx, ty <= 109\n\n", "solution_py": "from collections import defaultdict\n\nclass Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n def nextNum(ta,tb,s):\n if ta % tb == s % tb:\n return min(ta, s)\n return ta % tb\n visited = defaultdict(bool)\n while tx >= sx and ty >= sy and (sx != tx or sy != ty):\n if tx > ty:\n tx, ty = nextNum(tx, ty, sx), ty\n else:\n tx, ty = tx, nextNum(ty, tx, sy)\n if visited[(tx,ty)]:\n break\n visited[(tx,ty)] = True\n return (sx == tx) and (sy == ty)", "solution_js": "/**\n * @param {number} sx\n * @param {number} sy\n * @param {number} tx\n * @param {number} ty\n * @return {boolean}\n */\nvar reachingPoints = function(sx, sy, tx, ty) {\n while (tx >= sx && ty >= sy) {\n if (tx == ty) break;\n \n if (tx > ty) {\n if (ty > sy) tx %= ty;\n else return (tx - sx) % ty == 0;\n } else {\n if (tx > sx) ty %= tx;\n else return (ty - sy) % tx == 0;\n }\n }\n \n return (tx == sx && ty == sy);\n};", "solution_java": "class Solution {\n public boolean reachingPoints(int sx, int sy, int tx, int ty) {\n if (sx==tx && sy==ty){\n return true;\n }\n if (tx < sx || ty < sy){\n return false;\n }\n return txb) then at the previous step coordinate must be (a-b,b)\nas it can't be (a,b-a) because all the coordinates are positive and for a>b... b-a<0\nthis continues till the point when a becomes <=b\nwe can run a loop till there but its time taking\nwe can observe that the above phenomeon occurs till it becomes (a%b,b)\nexample :\nfor (50,7) it would have been like this:\n(50,7)...(43,7)...(36,7)...........(8,7)..(1,7)\n1 = 50%7\nBy repeating this procedure, after the loop, we have to test if sx == tx or sy == ty. There is still a condition to test.\nLet see we got sy = ty = 5 and have the following result\nsx,sy = (16,5)\ntx,ty = (21,5)\nnow if we run our program then it will stop at (1,5) which is not equal to sx,sy and will return false\nhowever during our iteration we will encounter (16,5) infact after the first iteration only but according to our current code it won't detect it\nso at the end we apply another condition:\ncheck if (tx - sx) % ty == 0. In our case, (21 - 16) mod 5 = 0 so we can return true.\n*/\n\n\nclass Solution \n{\npublic:\n // METHOD - 1\n bool reachingPoints_recursive(int sx, int sy, int tx, int ty) \n {\n if (sx > tx || sy > ty)\n {\n return false;\n }\n \n if (sx == tx && sy == ty)\n {\n return true;\n }\n \n \n bool canReach = reachingPoints_recursive(sx, sx+sy, tx, ty);\n if (!canReach)\n {\n canReach = reachingPoints_recursive(sx+sy, sy, tx, ty);\n }\n \n return canReach;\n }\n \n \n // METHOD - 2\n bool reachingPoints_internal(int sx, int sy, int tx, int ty)\n {\n if (sx > tx || sy > ty)\n {\n return false;\n }\n else if (sx == tx && sy == ty)\n {\n return true;\n }\n \n while (tx > sx && ty > sy)\n {\n if (tx > ty)\n {\n // implies previous path to this tx, ty should have to be tx-ty, ty \n // and this could continue till either tx < ty i.e difference would be tx % ty\n // so instead of doing that repeatedly just go the final point where \n // tx would have started before started adding ty to it repeatedly \n tx = tx % ty;\n }\n else\n {\n // implies previous path to this tx, ty should have to be (tx, ty-tx)\n // and this could continue till either tx > ty i.e difference would be tx % ty\n // so instead of doing that repeatedly just go the final point where \n // ty would have started before started adding tx to it repeatedly\n ty = ty % tx;\n }\n }\n \n if ((tx == sx) && ((ty - sy) % sx == 0) )\n {\n return true;\n }\n else if ((ty == sy) && ((tx - sx) % sy == 0))\n {\n return true;\n }\n \n return false;\n }\n \n \n bool reachingPoints(int sx, int sy, int tx, int ty)\n {\n // Method-1 : recurssion - will not work for larger numbers as stack will use up all the memory\n\t\t// return reachingPoints_recursive(sx, sy, tx, ty);\n \n\t\t// Method-2 : Effecient non recursive solution\n return reachingPoints_internal(sx, sy, tx, ty);\n }\n};" }, { "title": "Swapping Nodes in a Linked List", "algo_input": "You are given the head of a linked list, and an integer k.\n\nReturn the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\n\n\nExample 2:\n\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 <= k <= n <= 105\n\t0 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n tot = 0 # initialise total\n Head = head\n while Head: # count total nodes\n Head = Head.next # move forward\n tot += 1 # incerse count by one for each node\n one, two = None, None # two pointers of one and two\n count = 1 # we're initialising to one because we have one based index for swapping\n Head = head # regain original head to traverse\n while Head:\n if one and two: break # if we have both one and two then break loop to save time\n if count == k: # if from forward we reach at node k then it's our first node\n one = Head\n if count == (tot-k+1): # if from backward we reach to node k then save it\n two = Head\n Head = Head.next # move further\n count += 1 # increse count\n one.val, two.val = two.val, one.val # now swap values\n return head # return head", "solution_js": "var swapNodes = function(head, k) {\n let A = head, B = head, K, temp\n for (let i = 1; i < k; i++) A = A.next\n K = A, A = A.next\n while (A) A = A.next, B = B.next\n temp = K.val, K.val = B.val, B.val = temp\n return head\n};", "solution_java": "class Solution {\n public ListNode swapNodes(ListNode head, int k) {\n ListNode fast = head;\n ListNode slow = head;\n ListNode first = head, second = head;\n\n // Put fast (k-1) nodes after slow\n for(int i = 0; i < k - 1; ++i)\n fast = fast.next;\n\n // Save the node for swapping\n first = fast;\n\n // Move until the end of the list\n while(fast.next != null) {\n slow = slow.next;\n fast = fast.next;\n }\n\n // Save the second node for swapping\n // Note that the pointer second isn't necessary: we could use slow for swapping as well\n // However, having second improves readability\n second = slow;\n\n // Swap values\n int temp = first.val;\n first.val = second.val;\n second.val = temp;\n\n return head;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* swapNodes(ListNode* head, int k) {\n \n // declare a dummy node\n \n ListNode* dummy = new ListNode(0);\n \n // point dummy -> next to head\n \n dummy -> next = head;\n \n // declare a tail pointer and point to dummy\n \n ListNode* tail = dummy;\n \n // move the curr pointer (k - 1) times\n \n // this will maintain a gap of (k - 1) between curr and tail pointer\n \n ListNode* curr = head;\n \n while(k > 1)\n {\n curr = curr -> next;\n \n k--;\n }\n \n // store the address in start pointer\n \n ListNode* start = curr;\n \n // maintaing a gap of (k - 1) between curr and tail, move both pointer\n \n while(curr)\n {\n tail = tail -> next;\n \n curr = curr -> next;\n }\n \n // store the address of kth node from end\n \n ListNode* end = tail;\n \n // swap the values\n \n swap(start -> val, end -> val);\n \n // dummy -> next will be head\n \n return dummy -> next;\n }\n};" }, { "title": "Min Max Game", "algo_input": "You are given a 0-indexed integer array nums whose length is a power of 2.\n\nApply the following algorithm on nums:\n\n\n\tLet n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.\n\tFor every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).\n\tFor every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).\n\tReplace the array nums with newNums.\n\tRepeat the entire process starting from step 1.\n\n\nReturn the last number that remains in nums after applying the algorithm.\n\n \nExample 1:\n\nInput: nums = [1,3,5,2,4,8,2,2]\nOutput: 1\nExplanation: The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.\n\n\nExample 2:\n\nInput: nums = [3]\nOutput: 3\nExplanation: 3 is already the last remaining number, so we return 3.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1024\n\t1 <= nums[i] <= 109\n\tnums.length is a power of 2.\n\n", "solution_py": "class Solution:\n def minMaxGame(self, a: List[int]) -> int:\n \n def solve(n):\n if n==1:\n return\n for i in range(n//2):\n if i%2:\n a[i] = max (a[2*i], a[2*i+1])\n else:\n a[i] = min (a[2*i], a[2*i+1])\n solve(n//2)\n return\n solve(len(a))\n return a[0]", "solution_js": "var minMaxGame = function(nums) {\n while (nums.length > 1) {\n let half = nums.length / 2;\n for (let i = 0; i < half; i++)\n nums[i] = i % 2 === 0 ? Math.min(nums[2 * i], nums[2 * i + 1]) : Math.max(nums[2 * i], nums[2 * i + 1]);\n\n nums.length = half;\n }\n\n return nums[0];\n};", "solution_java": "class Solution {\n public int minMaxGame(int[] nums) {\n var isMin = true;\n var n=1;\n \n while(n& nums) {\n int n = nums.size(); \n if(n==1) return nums[0]; // Base case\n vector newNum(n/2); \n for(int i=0; i int:\n # pairs = list(combinations(nums, 2))\n \n maxHeap = []\n heapify(maxHeap)\n \n for idx, val1 in enumerate(nums):\n for val2 in nums[idx + 1:]:\n pair = [val1, val2]\n heappush(maxHeap, [-1*abs(pair[0] - pair[1]), pair])\n if len(maxHeap) > k:\n heappop(maxHeap)\n \n return -1*maxHeap[0][0]", "solution_js": "var smallestDistancePair = function(nums, k) { \n nums.sort((a,b) => a - b); \n let left = 0, right = nums[nums.length-1] - nums[0], mid = null, total = 0; \n \n while (left < right) {\n mid = left + Math.floor((right - left) / 2);\n \n total = 0;\n for (var i = 0, j = 1; i < nums.length - 1 && total <= k; i++) {\n for ( ; j < nums.length && nums[j] - nums[i] <= mid; j++) {}\n\t\t\ttotal += j - i - 1; \n }\n \n if (total >= k) {right = mid;} \n\t\telse {left = mid+1;}\n } \n\t\n return left;\n};", "solution_java": "class Solution {\n public int smallestDistancePair(int[] nums, int k) {\n Arrays.sort(nums);\n int low = 0, high = nums[nums.length-1] - nums[0];\n \n while(low<=high){\n int mid = low + (high-low)/2;\n if(noOfDistancesLessThan(mid,nums) >= k) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private int noOfDistancesLessThan(int dist,int[] nums){\n int count = 0,i = 0, j = 0;\n while(i &temp,int mid){\n int i=0,j=0,n=temp.size();\n int len=0;\n\n while(i& nums, int k) {\n int s=0,e=1e6;\n int ans=0;\n vector temp=nums;\n sort(temp.begin(),temp.end());\n while(s<=e){\n int mid=s+(e-s)/2;\n\n if(count(temp,mid)>=k){\n ans=mid;\n e=mid-1;\n }else {\n s=mid+1;\n }\n }\n return ans;\n }\n};" }, { "title": "Design Bitset", "algo_input": "A Bitset is a data structure that compactly stores bits.\n\nImplement the Bitset class:\n\n\n\tBitset(int size) Initializes the Bitset with size bits, all of which are 0.\n\tvoid fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs.\n\tvoid unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs.\n\tvoid flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.\n\tboolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.\n\tboolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.\n\tint count() Returns the total number of bits in the Bitset which have value 1.\n\tString toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.\n\n\n \nExample 1:\n\nInput\n[\"Bitset\", \"fix\", \"fix\", \"flip\", \"all\", \"unfix\", \"flip\", \"one\", \"unfix\", \"count\", \"toString\"]\n[[5], [3], [1], [], [], [0], [], [], [0], [], []]\nOutput\n[null, null, null, null, false, null, null, true, null, 2, \"01010\"]\n\nExplanation\nBitset bs = new Bitset(5); // bitset = \"00000\".\nbs.fix(3); // the value at idx = 3 is updated to 1, so bitset = \"00010\".\nbs.fix(1); // the value at idx = 1 is updated to 1, so bitset = \"01010\". \nbs.flip(); // the value of each bit is flipped, so bitset = \"10101\". \nbs.all(); // return False, as not all values of the bitset are 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"00101\".\nbs.flip(); // the value of each bit is flipped, so bitset = \"11010\". \nbs.one(); // return True, as there is at least 1 index with value 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = \"01010\".\nbs.count(); // return 2, as there are 2 bits with value 1.\nbs.toString(); // return \"01010\", which is the composition of bitset.\n\n\n \nConstraints:\n\n\n\t1 <= size <= 105\n\t0 <= idx <= size - 1\n\tAt most 105 calls will be made in total to fix, unfix, flip, all, one, count, and toString.\n\tAt least one call will be made to all, one, count, or toString.\n\tAt most 5 calls will be made to toString.\n\n", "solution_py": "class Bitset(object):\n\n def __init__(self, size):\n self.a = 0\n self.size = size\n self.cnt = 0\n\n def fix(self, idx):\n if self.a & (1 << idx) == 0:\n self.a |= 1 << idx\n self.cnt += 1\n\n def unfix(self, idx):\n if self.a & (1 << idx):\n self.a ^= 1 << idx\n self.cnt -= 1\n\n def flip(self):\n self.a ^= (1 << self.size) - 1\n self.cnt = self.size - self.cnt\n\n def all(self):\n return self.cnt == self.size\n\n def one(self):\n return self.a > 0\n\n def count(self):\n return self.cnt\n\n def toString(self):\n a = bin(self.a)[2:]\n return a[::-1] + '0' * (self.size - len(a))", "solution_js": "var Bitset = function(size) {\n //this.bits = new Array(size).fill(0);\n //this.bitsOp = new Array(size).fill(1);\n this.set0 = new Set();\n this.set1 = new Set();\n for (let i = 0; i(x)?0:1); \n //this.bits.forEach(x=>x=(x)?0:1); \n [this.set0, this.set1] = [this.set1, this.set0];\n};\n\n/**\n * @return {boolean}\n */\nBitset.prototype.all = function() {\n //return (this.bits.filter(x=>x).length == this.bits.length) \n //return !this.bits.includes(0);\n //for (let i = 0; ix).length>0 \n //return this.bits.includes(1);\n //for (let i = 0; i0;\n};\n\n/**\n * @return {number}\n */\nBitset.prototype.count = function() {\n //return this.bits.filter(x=>x).length \n //return this.bits.reduce((sum, cur)=>sum+cur);\n return this.set1.size;\n};\n\n/**\n * @return {string}\n */\nBitset.prototype.toString = function() {\n //return this.bits.join('');\n let set = new Array(this.set0.size+this.set1.size);\n for (let i=0; i one = new HashSet<>();\n Set zero = new HashSet<>();\n public Bitset(int size) {\n this.size = size;\n for(int i=0;i s = one;\n one = zero;\n zero = s;\n }\n \n public boolean all() {\n return one.size() == size;\n }\n \n public boolean one() {\n return one.size()>=1;\n }\n \n public int count() {\n return one.size();\n }\n \n public String toString() {\n StringBuilder sb= new StringBuilder();\n for(int i=0;iarr;\n int cnt,cntflip;\n Bitset(int size) {\n arr.resize(size,0);\n cnt=0,cntflip=0;\n }\n void fix(int idx) {\n\t// means current bit is 0 ,so set it to 1\n if((arr[idx]+cntflip)%2==0){\n arr[idx]++;\n cnt++;\n }\n }\n void unfix(int idx) {\n\t// means current bit is 1,so set it to 0\n if((arr[idx]+cntflip)%2!=0){\n arr[idx]--;\n cnt--;\n } \n }\n void flip() {\n\t// cnt will flip ,if we flip all the bits\n cnt=arr.size()-cnt;\n cntflip++;\n }\n bool all() {\n if(cnt==arr.size())\n return true;\n return false;\n }\n bool one() {\n if(cnt>=1)\n return true;\n return false;\n }\n int count() {\n return cnt;\n }\n string toString() {\n string ans;\n for(auto &ele :arr){\n if((cntflip+ele)%2==0)\n ans.push_back('0');\n else\n ans.push_back('1'); \n }\n return ans;\n }\n};" }, { "title": "Longest Ideal Subsequence", "algo_input": "You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:\n\n\n\tt is a subsequence of the string s.\n\tThe absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.\n\n\nReturn the length of the longest ideal string.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\nNote that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.\n\n \nExample 1:\n\nInput: s = \"acfgbd\", k = 2\nOutput: 4\nExplanation: The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.\n\nExample 2:\n\nInput: s = \"abcd\", k = 3\nOutput: 4\nExplanation: The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\t0 <= k <= 25\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestIdealString(self, s: str, k: int) -> int:\n DP = [0 for _ in range(26)]\n ans = 1\n \n for ch in s:\n i = ord(ch) - ord('a')\n DP[i] = DP[i] + 1\n \n for j in range(max(0, i - k), min(25, i + k) + 1):\n if j != i:\n DP[i] = max(DP[i], DP[j] + 1)\n \n ans = max(ans, DP[i])\n \n return ans", "solution_js": "var longestIdealString = function(s, k) {\n let n = s.length\n let dp = Array(26).fill(0);\n let ans = 0;\n for(let i=0; i bool:\n for i in range(0, 10001):\n if head == None: return False\n head = head.next\n \n return True", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n\n/**\n * @param {ListNode} head\n * @return {boolean}\n */\nfunction hasCycle(head){\n \n let fast = head;\n while (fast && fast.next) {\n head = head.next;\n fast = fast.next.next;\n if (head === fast) return true;\n }\n //head and first pointers value in \n //each iteration with head=[3,2,0,-4], pos = 1\n //1st iteration: 3 3\n //2nd iteration: 2 0\n //3rd iteration: 0 2\n //final iteration: -4 -4\n return false;\n};", "solution_java": "public class Solution {\n public boolean hasCycle(ListNode head) {\n ListNode fast = head;\n ListNode slow = head;\n boolean result = false;\n while(fast!=null && fast.next!=null){\n fast = fast.next.next;\n slow = slow.next;\n if(fast == slow){\n result = true;\n break;\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n bool hasCycle(ListNode *head) {\n\t\n\t\t// if head is NULL then return false;\n if(head == NULL)\n return false;\n \n\t\t// making two pointers fast and slow and assignning them to head\n ListNode *fast = head;\n ListNode *slow = head;\n \n\t\t// till fast and fast-> next not reaches NULL\n\t\t// we will increment fast by 2 step and slow by 1 step\n while(fast != NULL && fast ->next != NULL)\n {\n fast = fast->next->next;\n slow = slow->next;\n \n\t\t\t\n\t\t\t// At the point if fast and slow are at same address\n\t\t\t// this means linked list has a cycle in it.\n if(fast == slow)\n return true;\n }\n \n\t\t// if traversal reaches to NULL this means no cycle.\n return false;\n }\n};" }, { "title": "Find Elements in a Contaminated Binary Tree", "algo_input": "Given a binary tree with the following rules:\n\n\n\troot.val == 0\n\tIf treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1\n\tIf treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2\n\n\nNow the binary tree is contaminated, which means all treeNode.val have been changed to -1.\n\nImplement the FindElements class:\n\n\n\tFindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.\n\tbool find(int target) Returns true if the target value exists in the recovered binary tree.\n\n\n \nExample 1:\n\nInput\n[\"FindElements\",\"find\",\"find\"]\n[[[-1,null,-1]],[1],[2]]\nOutput\n[null,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True \n\nExample 2:\n\nInput\n[\"FindElements\",\"find\",\"find\",\"find\"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]\nOutput\n[null,true,true,false]\nExplanation\nFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False\n\nExample 3:\n\nInput\n[\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\nOutput\n[null,true,false,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True\n\n\n \nConstraints:\n\n\n\tTreeNode.val == -1\n\tThe height of the binary tree is less than or equal to 20\n\tThe total number of nodes is between [1, 104]\n\tTotal calls of find() is between [1, 104]\n\t0 <= target <= 106\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 FindElements:\n\n def __init__(self, root: Optional[TreeNode]):\n def recoverTree(root):\n if not root:\n return None\n self.vals.add(root.val)\n if root.left:\n root.left.val = 2 * root.val + 1\n recoverTree(root.left)\n if root.right:\n root.right.val = 2 * root.val + 2\n recoverTree(root.right)\n self.vals = set()\n root.val = 0\n recoverTree(root)\n\n def find(self, target: int) -> bool:\n return target in self.vals\n\n# Your FindElements object will be instantiated and called as such:\n# obj = FindElements(root)\n# param_1 = obj.find(target)", "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 */\nvar FindElements = function(root) {\n this.st = new Set()\n\n recover = (root, val) =>{\n this.st.add(val);\n if(root.left != null) recover(root.left, val * 2 + 1)\n if(root.right != null) recover(root.right, val * 2 + 2)\n }\n\n recover(root, 0)\n};\n\n/**\n * @param {number} target\n * @return {boolean}\n */\nFindElements.prototype.find = function(target) {\n return this.st.has(target)\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * var obj = new FindElements(root)\n * var param_1 = obj.find(target)\n */", "solution_java": "class FindElements {\n TreeNode tree,nodept;\n public FindElements(TreeNode root) {\n tree=root;\n tree.val=0;\n go(tree);\n }\n\n void go(TreeNode node){\n if(node.left!=null){\n node.left.val=node.val*2+1;\n go(node.left);\n }\n if(node.right!=null){\n node.right.val=node.val*2+2;\n go(node.right);\n }\n }\n\n public boolean find(int target) {\n return doit(target);\n }\n\n boolean doit(int target){\n if(target==0){\n nodept=tree;\n return true;\n }\n boolean f=doit((target-1)/2);\n if(!f)return false;\n if(nodept.left!=null && nodept.left.val==target)\n nodept=nodept.left;\n else if(nodept.right!=null && nodept.right.val==target)\n nodept=nodept.right;\n else f=false;\n return f;\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 FindElements {\npublic:\n void initialize(TreeNode* root,unordered_set &s){\n queue q;\n q.push(root);\n while(!q.empty()){\n auto t = q.front();\n q.pop();\n s.insert(t->val);\n if(t->left != NULL){\n t->left->val = 2*(t->val)+1;\n q.push(t->left);\n }\n if(t->right != NULL){\n t->right->val= 2*(t->val)+2;\n q.push(t->right);\n }\n }\n }\n unordered_set s;\n FindElements(TreeNode* root) {\n root->val = 0;\n \n\n initialize(root,s);\n \n }\n \n bool find(int target) {\n if(s.find(target) != s.end())\n return true;\n return false;\n }\n};\n\n/**\n * Your FindElements object will be instantiated and called as such:\n * FindElements* obj = new FindElements(root);\n * bool param_1 = obj->find(target);\n */```" }, { "title": "LFU Cache", "algo_input": "Design and implement a data structure for a Least Frequently Used (LFU) cache.\n\nImplement the LFUCache class:\n\n\n\tLFUCache(int capacity) Initializes the object with the capacity of the data structure.\n\tint get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.\n\tvoid put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.\n\n\nTo determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.\n\nWhen a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.\n\nThe functions get and put must each run in O(1) average time complexity.\n\n \nExample 1:\n\nInput\n[\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n\nExplanation\n// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n  // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3\n\n\n \nConstraints:\n\n\n\t0 <= capacity <= 104\n\t0 <= key <= 105\n\t0 <= value <= 109\n\tAt most 2 * 105 calls will be made to get and put.\n\n\n \n ", "solution_py": "class Node:\n \n def __init__(self, key, val, cnt=1, nxxt=None, prev=None):\n self.key = key\n self.val = val\n self.cnt = cnt\n self.nxxt = nxxt\n self.prev = prev\n \n \nclass NodeList(Node):\n \n def __init__(self):\n self.head = Node(0,0)\n self.tail = Node(0,0)\n self.head.nxxt = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n \n def addFront(self, node):\n temp = self.head.nxxt\n self.head.nxxt = node\n node.prev = self.head\n node.nxxt = temp\n temp.prev = node\n \n self.size += 1\n \n \n def removeNode(self, node):\n delprev = node.prev\n delnxxt = node.nxxt\n delprev.nxxt = delnxxt\n delnxxt.prev = delprev\n \n self.size -= 1\n \n\nclass LFUCache(NodeList):\n\n def __init__(self, capacity: int):\n self.keyNode = {}\n self.freqNodeList = {}\n self.maxSizeCache = capacity\n self.currSize = 0\n self.minFreq = 0\n \n \n def updateFreqNodeList(self, node):\n del self.keyNode[node.key]\n nodelist = self.freqNodeList[node.cnt]\n nodelist.removeNode(node)\n \n if node.cnt == self.minFreq and self.freqNodeList[node.cnt].size == 0:\n self.minFreq += 1\n \n if (node.cnt+1) in self.freqNodeList:\n nextHigherFreqNodeList = self.freqNodeList[node.cnt+1]\n else:\n nextHigherFreqNodeList = NodeList()\n \n node.cnt += 1\n nextHigherFreqNodeList.addFront(node)\n \n self.freqNodeList[node.cnt] = nextHigherFreqNodeList\n self.keyNode[node.key] = node\n \n\n def get(self, key: int) -> int:\n if key in self.keyNode:\n node = self.keyNode[key]\n ans = node.val\n self.updateFreqNodeList(node)\n \n return ans\n \n else:\n return -1\n \n\n def put(self, key: int, value: int) -> None:\n if self.maxSizeCache == 0:\n return\n \n if key in self.keyNode:\n node = self.keyNode[key]\n node.val = value\n self.updateFreqNodeList(node)\n return\n \n else:\n if self.currSize == self.maxSizeCache:\n nodelist = self.freqNodeList[self.minFreq]\n del self.keyNode[nodelist.tail.prev.key]\n nodelist.removeNode(nodelist.tail.prev)\n self.currSize -= 1\n \n self.currSize += 1\n self.minFreq = 1\n \n if self.minFreq in self.freqNodeList:\n nodelist = self.freqNodeList[self.minFreq]\n else:\n nodelist = NodeList()\n \n node = Node(key, value)\n nodelist.addFront(node)\n \n self.keyNode[key] = node\n self.freqNodeList[self.minFreq] = nodelist\n \n\n\n# Your LFUCache object will be instantiated and called as such:\n# obj = LFUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)", "solution_js": "/**\n * @param {number} capacity\n */\nvar LFUCache = function(capacity) {\n this.capacity = capacity;\n this.cache = [];\n};\n\n/** \n * @param {number} key\n * @return {number}\n */\nLFUCache.prototype.get = function(key) {\n let val = -1;\n if (!this.capacity) return val;\n const existIndex = this.cache.findIndex(item => item.key === key);\n if (existIndex > -1) {\n const item = this.cache[existIndex];\n val = item.value;\n item.count++;\n this.cache.splice(existIndex, 1);\n this.cache.unshift(item);\n }\n return val;\n};\n\n/** \n * @param {number} key \n * @param {number} value\n * @return {void}\n */\nLFUCache.prototype.put = function(key, value) {\n if (!this.capacity) return;\n const existIndex = this.cache.findIndex(item => item.key === key);\n if (existIndex > -1) {\n // new item already exists,rewrite the value and increase count\n const existItem = this.cache[existIndex];\n existItem.value = value;\n existItem.count++;\n this.cache.splice(existIndex, 1);\n this.cache.unshift(existItem);\n } else {\n // new item doesn't exist\n if (this.cache.length === this.capacity) {\n // reach the capacity, need to clear LFU\n let lfuIndex = 0;\n let leastCount = this.cache[lfuIndex].count;\n for (let i = 1; i < this.cache.length; i++) {\n const item = this.cache[i];\n if (item.count <= leastCount) {\n leastCount = item.count;\n lfuIndex = i;\n }\n }\n this.cache.splice(lfuIndex, 1);\n // after clear LFU, push the new item\n this.cache.unshift({\n key,\n value,\n count: 1\n });\n } else {\n // new item can be pushed\n this.cache.unshift({\n key,\n value,\n count: 1\n });\n }\n }\n};\n\n/** \n * Your LFUCache object will be instantiated and called as such:\n * var obj = new LFUCache(capacity)\n * var param_1 = obj.get(key)\n * obj.put(key,value)\n */", "solution_java": "\tclass LFUCache {\n // Declare Node class for Doubly Linked List \n class Node{\n int key,value,freq;// to store key,value and frequency\n Node prev,next;// Next and Previous Pointers\n Node(int k,int v){\n // initializing in constructor\n key=k;\n value=v;\n freq=1;\n }\n \n }\n // Declare class for List of Doubly Linked List\n class List{\n int size;\n Node head,tail;\n List(){\n // initializing in constructor\n size=0;\n head=new Node(-1,-1);// Default values\n tail=new Node(-1,-1);\n head.next=tail;\n tail.prev=head;\n }\n // To insert at the start of the list\n void ins(Node newNode){\n Node temp=head.next;\n head.next=newNode;\n newNode.prev=head;\n newNode.next=temp;\n temp.prev=newNode;\n size++;\n \n }\n // To delete specific node\n void del(Node newNode){\n Node pr=newNode.prev;\n Node nx=newNode.next;\n pr.next=nx;\n nx.prev=pr;\n size--;\n }\n }\n Mapmp;// to store key and Node\n MaplistMap;// to store frequency and Doubly Linked List\n int maxSize,minFreq,currSize;// to store total size , minimum frequency and current size of the list\n public LFUCache(int capacity) {\n // initializing in constructor\n maxSize=capacity;\n minFreq=0;\n currSize=0;\n mp=new HashMap();\n listMap=new HashMap();\n }\n \n public int get(int key) {\n // if map contains the specific key \n if(mp.containsKey(key)){\n Node node=mp.get(key);\n int val=node.value;\n updateFreq(node);// to update the frequency of the node\n return val; \n }\n //otherwise\n return -1;\n }\n \n public void put(int key, int value) {\n // one of the corner case\n if(maxSize==0)\n return;\n // if map contains the specific key \n if(mp.containsKey(key)){\n Node node=mp.get(key);\n node.value=value; // update the value of the node\n updateFreq(node);// to update the frequency of the node\n }\n else{\n // if current size is equal to spcified capacity of the LFU list\n if(maxSize==currSize){\n List list=listMap.get(minFreq);\n mp.remove(list.tail.prev.key);// to remove the LRU of the LFU from key-node map\n \n // here LFU is list and even if its is a single element or multiple tail.prev(LRU) is the required element\n \n list.del(list.tail.prev);// to remove the LRU of the LFU from freq-list map\n currSize--;\n }\n currSize++;\n minFreq=1;// reset minFreq to 1 because of adding new node\n List list= new List();\n // If listMap already contains minFreq list\n if(listMap.containsKey(minFreq)){\n list=listMap.get(minFreq);\n }\n Node node = new Node(key,value);// creating a new node\n list.ins(node); // inserting new node to the list\n mp.remove(key); \n mp.put(key,node); // inserting updated new node to the key-node map\n listMap.remove(minFreq);\n listMap.put(minFreq,list);// inserting updated list to the listMap \n }\n }\n public void updateFreq(Node newNode){\n mp.remove(newNode.key);// to remove the node from key-node map\n listMap.get(newNode.freq).del(newNode);// to remove the node from listmap\n \n // If node's freq was minimum and after removing it from the listMap, size is 0\n if(newNode.freq==minFreq && listMap.get(newNode.freq).size==0){\n minFreq++;\n }\n List higherFreqList= new List();\n // If listMap already contains node's freq +1 th list\n if(listMap.containsKey(newNode.freq+1)){\n higherFreqList= listMap.get(newNode.freq+1);\n }\n newNode.freq++; // updating node's frequency\n higherFreqList.ins(newNode); // inserting node to list\n listMap.remove(newNode.freq);\n listMap.put(newNode.freq,higherFreqList);// reinserting list to listMap\n mp.remove(newNode.key);\n mp.put(newNode.key,newNode);// reinserting node to key-node map\n }\n}", "solution_c": "class list_node {\npublic:\n int key, val, cnt;\n list_node* next;\n list_node* prev;\n list_node(int k, int v, list_node* n, list_node* p) {\n key = k; val = v; cnt = 1;\n next = n; prev = p;\n }\n};\nclass LFUCache {\npublic:\n int min_cnt;\n bool zero;\n unordered_map key2node;\n unordered_map> cnt2list;\n LFUCache(int capacity) {\n cin.tie(0); ios_base::sync_with_stdio(0);\n min_cnt = 0;\n c = capacity;\n zero = (c == 0);\n }\n \n int get(int key) {\n if(zero) return -1;\n auto it = key2node.find(key);\n if(it == key2node.end() || it->second == NULL) return -1;\n addcnt(key);\n return it->second->val;\n }\n \n void put(int key, int value) {\n if(zero) return;\n auto it = key2node.find(key);\n if(it != key2node.end() && it->second != NULL) {\n addcnt(key);\n it->second->val = value;\n return;\n }\n if(c) --c;\n else {\n key2node[cnt2list[min_cnt].first->key] = NULL;\n list_node* tmp = cnt2list[min_cnt].first;\n if(tmp->next) tmp->next->prev = NULL;\n cnt2list[min_cnt].first = tmp->next;\n if(cnt2list[min_cnt].second == tmp) cnt2list[min_cnt].second = NULL; \n }\n\n min_cnt = 1;\n list_node* node = new list_node(key, value, NULL, NULL);\n key2node[key] = node;\n if(cnt2list.find(1) == cnt2list.end() || cnt2list[1].first == NULL) {\n cnt2list[1].first = cnt2list[1].second = node;\n }\n else {\n node->prev = cnt2list[1].second;\n cnt2list[1].second->next = node;\n cnt2list[1].second = node;\n }\n }\nprivate:\n int c;\n void addcnt(int key) {\n if(cnt2list[key2node[key]->cnt].first == key2node[key]) \n cnt2list[key2node[key]->cnt].first = key2node[key]->next;\n if(cnt2list[key2node[key]->cnt].second == key2node[key]) \n cnt2list[key2node[key]->cnt].second = key2node[key]->prev;\n if(min_cnt == key2node[key]->cnt && cnt2list[key2node[key]->cnt].first == NULL) min_cnt++;\n key2node[key]->cnt++;\n if(key2node[key]->prev) key2node[key]->prev->next = key2node[key]->next;\n if(key2node[key]->next) key2node[key]->next->prev = key2node[key]->prev;\n key2node[key]->next = NULL;\n auto lit = cnt2list.find(key2node[key]->cnt);\n if(lit == cnt2list.end() || lit->second.first == NULL) {\n cnt2list[key2node[key]->cnt].first = cnt2list[key2node[key]->cnt].second = key2node[key];\n key2node[key]->prev = NULL;\n }\n else {\n key2node[key]->prev = cnt2list[key2node[key]->cnt].second;\n cnt2list[key2node[key]->cnt].second->next = key2node[key];\n cnt2list[key2node[key]->cnt].second = key2node[key];\n }\n }\n};" }, { "title": "Longest Common Prefix", "algo_input": "Write a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n \nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n\n\n \nConstraints:\n\n\n\t1 <= strs.length <= 200\n\t0 <= strs[i].length <= 200\n\tstrs[i] consists of only lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n cmp=strs[0]\n for i in range(1,len(strs)):\n l=0\n if (len(cmp)>len(strs[i])):\n l+=len(strs[i])\n else:\n l+=len(cmp)\n ans=\"\"\n for j in range(l):\n if (cmp[j]!=strs[i][j]):\n if (j==0):\n return \"\"\n else:\n break\n else:\n ans+=strs[i][j]\n cmp=ans\n return cmp\n\t\t\nUpvote If you Like!!!", "solution_js": " var longestCommonPrefix = function(strs) {\n let commonStr=strs[0];\n for(let i=1; i& strs) {\n //brute\n string ans=\"\";\n string ref=strs[0];\n for(int i=0;i int:\n # Basically what we need to return is how many pings fall in the range(t-3000, t).\n # So here we append every t. Now in loop how many t from left side < t-3000, we just pop them\n # and return the length of the list, which'd contain elements in range(t-3000, t).\n # And since every t is going to greater than previous, we don't need to think about duplicates.\n\n self.store.append(t)\n\n while self.store[0] < t-3000:\n self.store.pop(0)\n\n return len(self.store)", "solution_js": "var RecentCounter = function() {\n this.arr = [];\n};\n\nRecentCounter.prototype.ping = function(t) {\n this.arr.push(t);\n while(t > this.arr[0]+3000){\n this.arr.shift();\n }\n return this.arr.length;\n};", "solution_java": "class RecentCounter {\n ArrayList calls ;\n public RecentCounter() {\n calls = new ArrayList();\n }\n \n public int ping(int t) {\n calls.add(t);\n int count = 0;\n for(Integer call:calls){\n if( t-call<=3000) count++;\n }\n return count;\n \n }\n}\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter obj = new RecentCounter();\n * int param_1 = obj.ping(t);\n */", "solution_c": "class RecentCounter {\npublic:\n queue q;\n RecentCounter() {\n }\n\n int ping(int t) {\n q.push(t);\n int x = q.front();\n while(x < t-3000){\n q.pop(); x = q.front();\n }\n return q.size();\n }\n};" }, { "title": "Count Substrings That Differ by One Character", "algo_input": "Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.\n\nFor example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way.\n\nReturn the number of substrings that satisfy the condition above.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"aba\", t = \"baba\"\nOutput: 6\nExplanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.\n\n​​Example 2:\n\nInput: s = \"ab\", t = \"bb\"\nOutput: 3\nExplanation: The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n​​​​The underlined portions are the substrings that are chosen from s and t.\n\n\n \nConstraints:\n\n\n\t1 <= s.length, t.length <= 100\n\ts and t consist of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n res = 0\n for i in range(len(s)):\n for j in range(len(t)):\n miss, pos = 0, 0\n while i + pos < len(s) and j + pos < len(t) and miss < 2:\n miss += s[i + pos] != t[j + pos]\n res += miss == 1\n pos += 1\n return res", "solution_js": "var countSubstrings = function(s, t) {\n const count1 = countAllSubstr(s);\n const count2 = countAllSubstr(t);\n\n let res = 0;\n\n for (const [substr1, freq1] of count1) {\n for (const [substr2, freq2] of count2) {\n\n if (differByOneChar(substr1, substr2)) {\n res += freq1 * freq2;\n }\n }\n }\n\n return res;\n\n function countAllSubstr(str) {\n const n = str.length;\n const count = new Map();\n\n for (let i = 0; i < n; i++) {\n let substr = \"\";\n for (let j = i; j < n; j++) {\n substr += str.charAt(j);\n\n if (!count.has(substr)) count.set(substr, 0);\n count.set(substr, count.get(substr) + 1);\n }\n }\n\n return count;\n }\n\n function differByOneChar(str1, str2) {\n if (str1.length != str2.length) return false;\n\n const n = str1.length;\n\n let missed = 0;\n\n for (let i = 0; i < n; i++) {\n const char1 = str1.charAt(i);\n const char2 = str2.charAt(i);\n\n if (char1 != char2) missed++;\n\n if (missed > 1) return false;\n }\n\n return missed === 1;\n }\n\n};", "solution_java": "// version 1 : O(mn) space\nclass Solution {\n public int countSubstrings(String s, String t) {\n int m = s.length(), n = t.length();\n\n int[][][] dp = new int[m][n][2];\n \n int res = 0;\n // first col s[0:i] match t[0:0]\n for (int i = 0; i < m; i++) {\n dp[i][0][0] = (s.charAt(i) == t.charAt(0)) ? 1 : 0;\n dp[i][0][1] = (s.charAt(i) == t.charAt(0)) ? 0 : 1;\n res += dp[i][0][1];\n }\n \n \n // first row s[0:0] match t[0:j]\n for (int j = 1; j < n; j++) {\n dp[0][j][0] = (s.charAt(0) == t.charAt(j)) ? 1 : 0;\n dp[0][j][1] = (s.charAt(0) == t.charAt(j)) ? 0 : 1;\n res += dp[0][j][1];\n }\n \n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n dp[i][j][0] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][0] + 1 : 0;\n dp[i][j][1] = (s.charAt(i) == t.charAt(j)) ? dp[i-1][j-1][1] : dp[i-1][j-1][0] + 1;\n res += dp[i][j][1];\n }\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int countSubstrings(string s, string t)\n {\n int n=s.size();\n int m=t.size();\n int ans=0;\n for(int i=0;i1)\n {\n break;\n }\n ans+=diff;\n }\n }\n }\n return ans;\n }\n};" }, { "title": "Design Linked List", "algo_input": "Design your implementation of the linked list. You can choose to use a singly or doubly linked list.\nA node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.\nIf you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.\n\nImplement the MyLinkedList class:\n\n\n\tMyLinkedList() Initializes the MyLinkedList object.\n\tint get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.\n\tvoid addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.\n\tvoid addAtTail(int val) Append a node of value val as the last element of the linked list.\n\tvoid addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.\n\tvoid deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.\n\n\n \nExample 1:\n\nInput\n[\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n[[], [1], [3], [1, 2], [1], [1], [1]]\nOutput\n[null, null, null, null, 2, null, 3]\n\nExplanation\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3\n\n\n \nConstraints:\n\n\n\t0 <= index, val <= 1000\n\tPlease do not use the built-in LinkedList library.\n\tAt most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.\n\n", "solution_py": "class Node:\n def __init__(self, val: int):\n self.val = val\n self.next = None\n self.prev = None\n \nclass MyLinkedList:\n def __init__(self):\n self.head = Node(0)\n self.tail = Node(0)\n self.head.next = self.tail\n self.tail.prev = self.head\n self.size = 0\n \n def get(self, index: int) -> int:\n if index < 0 or index >= self.size:\n return -1\n # Distance of index is closer to head\n if index + 1 < self.size - index:\n curr = self.head\n for i in range(index + 1):\n curr = curr.next\n # Distance of index is closer to tail\n else:\n curr = self.tail\n for i in range(self.size - index):\n curr = curr.prev\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.head\n nextNode = self.head.next\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtTail(self, val: int) -> None:\n curr = Node(val)\n prevNode = self.tail.prev\n nextNode = self.tail\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n\n def addAtIndex(self, index: int, val: int) -> None:\n curr = Node(val)\n if index > self.size:\n return\n if index < 0:\n index = 0\n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next\n else:\n nextNode = self.tail\n for i in range(self.size - index):\n nextNode = nextNode.prev\n prevNode = nextNode.prev\n self.size += 1\n curr.prev = prevNode\n curr.next = nextNode\n prevNode.next = curr\n nextNode.prev = curr\n \n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.size:\n return \n if index < self.size - index:\n prevNode = self.head\n for i in range(index):\n prevNode = prevNode.next\n nextNode = prevNode.next.next\n else:\n nextNode = self.tail\n for i in range(self.size - index - 1):\n nextNode = nextNode.prev\n prevNode = nextNode.prev.prev\n self.size -= 1\n prevNode.next = nextNode\n nextNode.prev = prevNode\n\n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)", "solution_js": "var MyLinkedList = function() {\n this.linked = [];\n};\n\nMyLinkedList.prototype.get = function(index) {\n if(index < this.linked.length){\n return this.linked[index];\n }\n return -1;\n};\n\nMyLinkedList.prototype.addAtHead = function(val) {\n this.linked.unshift(val);\n};\n\nMyLinkedList.prototype.addAtTail = function(val) {\n this.linked.push(val);\n};\n\nMyLinkedList.prototype.addAtIndex = function(index, val) {\n if(index <= this.linked.length){\n this.linked.splice(index,0,val);\n }\n};\n\nMyLinkedList.prototype.deleteAtIndex = function(index) {\n this.linked.splice(index,1);\n};", "solution_java": "class MyLinkedList {\n\n public class ListNode {\n public int val;\n public ListNode next;\n\n public ListNode() {\n\n }\n\n public ListNode(int val) {\n this.val = val;\n }\n\n public ListNode(int val, ListNode next) {\n this.val = val;\n this.next = next;\n }\n }\n\n private ListNode head;\n private ListNode tail;\n private int length;\n\n public MyLinkedList() {\n length = 0;\n }\n\n public int get(int index) {\n if (index > length - 1 || index < 0) return -1;\n int thisIndex = 0;\n ListNode temp = head;\n while (thisIndex != index) {\n temp = temp.next;\n thisIndex++;\n }\n return temp.val;\n }\n\n public void addAtHead(int val) {\n head = new ListNode(val, head);\n length++;\n if (length == 1) tail = head;\n }\n\n public void addAtTail(int val) {\n length++;\n if (length == 1) {\n ListNode onlyNode = new ListNode(val);\n head = onlyNode;\n tail = head;\n return;\n }\n tail.next = new ListNode(val);\n tail = tail.next;\n }\n\n public void addAtIndex(int index, int val) {\n if (index <= length) {\n if (index == 0) {\n addAtHead(val);\n return;\n }\n if (index == length) {\n addAtTail(val);\n return;\n }\n length++;\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n temp.next = new ListNode(val, temp.next);\n }\n }\n\n public void deleteAtIndex(int index) {\n if (index >= length || index < 0) return;\n length--;\n if (index == 0) {\n head = head.next;\n return;\n }\n ListNode temp = head;\n int thisIndex = 0;\n while (thisIndex != index - 1) {\n temp = temp.next;\n thisIndex++;\n }\n if (index == length) {\n tail = temp;\n temp.next = null;\n }\n else temp.next = temp.next.next;\n }\n}", "solution_c": "class MyLinkedList {\n struct Node{\n int val;\n Node *next,*prev;\n Node(int x){val=x,next=prev=NULL;}\n };\n Node *head;int size;\npublic:\n MyLinkedList() {\n head=NULL;size=0;\n }\n \n int get(int index) {\n if(index>=size or index<0) return -1;\n Node *ptr=head;\n for(int i=0;inext;\n return ptr->val;\n }\n \n void addAtHead(int val) {\n Node *newNode=new Node(val);\n newNode->next=head;\n if(head) head->prev=newNode;\n head=newNode;\n size++;\n }\n \n void addAtTail(int val) {\n addAtIndex(size,val);\n }\n \n void addAtIndex(int index, int val) {\n if(index<0 or index>size) return;\n if(index==0){\n addAtHead(val);return;\n }\n Node *newNode=new Node(val);\n Node *prev=head;\n for(int i=0;inext;\n }\n newNode->next=prev->next;\n prev->next=newNode;\n newNode->prev=prev;\n if(newNode->next) newNode->next->prev=newNode;\n size++;\n }\n \n void deleteAtIndex(int index) {\n if(index>=size or index<0) return;\n if(index==0){\n Node *temp=head;\n head=head->next;\n delete temp;size--;\n return;\n }\n Node *del=head;\n for(int i=0;inext;\n }\n if(del->prev) del->prev->next=del->next;\n if(del->next) del->next->prev=del->prev;\n delete del;\n size--;\n }\n};" }, { "title": "Range Sum Query - Mutable", "algo_input": "Given an integer array nums, handle multiple queries of the following types:\n\n\n\tUpdate the value of an element in nums.\n\tCalculate the sum of the elements of nums between indices left and right inclusive where left <= right.\n\n\nImplement the NumArray class:\n\n\n\tNumArray(int[] nums) Initializes the object with the integer array nums.\n\tvoid update(int index, int val) Updates the value of nums[index] to be val.\n\tint sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n\n\n \nExample 1:\n\nInput\n[\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\nOutput\n[null, 9, null, 8]\n\nExplanation\nNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 3 * 104\n\t-100 <= nums[i] <= 100\n\t0 <= index < nums.length\n\t-100 <= val <= 100\n\t0 <= left <= right < nums.length\n\tAt most 3 * 104 calls will be made to update and sumRange.\n\n", "solution_py": "class NumArray:\n nums = []\n s = 0\n l = 0\n \n def __init__(self, nums: List[int]):\n self.nums = nums\n self.s = sum(nums)\n self.l = len(nums)\n\n def update(self, index: int, val: int) -> None:\n self.s -= self.nums[index]\n self.nums[index] = val\n self.s += self.nums[index]\n\n def sumRange(self, left: int, right: int) -> int:\n if right - left > self.l // 2:\n ans = sum(self.nums[:left]) + sum(self.nums[right + 1:])\n return self.s - ans\n else:\n return sum(self.nums[left: right + 1])", "solution_js": "var NumArray = function(nums) {\n this.nums = nums;\n this.n = nums.length;\n this.fenwickTree = new Array(this.n + 1).fill(0);\n nums.forEach((num, index) => this.init(index, num));\n};\n\nNumArray.prototype.init = function(index, val) {\n let j = index + 1;\n while(j <= this.n) {\n this.fenwickTree[j] += val;\n j += this.lsb(j);\n }\n};\n\nNumArray.prototype.lsb = function(index) {\n return index & ~(index - 1);\n};\n\nNumArray.prototype.update = function(index, val) {\n const diff = val - this.nums[index];\n this.nums[index] = val;\n this.init(index, diff);\n};\n\nNumArray.prototype.getSum = function(index) {\n let j = index + 1;\n let sum = 0;\n\n while(j > 0) {\n sum += this.fenwickTree[j];\n j -= this.lsb(j);\n }\n\n return sum;\n};\n\nNumArray.prototype.sumRange = function(left, right) {\n return this.getSum(right) - this.getSum(left - 1);\n};", "solution_java": "class NumArray {\n SegmentTree s;\n public NumArray(int[] nums) {\n s = new SegmentTree(nums);\n s.root = s.build(0, s.arr.length, s.arr);//build returns root Node of what it built\n }\n \n public void update(int index, int val) {\n int oldvalue = s.arr[index];//Find old value with traditional array, which is O(1) time complexity\n s.arr[index] = val;//Set our array so that there will be no contradictions if we ever rebuild.\n //If we are going use build function only once, then we don't need to update our traditional array. \n s.update(s.root, val, index, oldvalue);//Call class' function\n }\n \n public int sumRange(int left, int right) {\n return s.rangeSum(s.root, left, right);\n }\n}\n\nclass Node {\n int s;//inclusive label\n int e;//inclusive label\n int val;\n Node left;\n Node right;\n}\n\nclass SegmentTree {\n Node root;\n int[] arr;\n\n SegmentTree(int [] arr) {\n this.arr = arr;\n }\n\n public Node build(int start, int end, int[] arr) {\n //Start and End integers have nothing to do with building of our SegmentTree, you may ignore them for now\n //They are needed for querying and updating, so that we can use binary search.\n Node temp = new Node();\n if (arr.length == 1) {//which means we are setting a node equal to an element of arr\n temp.val = arr[0];\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n } else if (arr.length == 0 || start > end || start < 0 || end < 0) {\n return new Node();// may be better\n } else {\n //left = build(start, mid but add 1 if array's length is not divisible by 2, left half of the passed array)\n temp.left = build(start, (start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), Arrays.copyOfRange(arr, 0, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0)));\n //right = build(start, mid but add 1 if array's length is not divisible by 2, right half of the passed array)\n temp.right = build((start+end)/2 + (arr.length % 2 == 1 ? 1 : 0), end, Arrays.copyOfRange(arr, arr.length/2 + (arr.length % 2 == 1 ? 1 : 0), arr.length));\n temp.val = temp.left.val + temp.right.val;\n temp.s = start;\n temp.e = end-1;//to make it inclusive\n }\n return temp;//return this Node to one upper call so that this can be a child of it's parent\n }\n \n public int rangeSum(Node node, int l, int r) {\n if(node == null)\n {\n //Range is completely outside given range\n return 0;\n }\n if(l <= node.s && node.e <= r)\n {\n //Range is completely inside given range\n return node.val;\n }\n //Range is partially inside and partially outside the given range\n int mid = (node.s + node.e) / 2;\n int left = 0;\n int right = 0;\n if (l <= mid) {\n //For example let's say root's borders are 0:3, l,r=1:2\n //Then mid will be 1, then we will go into both directions because 1<=1, and 2>=1\n //Our next calls will be rS(root.left(which is 0:1), 1, 2) and rS(root.right(which is 2:3), 1, 2)\n //Left call's mid will be mid = (0+1)/2 = 0\n //Then 1<=0 ? No it's not, this is why left call's variable named left will be 0\n //Then 2>=0 ? Yes, we will call rS(root.left.right(which is 1:1), 1, 2)\n //Our left call's right call:\n //1:1 is completely inside 1:2, return the value it holds(equals to arr[1] if our arr is up to date)\n //Our original call's left will be arr[1]\n //Let's calculate our first right function\n //With same reasoning, our right function will go to left and be root.right.left(which is 2:2)\n //Our original call's right will be arr[2]\n //Our original/first function will return left + right, which is in fact [1:2] inclusive\n left = rangeSum(node.left, l, r);\n } \n if (r >= mid) {\n right = rangeSum(node.right, l, r);\n }\n return (left + right);\n }\n //What we are doing is, going downwards in our tree while we update the values we touch upon\n //We need to update root always, since it is sum of every element\n //After that we find mid which is mid value of our current node's start and end(inclusive)\n //At first call this will be (0+arr.length)/2 => mid\n //If given idx is bigger than mid, then we need to keep searching at right branch\n //That is why we call the function with root.right as our new root\n //If given idx is smaller and equals to mid, then we search at left branch\n //Why did we include equality too? Because I built my tree this way.(where equal things go left)\n //If idx is between our root's borders then we will decrease by the old value, increase by the new value.\n //If root equals null, we won't do anything\n //We update our traditional array at above.\n public void update(Node root, int value, int idx, int oldvalue) {\n if (root == null) {\n return;\n }\n int mid = (root.e + root.s) / 2;\n if (idx <= root.e && idx >= root.s) {\n root.val -= oldvalue;\n root.val += value;\n } if (idx > mid) {\n update(root.right, value, idx, oldvalue);\n } else if (idx <= mid) {\n update(root.left, value, idx, oldvalue);\n }\n }\n}", "solution_c": "class NumArray {\npublic:\n vectorv; //vector to store input vector.\n int sum; //sum of all element of vector \n NumArray(vector& nums) {\n v=nums;\n sum=0;\n for(int i=0;i bool:\n target.sort()\n arr.sort()\n if len(target)==len(arr):\n if target==arr:\n return True\n else:\n return False", "solution_js": "var canBeEqual = function(target, arr) {\n if(arr.length==1){\n if(arr[0]===target[0]){\n return true\n }\n }\n let obj = {}\n for(let i =0;ihm1=new HashMap();\n for(int i: arr){\n if(hm1.containsKey(i))\n hm1.put(i,hm1.get(i)+1);\n else\n hm1.put(i,1);\n }\n for(int i: target){\n if(hm1.containsKey(i)){\n hm1.put(i,hm1.getOrDefault(i,0)-1);\n if(hm1.get(i)==0)\n hm1.remove(i);\n }\n else\n return false;\n \n }\n if(hm1.size()==0)\n return true;\n \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canBeEqual(vector& target, vector& arr) {\n int arr1[1001]={0};\n int arr2[1001]={0};\n \n for(int i =0 ; i int:\n ans = self.solve(jobDifficulty, 0, d)\n if ans == float(\"inf\"):\n return -1\n else:\n return ans", "solution_js": "var minDifficulty = function(jobDifficulty, d) {\n // don't have enought jobs to distribute\n if (jobDifficulty.length < d) {\n return -1;\n }\n\n // in dynamic programming top-down approach\n // we need to have memoisation to not repeat calculations\n let memo = new Array(d+1).fill(-1).map(\n () => new Array(jobDifficulty.length+1).fill(-1)\n )\n\n const dp = function(D, N) {\n\n // if we calculated this before, just return\n if (-1 != memo[D][N]) {\n return memo[D][N];\n }\n\n // if we have only 1 day, we just need to take all jobs\n // and return the highest difficulty\n if (1 == D) {\n memo[D][N] = 0;\n for (let i = 0; i < N; i++) {\n if (memo[D][N] < jobDifficulty[i]) {\n memo[D][N] = jobDifficulty[i];\n }\n }\n return memo[D][N];\n }\n\n // otherwise, we use our recurrence relation to calculate\n memo[D][N] = 1000 * D;\n\n let max_job_per_day = N - D + 1;\n let max_difficulty = 0;\n\n // iteration for recurrence relation\n for (let X = 1; X <= max_job_per_day; X++) {\n // count max in the current range\n // len - X is the starting point for\n // the last day in D days\n if (jobDifficulty[N - X] > max_difficulty) {\n max_difficulty = jobDifficulty[N - X];\n }\n // recurrence relation\n // we took X jobs,\n // so we still have N - X jobs for D - 1 days\n let min_sum = max_difficulty + dp(D - 1, N - X);\n\n // pick the min only\n if (min_sum < memo[D][N]) {\n memo[D][N] = min_sum;\n }\n }\n\n return memo[D][N];\n }\n\n return dp(d, jobDifficulty.length);\n}", "solution_java": "class Solution {\n // Given an array, cut it into d contiguous subarray and return the minimum sum of max of each subarray.\n public int minDifficulty(int[] jobDifficulty, int d) {\n if(d>jobDifficulty.length){\n return -1;\n }\n \n int[][] memo = new int[d+1][jobDifficulty.length];\n for(int[] m : memo){\n Arrays.fill(m, -1);\n }\n \n return getMinDays(jobDifficulty, d, memo, 0);\n }\n \n private int getMinDays(int[] jobDifficulty, int d, int[][] memo, int idx){\n if(d==1){\n int max=0;\n while(idx < jobDifficulty.length){\n max=Math.max(max, jobDifficulty[idx]);\n idx++;\n }\n return max;\n }\n \n if(memo[d][idx] != -1) return memo[d][idx];\n \n int max=0;\n int res=Integer.MAX_VALUE;\n // [6,5,4,3,2,1], d=5 => we don't want the cut at 4th position in the array because we won't be able to divide it into 5 parts\n for(int i=idx; i v;\n int len;\n int dp[301][11];\n int dfs(int idx, int d){//n*d\n if(idx>=len)\n return 0;\n if(d==1)\n return *max_element(v.begin()+idx,v.end());\n if(dp[idx][d]!=-1)\n return dp[idx][d];\n int maxx=INT_MIN;\n int res=INT_MAX;\n for(int i=idx;i<=len-d;i++){//n\n maxx=max(v[i],maxx);\n res=min(maxx+dfs(i+1,d-1),res);\n }\n return dp[idx][d]=res;\n }\npublic:\n int minDifficulty(vector& jobDifficulty, int d) {\n v=jobDifficulty;\n len=v.size();\n if(d>len)\n return -1;\n memset(dp,-1,sizeof(dp));\n return dfs(0,d);\n }\n};" }, { "title": "Path With Minimum Effort", "algo_input": "You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.\n\nA route's effort is the maximum absolute difference in heights between two consecutive cells of the route.\n\nReturn the minimum effort required to travel from the top-left cell to the bottom-right cell.\n\n \nExample 1:\n\n\n\nInput: heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput: 2\nExplanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n\n\nExample 2:\n\n\n\nInput: heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput: 1\nExplanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n\n\nExample 3:\n\nInput: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput: 0\nExplanation: This route does not require any effort.\n\n\n \nConstraints:\n\n\n\trows == heights.length\n\tcolumns == heights[i].length\n\t1 <= rows, columns <= 100\n\t1 <= heights[i][j] <= 106\n", "solution_py": "class Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n di = (0, 1, 0, -1)\n dj = (1, 0, -1, 0)\n m, n = len(heights), len(heights[0])\n visited = [[False] * n for _ in range(m)]\n h = [(0, 0, 0)]\n while h:\n effort, i, j = heappop(h)\n if visited[i][j]:\n continue\n visited[i][j] = True\n if i + 1 == m and j + 1 == n:\n return effort ## have reached the (m-1, n-1) cell\n for k in range(4):\n ii, jj = i + di[k], j + dj[k]\n if 0 <= ii < m and 0 <= jj < n and not visited[ii][jj]:\n neffort = max(effort, abs(heights[i][j] - heights[ii][jj]))\n heappush(h, (neffort, ii, jj))\n return ## cell (m-1, n-1) not reachable, should never happen", "solution_js": "/**\n * @param {number[][]} heights\n * @return {number}\n * T: O((M*N)log(M*N))\n * S: O(M*N)\n */\nvar minimumEffortPath = function(heights) {\n const directions = [\n [1, 0],\n [0, 1],\n [-1, 0],\n [0, -1],\n ];\n const row = heights.length;\n const col = heights[0].length;\n const differences = [];\n for (let i = 0; i < row; i++) {\n for (let j = 0; j < col; j++) {\n if (!differences[i]) {\n differences[i] = [Infinity];\n } else {\n differences[i].push(Infinity);\n }\n }\n }\n differences[0][0] = 0;\n const pq = new PriorityQueue();\n pq.push([0, 0], 0);\n while (pq.data.length > 0) {\n const node = pq.shift();\n const difference = node.priority;\n const [x, y] = node.val;\n directions.forEach(([dx, dy]) => {\n const newX = x + dx;\n const newY = y + dy;\n if (newX >= 0 && newX < row && newY >= 0 && newY < col) {\n const currentDiff = Math.abs(heights[newX][newY] - heights[x][y]);\n const maxDiff = Math.max(currentDiff, differences[x][y]);\n if (differences[newX][newY] > maxDiff) {\n differences[newX][newY] = maxDiff;\n pq.push([newX, newY], maxDiff);\n }\n }\n });\n }\n return differences[row - 1][col - 1];\n};\n\nconst swap = (arr, i, j) => {\n const temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n};\n\nfunction Node(val, priority) {\n this.val = val;\n this.priority = priority;\n}\n\nfunction PriorityQueue() {\n this.data = [];\n}\n\nPriorityQueue.prototype.push = function push(val, priority) {\n const node = new Node(val, priority);\n this.data.push(node);\n let index = this.data.length - 1;\n while (index > 0) {\n const parentIndex = Math.floor((index - 1) / 2);\n const parent = this.data[parentIndex];\n if (parent.priority > node.priority) {\n swap(this.data, parentIndex, index);\n index = parentIndex;\n } else {\n break;\n }\n }\n};\n\nPriorityQueue.prototype.shift = function shift() {\n const minNode = this.data[0] || {};\n const lastNode = this.data.pop();\n if (this.data.length < 1) {\n return minNode;\n }\n this.data[0] = lastNode;\n let index = 0;\n while (index < this.data.length) {\n const leftIndex = 2 * index + 1;\n const rightIndex = 2 * index + 2;\n const leftNode = this.data[leftIndex] || {};\n const rightNode = this.data[rightIndex] || {};\n let smallerIndex;\n if (leftNode.priority < lastNode.priority) {\n smallerIndex = leftIndex;\n }\n if (!smallerIndex && rightNode.priority < lastNode.priority) {\n smallerIndex = rightIndex;\n }\n if (smallerIndex && rightNode.priority < leftNode.priority) {\n smallerIndex = rightIndex;\n }\n if (!smallerIndex) {\n break;\n }\n swap(this.data, index, smallerIndex);\n index = smallerIndex;\n }\n return minNode;\n};", "solution_java": "class Tuple {\n\n int distance;\n\n int row;\n\n int col;\n\n \n\n Tuple(int distance, int row, int col) {\n\n this.distance = distance;\n\n this.row = row;\n\n this.col = col;\n\n }\n\n}\n\n\n\nclass Solution {\n\n public int minimumEffortPath(int[][] heights) {\n\n // Create a min heap based on the distance\n\n PriorityQueue minHeap = new PriorityQueue<>((x, y) -> x.distance - y.distance);\n\n \n\n int rows = heights.length;\n\n int cols = heights[0].length;\n\n \n\n // Create a 2D array to store the minimum effort to reach each cell\n\n int effort[][] = new int[rows][cols];\n\n \n\n // Initialize all efforts to maximum initially\n\n for (int i = 0; i < rows; i++) {\n\n Arrays.fill(effort[i], Integer.MAX_VALUE);\n\n }\n\n \n\n effort[0][0] = 0; // Initial effort at the starting cell\n\n \n\n // Add the starting cell to the min heap\n\n minHeap.add(new Tuple(0, 0, 0));\n\n \n\n // Arrays to represent row and column changes for 4 directions\n\n int dr[] = {-1, 0, 1, 0}; // Up, Right, Down, Left\n\n int dc[] = {0, 1, 0, -1};\n\n \n\n while (!minHeap.isEmpty()) {\n\n Tuple current = minHeap.poll(); // Get the cell with the minimum effort\n\n int distance = current.distance;\n\n int row = current.row;\n\n int col = current.col;\n\n \n\n if (row == rows - 1 && col == cols - 1) {\n\n return distance; // If reached the destination, return the effort\n\n }\n\n \n\n // Explore each of the 4 possible directions\n\n for (int i = 0; i < 4; i++) {\n\n int newRow = row + dr[i]; // Calculate new row index\n\n int newCol = col + dc[i]; // Calculate new column index\n\n \n\n // Check if the new cell is within bounds\n\n if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {\n\n \n\n // Calculate the new effort based on the maximum of height difference and current effort\n\n int newEffort = Math.max(Math.abs(heights[row][col] - heights[newRow][newCol]), distance);\n\n \n\n // If the new effort is less than the stored effort for the cell, update and add to heap\n\n if (newEffort < effort[newRow][newCol]) {\n\n effort[newRow][newCol] = newEffort;\n\n minHeap.add(new Tuple(newEffort, newRow, newCol)); // Add to heap for further exploration\n\n }\n\n }\n\n }\n\n }\n\n return 0; // This value should be replaced with the actual minimum effort\n\n }\n\n}", "solution_c": "#define pii pair>\n\nclass Solution {\npublic:\n //Directions (top, right, bottom, left)\n const int d4x[4] = {-1,0,1,0}, d4y[4] = {0,1,0,-1};\n \n int minimumEffortPath(vector>& h) {\n int n = h.size(), m = h[0].size();\n //min-heap\n priority_queue , greater> pq;\n //to store distances from (0,0)\n vector> dis(n, vector(m, INT_MAX));\n dis[0][0] = 0;\n pq.push({0, {0, 0}});\n \n //Dijstra algorithm\n while(!pq.empty()) {\n pii curr = pq.top(); pq.pop();\n int d = curr.first, r = curr.second.first, c = curr.second.second;\n // bottom right position\n if(r==n-1 && c==m-1) return d;\n for(int i=0; i<4; ++i) {\n int nx = r + d4x[i], ny = c + d4y[i];\n //check if new position is invalid\n if(nx < 0 || nx >= n || ny < 0 || ny >= m)continue;\n\t\t\t\t//nd => new distance: which is max of distance till now(d) and curr distance (difference between heights of current cells)\n int nd = max(d, abs(h[nx][ny] - h[r][c]));\n if (nd < dis[nx][ny]) {\n dis[nx][ny] = nd;\n pq.push({nd, {nx, ny}});\n }\n }\n }\n return 0;\n //please upvote\n }\n};" }, { "title": "First Missing Positive", "algo_input": "Given an unsorted integer array nums, return the smallest missing positive integer.\n\nYou must implement an algorithm that runs in O(n) time and uses constant extra space.\n\n \nExample 1:\n\nInput: nums = [1,2,0]\nOutput: 3\nExplanation: The numbers in the range [1,2] are all in the array.\n\n\nExample 2:\n\nInput: nums = [3,4,-1,1]\nOutput: 2\nExplanation: 1 is in the array but 2 is missing.\n\n\nExample 3:\n\nInput: nums = [7,8,9,11,12]\nOutput: 1\nExplanation: The smallest positive integer 1 is missing.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-231 <= nums[i] <= 231 - 1\n\n", "solution_py": "class Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n mn = float('inf')\n mx = 0\n numsSet = set()\n\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] > 0:\n if nums[i] < mn:\n mn = nums[i]\n if nums[i] > mx:\n mx = nums[i]\n numsSet.add(nums[i])\n del nums[i]\n\n if mn >= 2:\n return 1\n if len(numsSet) == mx:\n return mx + 1\n for i in range(2, len(numsSet) + 1):\n if i not in numsSet:\n return i", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar firstMissingPositive = function (nums) {\n\n //first make all negative numbers to zero =>zero means we ignore whis number\n for (let index = 0; index < nums.length; index++) {\n if (nums[index] < 0)\n nums[index] = 0\n }\n\n for (let index = 0; index < nums.length; index++) {\n const temp = Math.abs(nums[index])\n const element = temp - 1\n\n if (element < nums.length && element >= 0)\n nums[element] = nums[element] === 0 ? -(nums.length + 1) : Math.abs(nums[element]) * -1\n\n }\n\n for (let index = 0; index < nums.length; index++) {\n const element = (nums[index])\n if (element >= 0) return index + 1\n\n }\n return nums.length+1\n\n};", "solution_java": "class Solution {\n public int firstMissingPositive(int[] nums) {\n //cyclic sort\n int i = 0;\n while (i0 && nums[i]<=nums.length && nums[i]!=nums[correct]){\n swap(nums,i,correct);\n }else{\n i++;\n }\n }\n //linear search to find the missing number\n for(int index=0;index& nums) {\n int n = nums.size();\n for(int i=0; in) continue;\n while(nums[i]!=i+1 && nums[i]>0 && nums[i]<=n && nums[nums[i]-1] != nums[i]){\n swap(nums[i],nums[nums[i]-1]);\n }\n }\n int ans = -1;\n for(int i=0; i bool:\n \n \"\"\"\n let's forget about Alice and Bob for a second and just concentrate on the n and plays\n if played optimally :\n \n 1 - player at 1 will loose since no factors\n 2 - player at 2 will win by choosing 1\n 3 - player at 3 will loose always since he/she has to choose 1. and then next player will always win because they are at 2\n 4 - player at 4 will win by choosing 1 as a factor as next player will have to play at 3\n 5 - player at 5 will loose because he has to choose 1, and player at 4 will always win\n 6 - player at 6 will always win by choosing 3 as a factor\n 7 - player at 7 will have to choose 1, and hence result 6 will make player at 6 to win\n 8 - player at 8 can choose 1 and win always\n .\n .\n .\n .\n Pattern detected\n \n Now, since Alice is the first player we can return bool values accordingly\n \n \n \"\"\"\n \n return n%2 == 0\n \n ", "solution_js": "var divisorGame = function(n) {\n let count = 0;\n while(true){\n let flag = true;\n for(let i = 1;i int:\n \n names=defaultdict(set)\n res=0 \n \n #to store first letter as key and followed suffix as val\n for i in ideas:\n names[i[0]].add(i[1:])\n \n #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)\n arr=list(names.keys())\n ans,n=0,len(arr)\n \n for i in range(n):\n for j in range(i+1,n):\n #a,b => 2 distinct first letters\n a,b=arr[i],arr[j]\n # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be \"newword1 newword2\" or \"newword2 newword1\"\n res+=len(names[a]-names[b])*len(names[b]-names[a])*2\n \n return res\n\t", "solution_js": "/**\n * @param {string[]} ideas\n * @return {number}\n */\nvar distinctNames = function(ideas) {\n let res = 0;\n let lMap = new Map();\n\n for(let i=0; i 0 && m2.size > 0){\n let k1 = Array.from(m1.keys());\n for(let k=0; k [] arr = new HashSet[26];\n for(int i=0; i<26; i++) {\n arr[i] = new HashSet<>();\n }\n for(String s: ideas) {\n arr[s.charAt(0)-'a'].add(s.substring(1));\n }\n long ans=0, cnt;\n for(int i=0; i<26; i++) {\n for(int j=i+1; j<26; j++) {\n cnt=0;\n for(String str: arr[j]) {\n if(arr[i].contains(str)) cnt++;\n }\n ans+=2*(arr[i].size()-cnt)*(arr[j].size()-cnt);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n long long distinctNames(vector& ideas) {\n unordered_map > mp;\n for(auto u : ideas) mp[u[0]].insert(u.substr(1,u.size()-1));\n \n long long ans = 0;\n \n for(int i = 0; i<26; i++){\n for(int j = i+1; j<26; j++){\n unordered_set s1 = mp[i+'a'], s2 = mp[j+'a'];\n \n int comm = 0;\n for(auto u : s1)\n if(s2.find(u)!=s2.end()) comm++;\n \n ans += (long long)(s1.size()-comm)*(long long)(s2.size()-comm)*2;\n }\n }\n return ans;\n }\n};" }, { "title": "Rearrange Characters to Make Target String", "algo_input": "You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.\n\nReturn the maximum number of copies of target that can be formed by taking letters from s and rearranging them.\n\n \nExample 1:\n\nInput: s = \"ilovecodingonleetcode\", target = \"code\"\nOutput: 2\nExplanation:\nFor the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.\n\n\nExample 2:\n\nInput: s = \"abcba\", target = \"abc\"\nOutput: 1\nExplanation:\nWe can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".\n\n\nExample 3:\n\nInput: s = \"abbaccaddaeea\", target = \"aaaaa\"\nOutput: 1\nExplanation:\nWe can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\t1 <= target.length <= 10\n\ts and target consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def rearrangeCharacters(self, s: str, target: str) -> int:\n counter_s = Counter(s)\n return min(counter_s[c] // count for c,count in Counter(target).items())", "solution_js": "/**\n * @param {string} s\n * @param {string} target\n * @return {number}\n */\nvar rearrangeCharacters = function(s, target) {\n let cnt = Number.MAX_VALUE;\n\n let m1 = new Map();\n for(const x of target) m1.set(x , m1.get(x)+1 || 1);\n\n let m2 = new Map();\n for(const x of s) m2.set(x , m2.get(x)+1 || 1);\n\n for(let it of m1){\n let ch = it[0];\n let x = it[1];\n let y = m2.get(ch);\n if(y === undefined) y=0;\n cnt = Math.min(cnt,Math.floor(y/x));\n }\n return cnt;\n};", "solution_java": "class Solution\n{\n public int rearrangeCharacters(String s, String target)\n {\n int[] freq = new int[26], freq2 = new int[26];\n for(char ch : s.toCharArray())\n freq[ch-'a']++;\n for(char ch : target.toCharArray())\n freq2[ch-'a']++;\n\n int min = Integer.MAX_VALUE;\n for(char ch : target.toCharArray())\n min = Math.min(min,freq[ch-'a']/freq2[ch-'a']);\n \n return min;\n }\n}", "solution_c": "Approach :\n => Take two map, one to store frequency of target, and another for sentence. \n\t => Traverse over the mp(frequency of target ) and calculate the minimum frequency ratio \n\t mn = min(mn , frequency of a char in sentance / frequency of same char in target) ; \t\t \n\t\t\t\t\t\t\t\t\t\t \n\t\tSpace : O(n) \n\t\tTime : O(n)\nclass Solution {\npublic:\n int rearrangeCharacters(string s, string target) {\n unordered_map targetFreq ; \n for(auto a : target) {\n targetFreq[a] ++;\n }\n unordered_map sentFreq ; \n for(auto a : s) {\n sentFreq[a] ++ ; \n }\n int mn = INT_MAX ; \n for(auto a : targetFreq ) {\n mn = min(mn , sentFreq[a.first]/a.second); \n }\n return mn ; \n }\n};" }, { "title": "Remove Duplicates from Sorted List", "algo_input": "Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.\n\n \nExample 1:\n\nInput: head = [1,1,2]\nOutput: [1,2]\n\n\nExample 2:\n\nInput: head = [1,1,2,3,3]\nOutput: [1,2,3]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 300].\n\t-100 <= Node.val <= 100\n\tThe list is guaranteed to be sorted in ascending order.\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if head is None:\n return head\n cur=head.next\n prev=head\n while cur is not None:\n if cur.val==prev.val:\n prev.next=cur.next\n else:\n prev=cur\n cur=cur.next\n return head", "solution_js": "var deleteDuplicates = function(head) {\n // Special case...\n if(head == null || head.next == null)\n return head;\n // Initialize a pointer curr with the address of head node...\n let curr = head;\n // Traverse all element through a while loop if curr node and the next node of curr node are present...\n while( curr != null && curr.next != null){\n // If the value of curr is equal to the value of prev...\n // It means the value is present in the linked list...\n if(curr.val == curr.next.val){\n // Hence we do not need to include curr again in the linked list...\n // So we increment the value of curr...\n curr.next = curr.next.next;\n }\n // Otherwise, we increment the curr pointer...\n else{\n curr = curr.next; \n }\n }\n return head; // Return the sorted linked list without any duplicate element...\n};", "solution_java": "class Solution {\n public ListNode deleteDuplicates(ListNode head) {\n\n if (head == null) {\n return head;\n }\n\n ListNode result = head;\n\n while (result != null) {\n if (result.next == null) {\n break;\n }\n\n if (result.val == result.next.val) {\n result.next = result.next.next;\n } else {\n result = result.next;\n }\n }\n\n return head;\n }\n}", "solution_c": "class Solution {\npublic:\n // Recursive Approach\n ListNode* deleteDuplicates(ListNode* head){\n // base case\n if(head==NULL || head->next==NULL)\n return head;\n // 1-1-2-3-3\n //we are giving next pointer to recursion and telling it to get it done for me\n ListNode* newNode=deleteDuplicates(head->next); // 1-2-3-3\n // after recursion we will get-- 1-2-3\n \n //now we will compare the head node with the newNode \n // if both are same then return the newNode\n //else return the current head\n if(head->val==newNode->val) \n return newNode;\n else{\n head->next=newNode;\n return head;\n } \n }\n};\n\n\nclass Solution {\npublic:\n // Iterative Approach\n ListNode* deleteDuplicates(ListNode* head){\n if(head==NULL || head->next==NULL) return head;\n \n ListNode* temp =head;\n while(temp->next!=NULL){\n // if the 2 consecutive nodes are equal then just delete the in between\n if(temp->val==temp->next->val){\n temp->next=temp->next->next;\n //dont need to update the temp variable as there can be more than 2 duplicates\n // 1-1-1-1-2-3-4-4-NULL\n }\n else{\n temp=temp->next; //update the temp variable\n }\n }\n return head;\n }\n};" }, { "title": "Robot Bounded In Circle", "algo_input": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:\n\n\n\tThe north direction is the positive direction of the y-axis.\n\tThe south direction is the negative direction of the y-axis.\n\tThe east direction is the positive direction of the x-axis.\n\tThe west direction is the negative direction of the x-axis.\n\n\nThe robot can receive one of three instructions:\n\n\n\t\"G\": go straight 1 unit.\n\t\"L\": turn 90 degrees to the left (i.e., anti-clockwise direction).\n\t\"R\": turn 90 degrees to the right (i.e., clockwise direction).\n\n\nThe robot performs the instructions given in order, and repeats them forever.\n\nReturn true if and only if there exists a circle in the plane such that the robot never leaves the circle.\n\n \nExample 1:\n\nInput: instructions = \"GGLLGG\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.\n\n\nExample 2:\n\nInput: instructions = \"GG\"\nOutput: false\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.\n\n\nExample 3:\n\nInput: instructions = \"GL\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.\n\n\n \nConstraints:\n\n\n\t1 <= instructions.length <= 100\n\tinstructions[i] is 'G', 'L' or, 'R'.\n\n", "solution_py": "class Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n pos, d = [0,0], \"N\"\n def move(d, pos, instructions):\n for i in instructions:\n if i == \"G\":\n if d == \"N\": pos[1] += 1\n elif d == \"S\": pos[1] -= 1\n elif d == \"W\": pos[0] -= 1\n else: pos[0] += 1\n elif i == \"L\":\n if d == \"N\": d = \"W\"\n elif d == \"W\": d = \"S\"\n elif d == \"S\": d = \"E\"\n else: d = \"N\"\n else:\n if d == \"N\": d = \"E\"\n elif d == \"W\": d = \"N\"\n elif d == \"S\": d = \"W\"\n else: d = \"S\"\n return (d, pos)\n for i in range(4):\n d, pos = (move(d, pos, instructions))\n return True if pos == [0,0] else False", "solution_js": "var isRobotBounded = function(instructions) {\n // north = 0, east = 1, south = 2, west = 3\n let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n // Initial position is in the center\n let x = 0, y = 0;\n // facing north\n let idx = 0;\n let movements = [...instructions];\n\n for (let move of movements) {\n if (move == 'L')\n idx = (idx + 3) % 4;\n else if (move == 'R')\n idx = (idx + 1) % 4;\n else {\n x += directions[idx][0];\n y += directions[idx][1];\n }\n }\n\n // after one cycle:\n // robot returns into initial position\n // or robot doesn't face north\n return (x == 0 && y == 0) || (idx != 0);\n};", "solution_java": "class Solution {\n public boolean isRobotBounded(String instructions) {\n if (instructions.length() == 0) {\n return true;\n }\n\n Robot bender = new Robot();\n int[] start = new int[]{0, 0};\n\n // 4 represents the max 90 degree turns that can restart initial orientation.\n for (int i = 0; i < 4; i++) {\n boolean orientationChanged = bender.performSet(instructions);\n\n int[] location = bender.location;\n if (location[0] == start[0] && location[1] == start[1]) {\n return true;\n }\n\n // If robot never turns and the first instruction isn't at start, exit.\n else if (!orientationChanged) {\n return false;\n }\n }\n\n return false;\n }\n}\n\nclass Robot {\n int[] location;\n int[] orientation;\n int[][] orientations;\n int orientationPos;\n boolean orientationChangeCheck;\n\n Robot() {\n // Start in center\n location = new int[]{0, 0};\n\n // N, E, S, W\n orientations = new int[][]{{1,0}, {0, 1}, {-1, 0}, {0, -1}};\n\n // Start pointing north\n orientationPos = 0;\n orientation = orientations[orientationPos];\n\n // Track if robot has turned\n orientationChangeCheck = false;\n }\n\n public boolean performSet(String orders) {\n this.orientationChangeCheck = false;\n\n for (int i = 0; i < orders.length(); i++) {\n this.perform(orders.charAt(i));\n }\n\n return this.orientationChangeCheck;\n }\n\n public void perform(char order) {\n if (order == 'G') {\n this.go();\n } else if (order == 'L' || order == 'R') {\n this.turn(order);\n } else {\n // do nothing\n }\n }\n\n public void turn(char direction) {\n if (direction == 'L') {\n this.orientationPos = this.orientationPos == 0 ? 3 : this.orientationPos - 1;\n } else if (direction == 'R') {\n this.orientationPos = (this.orientationPos + 1) % 4;\n }\n\n this.orientation = this.orientations[this.orientationPos];\n this.orientationChangeCheck = true;\n }\n\n public int[] go() {\n this.location[0] += this.orientation[0];\n this.location[1] += this.orientation[1];\n return this.location;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isRobotBounded(string instructions) {\n char direction = 'N';\n int x = 0, y = 0;\n for (char &instruction: instructions) {\n if (instruction == 'G') {\n if (direction == 'N') y++;\n else if (direction == 'S') y--;\n else if (direction == 'W') x--;\n else x++;\n } else if (instruction == 'L') {\n if (direction == 'N') direction = 'W';\n else if (direction == 'S') direction = 'E';\n else if (direction == 'W') direction = 'S';\n else direction = 'N';\n } else {\n if (direction == 'N') direction = 'E';\n else if (direction == 'S') direction = 'W';\n else if (direction == 'W') direction = 'N';\n else direction = 'S';\n }\n }\n return (x == 0 && y == 0) || direction != 'N';\n }\n};" }, { "title": "Contains Duplicate", "algo_input": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\n\n \nExample 1:\nInput: nums = [1,2,3,1]\nOutput: true\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: false\nExample 3:\nInput: nums = [1,1,1,3,3,4,3,2,4,2]\nOutput: true\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return len(nums) != len(set(nums))", "solution_js": "var containsDuplicate = function(nums) {\n if(nums.length <= 1) return false;\n let cache = {};\n let mid = Math.floor(nums.length /2)\n let left = mid -1;\n let right = mid;\n while(left >= 0 || right < nums.length) {\n if(nums[left] === nums[right]) {\n return true;\n };\n if(cache[nums[left]]){\n return true\n } else {\n cache[nums[left]] = true; \n }\n if(cache[nums[right]]){\n return true;\n } else{\n cache[nums[right]] = true;\n }\n left--;\n right++;\n }\n return false;\n};", "solution_java": "class Solution {\n public boolean containsDuplicate(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int i = 1; i < n; i++) {\n if (nums[i] == nums[i - 1])\n return true;\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool containsDuplicate(vector& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n for (int i=0; i 0:\n self.total[v] = self.xs[tr + 1] - self.xs[tl]\n else:\n self.total[v] = self.total[v*2] + self.total[v*2+1]\n return self.total[v]\n\nclass Solution:\n def rectangleArea(self, rectangles):\n #index i means the interval from xs[i] to xs[i+1]\n xs = sorted(set([x for x1, y1, x2, y2 in rectangles for x in [x1, x2]]))\n xs_i = {x:i for i, x in enumerate(xs)}\n st = SegmentTree(xs)\n L = []\n for x1, y1, x2, y2 in rectangles:\n L.append([y1, 1, x1, x2])\n L.append([y2, -1, x1, x2])\n L.sort()\n cur_y = cur_x_sum = area = 0\n for y, open_close, x1, x2 in L:\n area += (y - cur_y) * cur_x_sum\n cur_y = y\n #one index corresponds to one interval, that's why we use xs_i[x2]-1 instead of xs_i[x2]\n st.update(1, 0, len(xs) - 1, xs_i[x1], xs_i[x2]-1, open_close)\n cur_x_sum = st.total[1]\n\n return area % (10 ** 9 + 7)", "solution_js": "var rectangleArea = function(rectangles) {\n let events = [], active = [], area = 0n;\n let mod = BigInt(1000000007);\n for (var rec of rectangles) {\n events.push([rec[1], 'open', rec[0], rec[2]]);\n events.push([rec[3], 'close', rec[0], rec[2]]);\n } \n events = events.sort((a, b) => a[0] - b[0]);\n let y = events[0][0];\n for (var event of events) {\n let currY = event[0], type = event[1], x1 = event[2], x2 = event[3];\n let maxLength = 0, curr = -1;\n for (var ev of active) {\n curr = Math.max(curr, ev[0]);\n maxLength += Math.max(0, ev[1] - curr);\n curr = Math.max(curr, ev[1]);\n }\n area += (BigInt(maxLength) * BigInt(currY - y));\n area %= mod;\n if (type === 'open') {\n active.push([x1, x2]);\n active = active.sort((a, b) => a[0] - b[0]);\n } else {\n for (var i = 0; i < active.length; i++) {\n let e = active[i];\n if (e[0] === x1 && e[1] === x2) {\n active.splice(i, 1);\n break;\n }\n }\n }\n y = currY;\n }\n return area % mod;\n};", "solution_java": "class Solution {\n public int rectangleArea(int[][] rectangles) {\n int n = rectangles.length;\n Set coorx = new HashSet<>();\n Set coory = new HashSet<>();\n for (int[] rec : rectangles) {\n coorx.add(rec[0]); coorx.add(rec[2]);\n coory.add(rec[1]); coory.add(rec[3]);\n }\n\n Integer[] compressx = coorx.toArray(new Integer[0]);\n Arrays.sort(compressx);\n Integer[] compressy = coory.toArray(new Integer[0]);\n Arrays.sort(compressy);\n\n Map mapx = new HashMap<>();\n for(int i = 0; i < compressx.length; i++) {\n mapx.put(compressx[i], i);\n }\n Map mapy = new HashMap<>();\n for(int i = 0; i < compressy.length; i++) {\n mapy.put(compressy[i], i);\n }\n\n boolean[][] grid = new boolean[compressx.length][compressy.length];\n for (int[] rec: rectangles) {\n for (int x = mapx.get(rec[0]); x < mapx.get(rec[2]); x++) {\n for (int y = mapy.get(rec[1]); y < mapy.get(rec[3]); y++) {\n grid[x][y] = true;\n }\n }\n }\n\n long res = 0L;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j]) {\n res += (long)(compressx[i + 1] - compressx[i]) * (compressy[j + 1] - compressy[j]);\n }\n }\n }\n res %= 1000000007;\n return (int)res;\n }\n }", "solution_c": "struct Point\n{\n int X;\n int delta;\n};\n\nclass Solution\n{\npublic:\n int rectangleArea(vector>& rectangles)\n {\n map> lines; // y -> array of Points\n for (auto&r : rectangles)\n {\n auto x1 = r[0];\n auto y1 = r[1];\n auto x2 = r[2];\n auto y2 = r[3];\n\n lines[y1].push_back(Point {x1, +1});\n lines[y1].push_back(Point {x2, -1});\n lines[y2].push_back(Point {x1, -1});\n lines[y2].push_back(Point {x2, +1});\n }\n\n long area = 0;\n int prevy = 0;\n int length = 0;\n\n map scanline; // x -> delta\n for (const auto& [y, points] : lines)\n {\n area += (y - prevy) * (long)length;\n\n // Update scanline for new y: add new rectanhgles,\n // remove old\n for (auto point : points)\n {\n auto xdelta = scanline.find(point.X);\n if (xdelta != end(scanline))\n {\n xdelta->second += point.delta;\n if (xdelta->second == 0)\n scanline.erase(xdelta);\n }\n else\n scanline[point.X] = point.delta;\n }\n\n // For current y-line calc the length of\n // intersection with rectangles\n int startX = -1;\n int rectCount = 0;\n length = 0;\n for (const auto& [x, delta] : scanline)\n {\n int oldcount = rectCount;\n rectCount += delta;\n if (oldcount == 0)\n startX = x;\n else if (rectCount == 0)\n length += x - startX;\n }\n\n if (rectCount > 0)\n length += scanline.rbegin()->first - startX;\n\n prevy = y;\n }\n\n return area % (1000000007);\n }\n};" }, { "title": "Maximum Sum BST in Binary Tree", "algo_input": "Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).\n\nAssume a BST is defined as follows:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than the node's key.\n\tBoth the left and right subtrees must also be binary search trees.\n\n\n \nExample 1:\n\n\n\nInput: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput: 20\nExplanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n\n\nExample 2:\n\n\n\nInput: root = [4,3,null,1,2]\nOutput: 2\nExplanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n\n\nExample 3:\n\nInput: root = [-4,-2,-5]\nOutput: 0\nExplanation: All values are negatives. Return an empty BST.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 4 * 104].\n\t-4 * 104 <= Node.val <= 4 * 104\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 maxSumBST(self, root: Optional[TreeNode]) -> int:\n # declaire a variable maxSum to hold the max path sum\n self.maxSum=0\n def getMax(root):\n # return max,min,val - if root is null, valid BST\n if not root : return (float(\"-inf\"),float(\"inf\"),0)\n # traverse left and right part\n leftMax,leftMin,leftMaxSum=getMax(root.left)\n rightMax,rightMin,rightMaxSum=getMax(root.right)\n # if a valid BST\n if root.val>leftMax and root.val {\n // NoNode\n if(!node) return [true, 0, Infinity, -Infinity];\n\n // LeafNode\n if(node && !node.left && !node.right) {\n max = Math.max(max, node.val);\n return [true, node.val, node.val, node.val]\n };\n\n const [isLeftValid, leftVal, leftMin, leftMax] = dfs(node.left);\n const [isRightValid, rightVal, rightMin, rightMax] = dfs(node.right);\n\n /**\n * To establish that the current node is also a valid BST, we need to verify the following:\n * 1. Left sub tree is a valid BST\n * 2. Right sub tree is a valid BST\n * 3. The values in the left BST are smaller than current node's value\n * 4. The values in the right BST are greater than current node's value\n **/\n if(isLeftValid && isRightValid && node.val > leftMax && node.val < rightMin) {\n max = Math.max(max, leftVal + rightVal + node.val);\n return [\n true,\n leftVal + rightVal + node.val,\n /**\n * 12\n * / \\\n * 8 16\n * \\ /\n * 9 15\n * \\ /\n * 10 14\n * \\ /\n * Infinity -Infinity\n * [Infinity and -Infinity are to depict NoNode cases]\n **/\n Math.min(node.val, leftMin),\n Math.max(node.val, rightMax)\n ];\n }\n\n return [false, 0, leftMax, rightMin];\n }\n dfs(root);\n\n return max;\n};", "solution_java": "class Solution {\n\n int ans = 0;\n public int maxSumBST(TreeNode root) {\n solve(root);\n return ans;\n }\n // int[] = { min, max, sum };\n private int[] solve(TreeNode root) {\n if(root == null)\n return new int[] { Integer.MAX_VALUE, Integer.MIN_VALUE, 0 };\n\n int[] left = solve(root.left);\n int[] right = solve(root.right);\n\n if(root.val > left[1] && root.val < right[0]) {\n int sum = left[2] + right[2] + root.val;\n ans = Math.max(ans, sum);\n return new int[] { Math.min(left[0], root.val), Math.max(root.val, right[1]), sum };\n }\n\n return new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, 0 };\n }\n\n}", "solution_c": "class Solution {\npublic:\n int ans = 0 ;\n\n array solve(TreeNode * root){\n if(!root) return {1,0,INT_MIN,INT_MAX} ;\n\n array l = solve(root->left) ;\n array r = solve(root->right) ;\n\n if(l[0] and r[0]){\n if(root->val > l[2] and root->val < r[3]){\n ans = max({ans,l[1],r[1]}) ;\n return {1,l[1] + r[1] + root->val,max({root->val,l[2],r[2]}),min({root->val,l[3],r[3]})} ;\n }\n }\n\n return {0,max(l[1],r[1]),INT_MIN,INT_MAX} ;\n }\n\n int maxSumBST(TreeNode* root) {\n auto arr = solve(root) ;\n return max(ans,arr[1]) ;\n }\n};" }, { "title": "Intersection of Two Arrays", "algo_input": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique 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]\n\n\nExample 2:\n\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [9,4]\nExplanation: [4,9] 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", "solution_py": "class Solution:\n def intersection(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 if len(ans) == 0 or nums1[i] != ans[-1]:\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 intersection = function(nums1, nums2) {\n let set = new Set(nums1);\n let set2 = new Set(nums2);\n let result = [];\n for (const val of set) {\n if (set2.has(val)) {\n result.push(val);\n }\n }\n return result;\n};", "solution_java": "class Solution {\n public int[] intersection(int[] nums1, int[] nums2) {\n int[] dp = new int[1000];\n for(int i:nums1){\n dp[i]++;\n }\n int[] ans = new int[1000];\n\n //declaring ptr to track ans array index\n int ptr = 0;\n for(int i:nums2){\n if(dp[i] != 0){\n dp[i] = 0;\n ans[ptr] = i;\n ptr++;\n }\n }\n return Arrays.copyOfRange(ans, 0, ptr);\n }\n}", "solution_c": "class Solution {\npublic:\n //what i think is we have to return the intersection elements from both nums\n vector intersection(vector& nums1, vector& nums2) {\n\n //result vector which will store those values which will be intersecting in both nums\n vector result;\n\n //map intersection, which will store values of all the elements in num1\n unordered_map intersection;\n\n //map will store all the values of num1(as key),with corresponding value 1\n for(auto character : nums1)\n {\n intersection[character] = 1;\n }\n\n //this loop will check if any element of num1 is there in num2? if yes, insert it in result\n //after inserting it once, make its corresponding value to 0\n //so that if you find any elements, that is repeating in num2, as well as present in num1\n //so you dont enter it twice in result, you should enter it once only\n for(auto character : nums2)\n {\n //if found once, it's value would be 1, so entered in result\n //after it is entered in result, its value we change to 0\n //so agin if that same element repeats, due to 0 as its value, we avoid pushing it to result\n if(intersection[character])\n {\n result.push_back(character);\n intersection[character] = 0;\n }\n }\n\n //after getting all the intersecting elements,we return result\n return result;\n }\n};" }, { "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree", "algo_input": "Given two binary trees original and cloned and given a reference to a node target in the original tree.\n\nThe cloned tree is a copy of the original tree.\n\nReturn a reference to the same node in the cloned tree.\n\nNote that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.\n\n \nExample 1:\n\nInput: tree = [7,4,3,null,null,6,19], target = 3\nOutput: 3\nExplanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\n\n\nExample 2:\n\nInput: tree = [7], target = 7\nOutput: 7\n\n\nExample 3:\n\nInput: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput: 4\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\tThe values of the nodes of the tree are unique.\n\ttarget node is a node from the original tree and is not null.\n\n\n \nFollow up: Could you solve the problem if repeated values on the tree are allowed?\n", "solution_py": "class Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n def DFS(node1,node2):\n if node1==target:\n return node2\n if node1 and node1.left is None and node1.right is None:\n return\n\n res1 = DFS(node1.left,node2.left) if node1 else None\n if res1 is not None:\n return res1\n res2 = DFS(node1.right,node2.right) if node1 else None\n if res2 is not None:\n return res2\n res=DFS(original,cloned)\n return res", "solution_js": "var getTargetCopy = function(original, cloned, target) {\n \n if( original == null ){\n \n // Base case aka stop condition\n // empty tree or empty node\n return null;\n }\n \n // General cases\n if( original == target ){\n \n // current original node is target, so is cloned\n return cloned;\n }\n \n // Either left subtree has target, or right subtree has target\n return getTargetCopy(original.left, cloned.left, target) || \n getTargetCopy(original.right, cloned.right, target);\n \n};", "solution_java": "class Solution {\n public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {\n TreeNode[] ref = new TreeNode[]{null};\n dfs(cloned, target, ref);\n return ref[0];\n }\n public static void dfs (TreeNode root, TreeNode target, TreeNode[] ref) {\n if (root == null) return;\n if (root.val == target.val) {\n ref[0] = root;\n return;\n } else {\n dfs(root.left, target, ref);\n dfs(root.right, target, ref);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) {\n if(original == target || original == NULL)\n return cloned;\n TreeNode* found_left = getTargetCopy(original->left, cloned->left, target);\n TreeNode* found_right = getTargetCopy(original->right, cloned->right, target);\n if(found_left)\n return found_left;\n else\n return found_right;\n }\n};" }, { "title": "Average Salary Excluding the Minimum and Maximum Salary", "algo_input": "You are given an array of unique integers salary where salary[i] is the salary of the ith employee.\n\nReturn the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.\n\n \nExample 1:\n\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500\n\n\nExample 2:\n\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000\n\n\n \nConstraints:\n\n\n\t3 <= salary.length <= 100\n\t1000 <= salary[i] <= 106\n\tAll the integers of salary are unique.\n\n", "solution_py": "class Solution:\n def average(self, salary: List[int]) -> float: \n\n return (sum(salary)-min(salary)-max(salary))/(len(salary)-2)", "solution_js": "var average = function(salary) {\n let max = salary[0], min = salary[salary.length-1], sum = 0;\n for(let i = 0; i < salary.length; i++) {\n if(salary[i] > max) {\n max = salary[i];\n }\n else if(salary[i] < min) {\n min = salary[i];\n }\n sum += salary[i];\n }\n return (sum-min-max)/(salary.length-2);\n};", "solution_java": "class Solution {\n public double average(int[] salary) {\n int n = salary.length-2;\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n int sum = 0;\n for(int i=0;i& salary) {\n int n = salary.size();\n double ans=0;\n sort(salary.begin(),salary.end());\n for(int i=1;i bool:\n # The two criteria for a valid board are:\n # 1) num of Xs - num of Os is 0 or 1\n # 2) X is not a winner if the # of moves is even, and\n # O is not a winner if the # of moves is odd.\n\n d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array\n s = [d[ch] for ch in ''.join(board)] # Ex: [\"XOX\",\" X \",\" \"] --> [1,-1,1,0,1,0,0,0,0]\n sm = sum(s)\n\n if sm>>1: return False # <-- criterion 1\n \n n = -3 if sm == 1 else 3 # <-- criterion 2.\n if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], \n s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are \n s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags\n \n return True # <-- both criteria are true", "solution_js": "var validTicTacToe = function(board) {\n let playerX = 0 , playerO = 0;\n let horizontal = [0,0,0];\n let vertical = [0,0,0];\n let diagnol = [0, 0];\n \n const transformConfig=(row,col,val)=>{\n horizontal[row] +=val; \n vertical[col]+=val;\n if(row ===col ){\n diagnol[0]+=val; \n if(row+col == board.length-1){\n diagnol[1]+=val; \n }\n }else if(row+col == board.length-1){\n diagnol[1]+=val; \n }\n }\n \n board.forEach((data,row)=>{\n data.split(\"\").forEach((turn,col)=>{\n if(turn == 'X'){\n playerX++\n transformConfig(row,col,1)\n }else if(turn == 'O'){\n playerO++;\n transformConfig(row,col,-1);\n }\n });\n });\n if(playerX1 ) return false;\n if(horizontal.includes(3)&&playerX<= playerO)return false;\n if(vertical.includes(3)&&playerX <= playerO)return false;\n if(diagnol.includes(3)&&playerX <=playerO)return false;\n if(horizontal.includes(-3)&&playerX> playerO)return false;\n if(vertical.includes(-3)&&playerX> playerO)return false;\n if(diagnol.includes(-3)&&playerX>playerO)return false;\n \n return true;\n};", "solution_java": "class Solution {\n public boolean validTicTacToe(String[] board) {\n //cnt number of X and O\n int x = cntNumber('X', board);\n //this check can be omitted, it can be covered in the second number check.\n if(x >5){\n return false;\n }\n int o = cntNumber('O', board);\n if(x < o || x > o + 1){\n return false;\n }\n //if(x <3 ) true, no need to see winning\n if(o >= 3){\n //if x has won, but game doesnt stop\n if(x == o && hasWon('X', board)){\n return false;\n }\n //if o has won, but game doesnt stop\n if( x > o && hasWon('O', board) ){\n return false;\n }\n }\n return true;\n }\n\n private int cntNumber(char target, String[] board){\n int res = 0;\n for(int i = 0; i<3; i++) {\n for(int j = 0; j<3; j++) {\n if(target == board[i].charAt(j)){\n res++;\n }\n }\n }\n return res;\n }\n\n private boolean hasWon(char target, String[] board){\n String toWin = Character.toString(target).repeat(3);\n for(int i = 0; i<3; i++) {\n if(board[i].equals(toWin)){\n return true;\n }\n }\n for(int j = 0; j<3; j++) {\n boolean col = true;\n for(int i = 0; i<3; i++) {\n col = col && target == board[i].charAt(j);\n if(!col){\n break;\n }\n }\n if(col){\n return true;\n }\n }\n //check diagonal. If center is not target, not possible to form diag win.\n if(target != board[1].charAt(1)){\n return false;\n }\n\n boolean diagonal1 = target == board[0].charAt(0);\n //only proceed if the first letter match. Otherwise might get false positive\n if(diagonal1){\n if(target == board[2].charAt(2)){\n return true;\n }\n }\n\n boolean diagonal2 = target == board[0].charAt(2);\n if(diagonal2){\n if(target == board[2].charAt(0)){\n return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n \n bool win(vector board, char player, int size){\n int row_win=0, col_win=0, diagonal_win=0, rev_diagonal_win=0;\n \n for(int i=0;i<3;i++){\n \n row_win=0; \n col_win=0;\n \n for(int j=0;j<3;j++){\n \n if(player == board[i][j]){\n row_win++; \n if(row_win == 3)\n return 1;\n }\n \n if(player == board[j][i]){\n col_win++;\n if(col_win == 3)\n return 1;\n }\n \n if(i==j && player==board[i][j]){\n diagonal_win++;\n }\n \n if(i+j == size-1 && player==board[i][j]){\n rev_diagonal_win++;\n }\n \n }\n }\n \n if(diagonal_win==3 || rev_diagonal_win==3)\n return 1;\n \n return 0;\n }\n \n bool validTicTacToe(vector& board) {\n int count_x=0, count_o=0, size = board.size();\n for(auto i:board){\n for(auto j:i){\n if(j=='X') count_x++;\n else if(j=='O') count_o++;\n }\n }\n if(count_o>count_x || count_x-count_o>=2)\n return false;\n if(count_x>=3 && count_x==count_o && win(board, 'X', size))\n return false;\n if(count_o>=3 && count_x>count_o && win(board, 'O', size))\n return false;\n \n return true;\n }\n};" }, { "title": "Number of Visible People in a Queue", "algo_input": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.\n\nA person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).\n\nReturn an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.\n\n \nExample 1:\n\n\n\nInput: heights = [10,6,8,5,11,9]\nOutput: [3,1,2,1,1,0]\nExplanation:\nPerson 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.\n\n\nExample 2:\n\nInput: heights = [5,1,2,3,10]\nOutput: [4,1,1,1,0]\n\n\n \nConstraints:\n\n\n\tn == heights.length\n\t1 <= n <= 105\n\t1 <= heights[i] <= 105\n\tAll the values of heights are unique.\n\n", "solution_py": "class Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans=[]\n stack=[]\n n=len(heights)\n for i in range(n-1,-1,-1):\n if len(stack)==0:\n ans.append(0)\n stack.append(heights[i])\n else:\n if heights[i]0 and stack[-1]= 0){ \n let popCount = 0\n \n // Keep Popping untill top ele is smaller\n while(stack.length > 0 && stack[stack.length-1][0] < heights[i]){\n\t\t\tstack.pop()\n popCount+=1\n }\n \n /////////////////////\n /// After Popping ///\n ////////////////////\n \n // Case1: if ALL elements got popped\n if(stack.length === 0)\n result[i] = popCount // mark\n \n // Case2: if NO elements were popped\n else if(popCount === 0)\n result[i] = 1 // mark\n \n // Case3: if SOME elements were popped\n else\n result[i] = popCount+1 // mark\n \n // store\n stack.push([heights[i],popCount])\n \n i-=1\n }\n \n return result\n}\nvar canSeePersonsCount = function(heights) {\n return visibleToRight(heights)\n};", "solution_java": "class Solution {\n public int[] canSeePersonsCount(int[] heights) {\n Stack stack = new Stack<>();\n int result[] = new int[heights.length];\n for(int i = heights.length - 1; i >= 0; i--) {\n int visibility = 0;\n while(!stack.isEmpty() && heights[i] > stack.peek()) {\n stack.pop();\n visibility++;\n }\n if(!stack.isEmpty()) visibility++;\n stack.push(heights[i]);\n result[i] = visibility;\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector canSeePersonsCount(vector& h) {\n vectorans ;\n stacks ;\n int a = 0;\n for(int i = h.size()-1 ; i >= 0 ; i--){\n if(s.empty()){\n ans.push_back(a);\n s.push(h[i]);a++;\n }\n else{\n if(s.top() > h[i]){\n ans.push_back(1);\n s.push(h[i]);a++;\n }\n else{\n int b = 0;\n while(!s.empty() && s.top() < h[i]){\n s.pop() ; a--;b++;\n }\n if(!s.empty())b++;\n ans.push_back(b);\n s.push(h[i]); a++;\n } \n }\n }\n reverse(ans.begin() , ans.end());\n return ans;\n }\n};" }, { "title": "Largest Number After Mutating Substring", "algo_input": "You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].\n\nYou may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\n\nReturn a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.\n\nA substring is a contiguous sequence of characters within the string.\n\n \nExample 1:\n\nInput: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\nOutput: \"832\"\nExplanation: Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.\n\n\nExample 2:\n\nInput: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\nOutput: \"934\"\nExplanation: Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.\n\n\nExample 3:\n\nInput: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\nOutput: \"5\"\nExplanation: \"5\" is already the largest number that can be created, so return it.\n\n\n \nConstraints:\n\n\n\t1 <= num.length <= 105\n\tnum consists of only digits 0-9.\n\tchange.length == 10\n\t0 <= change[d] <= 9\n\n", "solution_py": "class Solution:\ndef maximumNumber(self, num: str, change: List[int]) -> str:\n flag=0\n ls=list(num)\n for i in range(len(ls)):\n k=int(ls[i])\n if change[k]>k:\n ls[i]=str(change[k])\n flag=1\n elif flag==1 and change[k] origDig) {\n started = true;\n digits[i] = changeDig;\n }\n else if (changeDig < origDig && started) {\n break;\n }\n }\n\n return digits.join(\"\");\n};", "solution_java": "class Solution {\n public String maximumNumber(String num, int[] change) {\n int i=0, n=num.length(), startIndex=-1, substringLength=0;\n \n // traverse through each digit in the input string\n while(i digit) {\n startIndex = i;\n // keep on replacing subsequent characters with with the change if they also have greater change\n while(i=startIndex && j& change){\n int n=num.size();\n for(int i=0;i List[str]:\n first_row = \"qwertyuiopQWERTYUIOP\"\n second_row = \"asdfghjklASDFGHIJKL\"\n third_row = \"zxcvbnmZXCVBNM\"\n first_list = []\n second_list = []\n third_list = []\n one_line_words = []\n\n for word in words:\n if set(word).issubset(first_row):\n one_line_words.append(word)\n if set(word).issubset(second_row):\n one_line_words.append(word)\n if set(word).issubset(third_row):\n one_line_words.append(word)\n\n return one_line_words", "solution_js": "var findWords = function(words) {\nconst firstRow = {\"q\":true,\"w\":true,\"e\":true,\"r\":true,\"t\":true,\"y\":true,\"u\":true,\"i\":true,\"o\":true,\"p\":true }\nconst secondRow = {\"a\":true,\"s\":true,\"d\":true,\"f\":true,\"g\":true,\"h\":true,\"j\":true,\"k\":true,\"l\":true }\nconst thirdRow = {\"z\":true,\"x\":true,\"c\":true,\"v\":true,\"b\":true,\"n\":true,\"m\":true }\nlet result = [];\n\nconst helperFunc= (word)=>{\n let targetRow;\n //Determine in which row the word should be;\n if(firstRow[word[0].toLowerCase()]) targetRow = firstRow;\n if(secondRow[word[0].toLowerCase()]) targetRow = secondRow;\n if(thirdRow[word[0].toLowerCase()]) targetRow = thirdRow;\n \n for(let i = 1;i parent, size;\n\n vector Q{'q','w','e','r','t','y','u','i','o','p','Q','W','E','R','T','Y','U','I','O','P'};\n vector A{'a','s','d','f','g','h','j','k','l','A','S','D','F','G','H','J','K','L'};\n vector Z{'z','x','c','v','b','n','m','Z','X','C','V','B','N','M'};\n\npublic:\n DSU(){\n for(int i= 0;i<123;i++) parent.push_back(i),size.push_back(1);\n for(int i = 0; isize[a]) swap(a,b);parent[b] = a,size[a]+=size[b];\n }\n};\n\nclass Solution {\npublic:\n vector findWords(vector& words) {\n int n = words.size();\n DSU dsu;\n vector ans;\n for(int i = 0;i= nums[deq[-1]]: deq.pop()\n deq.append(i)\n \n return nums[-1]", "solution_js": "var maxResult = function(nums, k) {\n let n = nums.length, deq = [n-1]\n for (let i = n - 2; ~i; i--) {\n if (deq[0] - i > k) deq.shift()\n nums[i] += nums[deq[0]]\n while (deq.length && nums[deq[deq.length-1]] <= nums[i]) deq.pop()\n deq.push(i)\n }\n return nums[0] \n};", "solution_java": "class Solution {\n public int maxResult(int[] nums, int k) {\n int n = nums.length, a = 0, b = 0;\n int[] deq = new int[n];\n deq[0] = n - 1;\n for (int i = n - 2; i >= 0; i--) {\n if (deq[a] - i > k) a++;\n nums[i] += nums[deq[a]];\n while (b >= a && nums[deq[b]] <= nums[i]) b--;\n deq[++b] = i;\n }\n return nums[0];\n }\n}", "solution_c": "#define pii pair\nclass Solution {\npublic:\n int maxResult(vector& nums, int k)\n {\n int n=nums.size();\n int score[n];\n priority_queue pq;\n \n for(int i=n-1 ; i>=0 ; i--)\n {\n while(pq.size() && pq.top().second>i+k)\n pq.pop();\n \n score[i]=nums[i];\n score[i]+=(pq.size() ? pq.top().first : 0);\n pq.push({score[i], i});\n }\n \n return score[0];\n }\n};" }, { "title": "Check If a String Can Break Another String", "algo_input": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.\n\nA string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.\n\n \nExample 1:\n\nInput: s1 = \"abc\", s2 = \"xya\"\nOutput: true\nExplanation: \"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".\n\n\nExample 2:\n\nInput: s1 = \"abe\", s2 = \"acd\"\nOutput: false \nExplanation: All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\n\n\nExample 3:\n\nInput: s1 = \"leetcodee\", s2 = \"interview\"\nOutput: true\n\n\n \nConstraints:\n\n\n\ts1.length == n\n\ts2.length == n\n\t1 <= n <= 10^5\n\tAll strings consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n s1, s2 = sorted(s1), sorted(s2)\n return all(a1 >= a2 for a1, a2 in zip(s1, s2)) or all(a1 <= a2 for a1, a2 in zip(s1, s2))", "solution_js": "const canAbreakB = (s1, s2) => {\n const s1Heap = new MinPriorityQueue();\n const s2Heap = new MinPriorityQueue();\n \n for(let c of s1) {\n s1Heap.enqueue(c.charCodeAt(0));\n }\n \n for(let c of s2) {\n s2Heap.enqueue(c.charCodeAt(0));\n }\n \n while(s2Heap.size()) {\n const s1Least = s1Heap.dequeue().element;\n const s2Least = s2Heap.dequeue().element;\n if(s1Least > s2Least) {\n return false;\n }\n }\n return true;\n}\n\nvar checkIfCanBreak = function(s1, s2) {\n return canAbreakB(s1, s2) || canAbreakB(s2, s1);\n};", "solution_java": "class Solution {\n public boolean checkIfCanBreak(String s1, String s2) {\n int n = s1.length();\n char[] one = s1.toCharArray();\n char[] two = s2.toCharArray();\n Arrays.sort(one);\n Arrays.sort(two);\n if(check(one,two,n) || check(two,one,n)){\n return true;\n }\n return false;\n }\n public boolean check(char[] one,char[] two,int n){\n for(int i=0;itwo[i]-'a'){\n return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n\n bool checkIfCanBreak(string s1, string s2)\n {\n vectorfreq1(26,0),freq2(26,0);\n for(int i=0;i int:\n\t\treturn 0 if 0 in nums else -1 if sum(x < 0 for x in nums) % 2 else 1", "solution_js": "var arraySign = function(nums) {\n // use filter to find total negative numbers in the array\n let negativeCount = nums.filter(n => n<0).length;\n\n // check if the nums array has zero. If it does, then return 0\n if(nums.includes(0)) return 0;\n\n // If negativeCount variable is even answer is 1 else -1\n return negativeCount % 2 === 0 ? 1 : -1\n};", "solution_java": "class Solution {\n public int arraySign(int[] nums) {\n int prod=1;\n for(int i=0;i0) return 1;\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n int arraySign(vector& nums) {\n int res = 1;\n for(auto x : nums)\n {\n if(x < 0) res *= -1;\n else if(x == 0) return 0;\n }\n return res;\n }\n};" }, { "title": "Flip Binary Tree To Match Preorder Traversal", "algo_input": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.\n\nAny node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:\n\nFlip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.\n\nReturn a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].\n\n \nExample 1:\n\nInput: root = [1,2], voyage = [2,1]\nOutput: [-1]\nExplanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\n\n\nExample 2:\n\nInput: root = [1,2,3], voyage = [1,3,2]\nOutput: [1]\nExplanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\n\nExample 3:\n\nInput: root = [1,2,3], voyage = [1,2,3]\nOutput: []\nExplanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\tn == voyage.length\n\t1 <= n <= 100\n\t1 <= Node.val, voyage[i] <= n\n\tAll the values in the tree are unique.\n\tAll the values in voyage are unique.\n\n", "solution_py": "class Solution:\n def flipMatchVoyage(self, root, voyage):\n \n # ------------------------------\n \n def dfs(root):\n \n if not root:\n # base case aka stop condition\n\t\t\t\t# empty node or empty tree\n return True\n \n \n ## general cases\n if root.val != voyage[dfs.idx]:\n \n # current node mismatch, no chance to make correction by flip\n return False\n \n # voyage index moves forward\n dfs.idx += 1\n \n if root.left and (root.left.val != voyage[dfs.idx]):\n \n # left child mismatch, flip with right child if right child exists\n root.right and result.append( root.val )\n \n # check subtree in preorder DFS with child node flip\n return dfs(root.right) and dfs(root.left)\n \n else:\n \n # left child match, check subtree in preorder DFS\n return dfs(root.left) and dfs(root.right)\n \n \n # --------------------------\n \n # flip sequence\n result = []\n \n # voyage index during dfs\n dfs.idx = 0\n \n # start checking from root node\n good = dfs(root)\n \n return result if good else [-1]", "solution_js": "var flipMatchVoyage = function(root, voyage) {\n const output = []\n let idx = 0;\n \n function run(node) {\n if(!node) return true;\n if(voyage[idx] !== node.val) return false;\n idx++;\n \n if(node.left && node.left.val !== voyage[idx]) {\n output.push(node.val);\n return run(node.right) && run(node.left);\n }\n return run(node.left) && run(node.right);\n }\n return run(root) ? output : [-1];\n};", "solution_java": "class Solution {\n private int i = 0;\n \n public List flipMatchVoyage(TreeNode root, int[] voyage) {\n List list = new ArrayList<>();\n flipMatchVoyage(root,voyage,list);\n return list;\n }\n \n private void flipMatchVoyage(TreeNode root, int[] voyage,List list) {\n if(root == null || list.contains(-1)){\n return;\n }\n if(root.val != voyage[i++]){\n list.clear();\n list.add(-1);\n return;\n }\n if(root.left != null && root.right != null && root.left.val != voyage[i]){\n list.add(root.val);\n flipMatchVoyage(root.right,voyage,list);\n flipMatchVoyage(root.left,voyage,list);\n return;\n }\n flipMatchVoyage(root.left,voyage,list); \n flipMatchVoyage(root.right,voyage,list);\n }\n}", "solution_c": "class Solution {\npublic:\n\n bool helper(int &ind, TreeNode *root, vector &voyage, vector &ans){\n if(root == NULL || ind == voyage.size()){\n ind--;\n return true;\n }\n\n // Not possible to create\n if(root->val != voyage[ind]){\n ans.clear();\n ans.push_back(-1);\n return false;\n }\n\n // If voyage value not equal to its left child, then swap both childs and check\n if(root->left && root->left->val != voyage[ind+1]){\n TreeNode *temp = root->left;\n root->left = root->right;\n root->right = temp;\n\n // Pusing root into ans\n ans.push_back(root->val);\n }\n\n return helper(++ind, root->left, voyage, ans) &&\n helper(++ind, root->right, voyage, ans);\n }\n\n vector flipMatchVoyage(TreeNode* root, vector& voyage) {\n int ind = 0;\n vector ans;\n helper(ind, root, voyage, ans);\n return ans;\n }\n};" }, { "title": "Next Greater Node In Linked List", "algo_input": "You are given the head of a linked list with n nodes.\n\nFor each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.\n\nReturn an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.\n\n \nExample 1:\n\nInput: head = [2,1,5]\nOutput: [5,5,0]\n\n\nExample 2:\n\nInput: head = [2,7,4,3,5]\nOutput: [7,0,5,5,0]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 <= n <= 104\n\t1 <= Node.val <= 109\n\n", "solution_py": "class Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n stack = []\n ans = []\n node = head\n \n i = 0\n while node is not None:\n while stack and stack[-1][0] < node.val:\n ans[stack[-1][1]] = node.val\n stack.pop()\n \n stack.append((node.val, i))\n ans.append(0)\n i += 1\n node = node.next\n \n return ans", "solution_js": "var nextLargerNodes = function(head) {\n let arr = [];\n while(head){\n arr.push(head.val);\n head = head.next\n }\n return nextGreaterElement(arr)\n \n};\n\nfunction nextGreaterElement(arr){\n let temp = [];\n let n = arr.length;\n let stack = [];\n for(let i=n-1; i>=0; i--){\n while(stack.length != 0 && arr[stack[stack.length-1]] <= arr[i]){\n stack.pop()\n }\n \n if(stack.length == 0){\n temp[i] = 0\n }else{\n temp[i] = arr[stack[stack.length-1]]\n }\n stack.push(i)\n }\n return temp\n}", "solution_java": "class Solution {\n public int[] nextLargerNodes(ListNode head) {\n ListNode length=head;\n int l=0;\n while(length!=null)\n {\n length=length.next;\n l++;\n }\n int[] res=new int[l];\n int i=0;\n ListNode temp=head;\n\n while(temp!=null)\n {\n ListNode temp1=temp.next;\n int max=temp.val;\n\n while(temp1!=null)\n {\n if(temp1.val>max)\n {\n max=temp1.val;\n res[i]=max;\n break;\n }\n\n temp1=temp1.next;\n }\n temp=temp.next;\n i++;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector nextLargerNodes(ListNode* head) {\n vector ans;\n ListNode* curr = head;\n if(head->next == NULL){\n ans.push_back(0);\n return ans;\n }\n\n while(curr != NULL){\n ListNode* next = curr->next;\n while(next != NULL){\n if(next->val > curr->val){\n ans.push_back(next->val);\n break;\n }\n next = next->next;\n }\n if(next == NULL){\n ans.push_back(0);\n }\n curr = curr->next;\n }\n return ans;\n }\n};" }, { "title": "Kth Missing Positive Number", "algo_input": "Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.\n\nReturn the kth positive integer that is missing from this array.\n\n \nExample 1:\n\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\n\n\nExample 2:\n\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 1000\n\t1 <= arr[i] <= 1000\n\t1 <= k <= 1000\n\tarr[i] < arr[j] for 1 <= i < j <= arr.length\n\n\n \nFollow up:\n\nCould you solve this problem in less than O(n) complexity?\n", "solution_py": "class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n arr = set(arr)\n i = 0\n missed = 0\n while missed != k:\n i += 1\n if i not in arr:\n missed += 1\n return i", "solution_js": "var findKthPositive = function(arr, k) {\n let newArr = [];\n for(let i=0,j=1; j<=arr.length+k; j++){\n arr[i]!=j?newArr.push(j):i++;\n }\n return newArr[k-1]; \n \n};", "solution_java": "class Solution {\n public int findKthPositive(int[] arr, int k) {\n if(arr[0] > k) {\n return k;\n }\n \n for(int i=0; i& arr, int k) {\n\n int n=arr.size();\n if(arr[n-1]==n)\n return n+k;\n else\n {\n int start=0;\n int end=n-1;\n int ans;\n while(start<=end)\n {\n int mid=start+(end-start)/2;\n if((arr[mid]-(mid+1))0:\n\t\t\tif self.q[i] > self.q[(i-1)//2]:\n\t\t\t\tself.q[i], self.q[(i-1)//2] = self.q[(i-1)//2], self.q[i]\n\t\t\t\ti = (i-1)//2\n\t\t\telse: return \n\tdef pop(self):\n\t\tif len(self.q)==0:return\n\t\tself.q[0] = self.q[-1]\n\t\tself.q.pop()\n\t\tdef heapify(i):\n\t\t\tind = i\n\t\t\tl = 2*i+1\n\t\t\tr = 2*i+2\n\t\t\tif r None:\n\t\tn = len(nums)\n\t\th = Heap()\n\t\tfor i in nums: h.push(i)\n\t\tfor i in range(1,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()\n\t\tfor i in range(0,n,2):\n\t\t\tnums[i] = h.top()\n\t\t\th.pop()", "solution_js": "var wiggleSort = function(nums) {\n nums.sort((a,b) => a - b);\n\n let temp = [...nums];\n\n let low = Math.floor((nums.length-1)/2), high = nums.length-1;\n\n for(let i=0; i < nums.length; i++){\n if(i % 2 === 0){\n nums[i] = temp[low];\n low--;\n }else{\n nums[i] = temp[high];\n high--;\n }\n }\n\n return nums;\n};", "solution_java": "class Solution {\n public void wiggleSort(int[] nums) {\n int a[]=nums.clone();\n Arrays.sort(a);\n int left=(nums.length-1)/2;\n int right=nums.length-1;\n for(int i=0;i& nums) {\n\n priority_queue pq;\n for(auto &i : nums)\n pq.push(i);\n\n for(int i = 1; i < nums.size(); i += 2)\n nums[i] = pq.top(), pq.pop();\n\n for(int i = 0; i < nums.size(); i += 2)\n nums[i] = pq.top(), pq.pop();\n }\n};" }, { "title": "Count Vowels Permutation", "algo_input": "Given an integer n, your task is to count how many strings of length n can be formed under the following rules:\n\n\n\tEach character is a lower case vowel ('a', 'e', 'i', 'o', 'u')\n\tEach vowel 'a' may only be followed by an 'e'.\n\tEach vowel 'e' may only be followed by an 'a' or an 'i'.\n\tEach vowel 'i' may not be followed by another 'i'.\n\tEach vowel 'o' may only be followed by an 'i' or a 'u'.\n\tEach vowel 'u' may only be followed by an 'a'.\n\n\nSince the answer may be too large, return it modulo 10^9 + 7.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 5\nExplanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n\n\nExample 2:\n\nInput: n = 2\nOutput: 10\nExplanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n\n\nExample 3: \n\nInput: n = 5\nOutput: 68\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 10^4\n\n", "solution_py": "class Solution:\n def countVowelPermutation(self, n: int) -> int:\n # dp[i][j] means the number of strings of length i that ends with the j-th vowel.\n dp = [[1] * 5] + [[0] * (5) for _ in range(n - 1)]\n moduler = math.pow(10, 9) + 7\n for i in range(1, n):\n # For vowel a\n dp[i][0] = (dp[i - 1][1] + dp[i - 1][2] + dp[i - 1][4]) % moduler\n # For vowel e\n dp[i][1] = (dp[i - 1][0] + dp[i - 1][2]) % moduler\n # For vowel i\n dp[i][2] = (dp[i - 1][1] + dp[i - 1][3]) % moduler\n # For vowel o\n dp[i][3] = (dp[i - 1][2]) % moduler\n # For vowel u\n dp[i][4] = (dp[i - 1][2] + dp[i - 1][3]) % moduler\n\n return int(sum(dp[-1]) % moduler)", "solution_js": "var countVowelPermutation = function(n) {\n let a = 1, e = 1, i = 1, o = 1, u = 1, mod = 1000000007\n while(n-- > 1){\n let new_a = a % mod, new_e = e % mod, new_i = i % mod, new_o = o % mod, new_u = u % mod\n a = new_e + new_i + new_u\n e = new_a + new_i\n i = new_e + new_o\n o = new_i\n u = new_i + new_o\n }\n return (a + e + i + o + u) % mod\n};", "solution_java": "class Solution {\n private long[][] dp;\n private int mod = (int)1e9 + 7;\n\n public int countVowelPermutation(int n) {\n dp = new long[6][n+1];\n if(n == 1) return 5;\n\n for(int i = 0; i < 5; i++)\n dp[i][0] = 1;\n\n helper(n,'z');\n return (int)dp[5][n];\n }\n\n private long helper(int n, char vowel)\n {\n long ans = 0;\n if(n == 0) return 1;\n\n if(vowel == 'z') // we are using z for our convenience just to add Permutations of all Vowels\n {\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'i') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[5][n] = ans;\n }\n // from here as per our assumptions of Vowels we will make calls & store results\n else if(vowel == 'a') // for Nth number we would store Result for \"a\" in dp[0][n]\n {\n if(dp[0][n] != 0) return dp[0][n];\n ans = (ans + helper(n-1,'e'))%mod;\n dp[0][n] = ans;\n }\n\n else if(vowel == 'e') // for Nth number we would store Result for \"e\" in dp[1][n]\n {\n if(dp[1][n] != 0) return dp[1][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'i'))%mod;\n dp[1][n] = ans;\n }\n\n else if(vowel == 'i') // for Nth number we would store Result for \"i\" in dp[2][n]\n {\n if(dp[2][n] != 0) return dp[2][n];\n ans = (ans + helper(n-1,'a') + helper(n-1,'e') + helper(n-1,'o') + helper(n-1,'u'))%mod;\n dp[2][n] = ans;\n }\n\n else if(vowel == 'o') // for Nth number we would store Result for \"o\" in dp[3][n]\n {\n if(dp[3][n] != 0) return dp[3][n];\n ans = (ans + helper(n-1,'i') + helper(n-1,'u'))%mod;\n dp[3][n] = ans;\n }\n\n else // for Nth number we would store Result for \"u\" in dp[4][n]\n {\n if(dp[4][n] != 0) return dp[4][n];\n ans = (ans + helper(n-1,'a'))%mod;\n dp[4][n] = ans;\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int countVowelPermutation(int n) {\n long a = 1, e = 1, i = 1, o = 1, u = 1, mod = pow(10, 9)+7;\n long a2, e2, i2, o2, u2;\n\n for (int j = 2; j <= n; j++) {\n a2 = (e + i + u) % mod;\n e2 = (a + i) % mod;\n i2 = (e + o) % mod;\n o2 = i;\n u2 = (o + i) % mod;\n\n a = a2, e = e2, i = i2, o = o2, u = u2;\n }\n\n return (a + e + i + o + u) % mod;\n }\n};" }, { "title": "Stickers to Spell Word", "algo_input": "We are given n different types of stickers. Each sticker has a lowercase English word on it.\n\nYou would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\n\nReturn the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.\n\nNote: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.\n\n \nExample 1:\n\nInput: stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput: 3\nExplanation:\nWe can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.\n\n\nExample 2:\n\nInput: stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput: -1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.\n\n\n \nConstraints:\n\n\n\tn == stickers.length\n\t1 <= n <= 50\n\t1 <= stickers[i].length <= 10\n\t1 <= target.length <= 15\n\tstickers[i] and target consist of lowercase English letters.\n\n", "solution_py": "from functools import lru_cache\nfrom collections import Counter\nclass Solution(object):\n def minStickers(self, stickers, target):\n counter = [Counter(sticker) for sticker in stickers] \n n = len(counter)\n @lru_cache(None)\n def dfs(target):\n if not target: return 0\n targ_counter = Counter(target)\n res = float('inf')\n #using sticker[i] if it contains the first letter of target\n for i in range(n):\n if counter[i][target[0]] == 0:\n continue\n s = ''\n for j in 'abcdefghijklmnopqrstuvwxyz':\n s += j*max(targ_counter[j] - counter[i][j], 0) \n res = min(res, 1 + dfs(s)) if dfs(s) != -1 else res\n return -1 if res == float('inf') else res\n return dfs(target)", "solution_js": "/**\n * @param {string[]} stickers\n * @param {string} target\n * @return {number}\n */\n\n// Backtracking\nvar minStickers = function(stickers, target) {\n //* Inits *//\n let dp = new Map();\n\n //* Helpers *//\n const getStringDiff = (str1, str2) => {\n for(let c of str2) {\n if(str1.includes(c)) str1 = str1.replace(c, '');\n }\n return str1;\n }\n dp.set('', 0);\n\n //* Main *//\n function calcStickers(restStr) {\n // if(restStr === \"\") return 0; <-- without memoization\n if (dp.has(restStr)) return dp.get(restStr);\n let res = Infinity;\n\n for (let s of stickers.filter(s => s.includes(restStr[0]))) { // if current sticker does not contain the FIRST char, continue\n let str = getStringDiff(restStr, s); //aabbc - bc = aab\n res = Math.min(res, 1 + calcStickers(str)); // RECURSE.... calculate min stickers for the remaining letters.. try combination for all strings and get min\n }\n\n dp.set(restStr, res === Infinity || res === 0 ? -1 : res); //Memoize the result in dp;\n return dp.get(restStr);\n // return res; <-- without memoization\n }\n return calcStickers(target)\n}", "solution_java": "class Solution {\n HashMap>map;\n public int minStickers(String[] stickers, String target) {\n map = new HashMap<>();\n for(String sticker:stickers){\n HashMap temp = new HashMap<>();\n for(char ch:sticker.toCharArray())\n temp.put(ch,temp.getOrDefault(ch,0)+1);\n map.put(sticker,temp);\n }\n int count = memoization(target,new HashMap<>());\n return count<1||count>=Integer.MAX_VALUE?-1:count;\n }\n public int memoization(String target, HashMapdpmap){\n if(target.length()==0)return 0;\n if(dpmap.containsKey(target)) return dpmap.get(target);\n int count = Integer.MAX_VALUE;\n for(String str: map.keySet()){\n HashMap xd = new HashMap(map.get(str));\n String temp = target;\n char ch = temp.charAt(0);\n if(xd.containsKey(ch)){\n for(int i =0;i0){\n xd.put(ch,xd.get(ch)-1);\n temp = temp.substring(0,i)+temp.substring(i+1);\n i--;\n }\n }\n if(temp.length()!=target.length()){\n count = Math.min(count,1+memoization(temp,dpmap));\n dpmap.put(target,count); \n }\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[50][1<<15] ;\n int solve(int ind, int mask, vector& stickers, string& target)\n {\n if (mask == 0)\n return 0 ;\n if (ind == stickers.size())\n return 1e8 ;\n if (dp[ind][mask] != -1)\n return dp[ind][mask] ;\n vector mp(26, 0);\n bool flag = false ;\n int ans = 1e8 ;\n for(int i = 0; i < stickers[ind].size(); i++)\n mp[stickers[ind][i]-'a'] ++ ;\n for(int i= 0; i < target.size(); i++)\n {\n if (mp[target[i]-'a'] > 0 && (mask & (1< 0 && (tempMask & (1<& stickers, string target) {\n int n = target.size();\n memset(dp, -1, sizeof(dp)) ;\n int ans = solve(0, (1< str:\n sz, window = len(num), SortedList()\n remainedIndices, poppedIndices = SortedList(range(sz)), []\n while k > 0:\n while len(window) < k + 1 and len(window) < len(remainedIndices):\n idx = remainedIndices[len(window)]\n window.add((num[idx], idx))\n if not window:\n break\n index = window.pop(0)[1]\n k -= remainedIndices.bisect_left(index)\n remainedIndices.remove(index)\n poppedIndices.append(index)\n for idx in remainedIndices[k + 1: len(window)]:\n window.remove((num[idx], idx))\n poppedSet = set(poppedIndices)\n return \"\".join(num[idx] for idx in poppedIndices) + \"\".join(num[idx] for idx in range(sz) if idx not in poppedSet)", "solution_js": "/**\n * @param {string} num\n * @param {number} k\n * @return {string}\n \n Idea is based on bubble sorting with limited steps k\n \n */\n\nvar minInteger = function(num, k) {\n if (num.length == 1)\n return num;\n \n let nums = num.split('');\n let i = 0, j = 0;\n \n while (k && i < num.length-1) {\n// step 0: if leading zero, check the next digit\n if (nums[i] == '0') {\n i++;\n j++;\n continue;\n }\n \n// step 1: find the min digit \n let p = j, steps = 0;\n while (nums[p] !== '0' && j < nums.length && steps <= k) {\n if (nums[j] < nums[p])\n p = j;\n j++;\n steps++;\n }\n \n// step 2: nums[i] is the current minimum digit --> check next digit\n if (p == i) {\n i++;\n j = i;\n continue;\n }\n \n// step 3: move the min digit to i\n for (; p > i; p--) {\n [nums[p], nums[p-1]] = [nums[p-1], nums[p]];\n k--;\n }\n \n i++;\n j = i;\n \n }\n \n return nums.join('');\n};", "solution_java": "class Solution {\n public String minInteger(String num, int k) {\n //pqs stores the location of each digit.\n List> pqs = new ArrayList<>();\n for (int i = 0; i <= 9; ++i) {\n pqs.add(new LinkedList<>());\n }\n\n for (int i = 0; i < num.length(); ++i) {\n pqs.get(num.charAt(i) - '0').add(i);\n }\n String ans = \"\";\n SegmentTree seg = new SegmentTree(num.length());\n\n for (int i = 0; i < num.length(); ++i) {\n // At each location, try to place 0....9\n for (int digit = 0; digit <= 9; ++digit) {\n // is there any occurrence of digit left?\n if (pqs.get(digit).size() != 0) {\n // yes, there is a occurrence of digit at pos\n Integer pos = pqs.get(digit).peek();\n\t\t\t\t\t// Since few numbers already shifted to left, this `pos` might be outdated.\n // we try to find how many number already got shifted that were to the left of pos.\n int shift = seg.getCountLessThan(pos);\n // (pos - shift) is number of steps to make digit move from pos to i.\n if (pos - shift <= k) {\n k -= pos - shift;\n seg.add(pos); // Add pos to our segment tree.\n pqs.get(digit).remove();\n ans += digit;\n break;\n }\n }\n }\n }\n return ans;\n }\n\n class SegmentTree {\n int[] nodes;\n int n;\n\n public SegmentTree(int max) {\n nodes = new int[4 * (max)];\n n = max;\n }\n\n public void add(int num) {\n addUtil(num, 0, n, 0);\n }\n\n private void addUtil(int num, int l, int r, int node) {\n if (num < l || num > r) {\n return;\n }\n if (l == r) {\n nodes[node]++;\n return;\n }\n int mid = (l + r) / 2;\n addUtil(num, l, mid, 2 * node + 1);\n addUtil(num, mid + 1, r, 2 * node + 2);\n nodes[node] = nodes[2 * node + 1] + nodes[2 * node + 2];\n }\n\n // Essentialy it tells count of numbers < num.\n public int getCountLessThan(int num) {\n return getUtil(0, num, 0, n, 0);\n }\n\n private int getUtil(int ql, int qr, int l, int r, int node) {\n if (qr < l || ql > r) return 0;\n if (ql <= l && qr >= r) {\n return nodes[node];\n }\n\n int mid = (l + r) / 2;\n return getUtil(ql, qr, l, mid, 2 * node + 1) + getUtil(ql, qr, mid + 1, r, 2 * node + 2);\n }\n }\n\n}", "solution_c": "/*\n Time: O(nlogn)\n Space: O(n)\n Tag: Segment Tree, Greedy (put the possible feasible smallest index in place of cur index), Queue\n Difficulty: H (Both Logic and Implementation)\n*/\n\nclass SegmentTree {\n vector tree;\n\npublic:\n SegmentTree(int size) {\n tree.resize(4 * size + 1, 0);\n }\n\n void printTree() {\n for (int num : tree) cout << num << \"\";\n cout << endl;\n }\n\n void updateTree(int lo, int hi, int index, int upd) {\n if (upd < lo || upd > hi) return;\n if (lo == hi) {\n tree[index]++;\n return;\n }\n int mid = lo + (hi - lo) / 2;\n updateTree(lo, mid, 2 * index, upd);\n updateTree(mid + 1, hi, 2 * index + 1, upd);\n tree[index] = tree[2 * index] + tree[2 * index + 1];\n }\n\n int queryTree(int lo, int hi, int index, int qs, int qe) {\n if (qe < lo || qs > hi) return 0;\n if (qe >= hi && qs <= lo) return tree[index];\n\n int mid = lo + (hi - lo) / 2;\n\n int left = queryTree(lo, mid, 2 * index, qs, qe);\n int right = queryTree(mid + 1, hi, 2 * index + 1, qs, qe);\n return left + right;\n }\n};\n\nclass Solution {\npublic:\n string minInteger(string num, int k) {\n queue pos[10];\n for (int i = 0; i < num.length(); i++) {\n pos[num[i] - '0'].push(i);\n }\n string res = \"\";\n SegmentTree *seg = new SegmentTree((int)num.length());\n for (int i = 0; i < num.length(); i++) {\n if (num[i] == '-') continue;\n int digit = num[i] - '0';\n\n bool swapped = false;\n for (int j = 0; j < digit; j++) {\n if (pos[j].size() > 0) {\n int curNumIndex = pos[j].front();\n int shifts = seg->queryTree(0, num.length() - 1, 1, i, pos[j].front());\n\n if (curNumIndex - i - shifts <= k) {\n seg->updateTree(0, num.length() - 1, 1, curNumIndex);\n k -= curNumIndex - i - shifts;\n pos[j].pop();\n res += num[curNumIndex];\n num[curNumIndex] = '-';\n swapped = true;\n i--;\n break;\n }\n }\n }\n if (!swapped) {\n res += num[i];\n pos[digit].pop();\n }\n }\n return res;\n }\n};" }, { "title": "Bulls and Cows", "algo_input": "You are playing the Bulls and Cows game with your friend.\n\nYou write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:\n\n\n\tThe number of \"bulls\", which are digits in the guess that are in the correct position.\n\tThe number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.\n\n\nGiven the secret number secret and your friend's guess guess, return the hint for your friend's guess.\n\nThe hint should be formatted as \"xAyB\", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.\n\n \nExample 1:\n\nInput: secret = \"1807\", guess = \"7810\"\nOutput: \"1A3B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"\n\nExample 2:\n\nInput: secret = \"1123\", guess = \"0111\"\nOutput: \"1A1B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.\n\n\n \nConstraints:\n\n\n\t1 <= secret.length, guess.length <= 1000\n\tsecret.length == guess.length\n\tsecret and guess consist of digits only.\n\n", "solution_py": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n # Setup counts for bulls and cows\n bulls = cows = 0\n \n # Copy secret and guess into lists that are easier to work with\n secretCopy = list(secret)\n guessCopy = list(guess)\n \n # In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls\n for i in range(len(secret)):\n \n # If they match, bulls += 1 and pop() the letters from the copy lists via their .index()\n if secret[i] == guess[i]:\n bulls += 1\n secretCopy.pop(secretCopy.index(secret[i]))\n guessCopy.pop(guessCopy.index(guess[i]))\n \n \n # Count() the letters remaining in secret and guess lists\n secretCounter = Counter(secretCopy)\n guessCounter = Counter(guessCopy)\n \n # Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed\n # secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters\n # Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters\n dif = secretCounter - (secretCounter - guessCounter)\n \n # The .total() of the dif Counter is the number of cows\n cows = dif.total()\n\n # return the formatted string with req. info\n return f'{bulls}A{cows}B'", "solution_js": "var getHint = function(secret, guess) {\n let ACount = 0, BCount = 0;\n const secretMap = new Map(), guessMap = new Map();\n for(let i = 0; i < secret.length; i++) {\n if(secret[i] == guess[i]) {\n ACount++;\n }\n else {\n if(secretMap.has(secret[i])) {\n secretMap.set(secret[i], secretMap.get(secret[i])+1);\n }\n else {\n secretMap.set(secret[i], 1);\n }\n }\n }\n for(let i = 0; i < guess.length; i++) {\n if(secret[i] !== guess[i]) {\n if(secretMap.get(guess[i]) > 0) {\n secretMap.set(guess[i], secretMap.get(guess[i])-1);\n BCount++;\n }\n }\n }\n return ACount+'A'+BCount+'B';\n};", "solution_java": "class Solution {\n public String getHint(String secret, String guess) {\n int arr[] = new int[10], bulls = 0, cows = 0;\n for (int i = 0; i < secret.length(); i++) {\n char sec = secret.charAt(i);\n char gue = guess.charAt(i); \n if (sec == gue) bulls++;\n else {\n if (arr[sec - '0'] < 0) cows++;\n if (arr[gue - '0'] > 0) cows++;\n arr[sec - '0']++;\n arr[gue - '0']--;\n }\n }\n return new StringBuilder(String.valueOf(bulls)).append(\"A\").append(cows).append(\"B\").toString();\n }\n}", "solution_c": "class Solution\n{\npublic:\n string getHint(string secret, string guess)\n {\n int bulls = 0;\n vector v1(10, 0);\n vector v2(10, 0);\n for (int i = 0; i < secret.size(); ++i)\n {\n if (secret[i] == guess[i])\n {\n ++bulls;\n }\n else\n {\n ++v1[secret[i] - '0'];\n ++v2[guess[i] - '0'];\n }\n }\n int cows = 0;\n for (int i = 0; i < 10; ++i)\n {\n cows += min(v1[i], v2[i]);\n }\n return to_string(bulls) + \"A\" + to_string(cows) + \"B\";\n }\n};" }, { "title": "Check If String Is a Prefix of Array", "algo_input": "Given a string s and an array of strings words, determine whether s is a prefix string of words.\n\nA string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.\n\nReturn true if s is a prefix string of words, or false otherwise.\n\n \nExample 1:\n\nInput: s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput: true\nExplanation:\ns can be made by concatenating \"i\", \"love\", and \"leetcode\" together.\n\n\nExample 2:\n\nInput: s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput: false\nExplanation:\nIt is impossible to make s using a prefix of arr.\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length <= 20\n\t1 <= s.length <= 1000\n\twords[i] and s consist of only lowercase English letters.\n\n", "solution_py": "class Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \n a = ''\n \n for i in words:\n \n a += i\n \n if a == s:\n return True\n if not s.startswith(a):\n break\n \n return False ", "solution_js": "var isPrefixString = function(s, words) {\n let str = words[0];\n if(s === words[0]){\n return true;\n }\n for(let i=1; i < words.length; i++){\n if(s === str){\n return true;\n }\n if( s.startsWith(str)){\n str += words[i];\n continue;\n }else{\n return false;\n }\n }\n if(s !== str){\n return false;\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean isPrefixString(String s, String[] words) {\n StringBuilder res = new StringBuilder (\"\");\n for (String word : words) {\n res.append (word);\n if (s.equals (res.toString()))\n return true;\n if (s.indexOf (res.toString()) == -1)\n return false;\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPrefixString(string s, vector& words) {\n string n=\"\";\n for(string str:words){\n for(char ch:str){\n n+=ch;\n }\n if(n==s){\n return true;\n }\n }\n \n return false;\n }\n};" }, { "title": "Sorting the Sentence", "algo_input": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.\n\nA sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.\n\n\n\tFor example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\".\n\n\nGiven a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.\n\n \nExample 1:\n\nInput: s = \"is2 sentence4 This1 a3\"\nOutput: \"This is a sentence\"\nExplanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.\n\n\nExample 2:\n\nInput: s = \"Myself2 Me1 I4 and3\"\nOutput: \"Me Myself and I\"\nExplanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 200\n\ts consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.\n\tThe number of words in s is between 1 and 9.\n\tThe words in s are separated by a single space.\n\ts contains no leading or trailing spaces.\n", "solution_py": "class Solution:\n def sortSentence(self, s: str) -> str:\n\n x = s.split()\n dic = {}\n for i in x :\n dic[i[-1]] = i[:-1]\n return ' '.join([dic[j] for j in sorted(dic)])", "solution_js": "var sortSentence = function(s) {\n let sortingS = s.split(' ').sort((a,b) => a.substr(-1) - b.substr(-1));\n slicingS = sortingS.map(word => word.slice(0, -1));\n return slicingS.join(' ');\n};", "solution_java": "class Solution {\n public String sortSentence(String s) {\n String []res=new String[s.split(\" \").length];\n for(String st:s.split(\" \")){\n res[st.charAt(st.length()-1)-'1']=st.substring(0,st.length()-1);\n }\n return String.join(\" \",res);\n }\n}", "solution_c": "class Solution {\npublic:\n string sortSentence(string s) \n {\n stringstream words(s); \n string word;\n pair m;\n vector > sent;\n \n //SECTION 1\n while(words>>word)\n {\n int len = word.size();\n int i = int(word[len-1]) - 48;\n sent.push_back(make_pair(i, word.substr(0, len-1)));\n }\n \n //SECTION 2\n sort(sent.begin(), sent.end());\n \n //SECTION 3\n string ans = \"\";\n int len = sent.size();\n for(int i=0; ileft);\n int right = countNodes(root->right);\n \n return 1+left+right;\n }\n};" }, { "title": "Strange Printer", "algo_input": "There is a strange printer with the following two special properties:\n\n\n\tThe printer can only print a sequence of the same character each time.\n\tAt each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.\n\n\nGiven a string s, return the minimum number of turns the printer needed to print it.\n\n \nExample 1:\n\nInput: s = \"aaabbb\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"bbb\".\n\n\nExample 2:\n\nInput: s = \"aba\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution(object):\n def strangePrinter(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # remove duplicate letters from s.\n tmp = []\n for c in s:\n if len(tmp) == 0 or tmp[-1] != c:\n tmp.append(c)\n s = \"\".join(tmp)\n\n _m = {}\n def _dp(i, j, background):\n if j < i:\n return 0\n elif i == j:\n return 1 if background != s[i] else 0\n elif (i, j, background) in _m:\n return _m[(i, j, background)]\n\n ans = len(s)\n\n # shrink s[i:j+1] to s[i_:j_+1] according to the background letter\n i_ = i + 1 if s[i] == background else i\n j_ = j - 1 if s[j] == background else j\n\n if s[i_] == s[j_]:\n # case \"AxxxA\" => best strategy is printing A first\n ans = _dp(i_ + 1, j_ - 1, s[i_]) + 1\n else:\n # otherwise, print first letter, try every possible print length\n for p in range(i_, j_ + 1):\n # searching is needed only if s[p] == s[i_]\n # e.g. s=\"ABCDEA\"print 'A' on s[0:1] is equivalent to s[0:5]\n if s[p] != s[i_]:\n continue\n l = _dp(i_, p, s[i_])\n r = _dp(p + 1, j_, background)\n ans = min(ans, l + r + 1)\n _m[(i, j, background)] = ans\n return ans\n\n return _dp(0, len(s) - 1, '')", "solution_js": "var strangePrinter = function(s) {\n if(!s) return 0;\n\n const N = s.length; \n const state = Array.from({length:N}, () => Array.from({length:N}));\n \n for(let i = 0; i < N; i++) {\n // Printing one character always takes one attempt\n state[i][i] = 1;\n }\n \n const search = (i,j) => {\n if(state[i][j]) return state[i][j];\n \n state[i][j] = Infinity;\n for(let k = i; k < j; k++) {\n state[i][j] = Math.min(state[i][j], search(i,k) + search(k+1,j));\n }\n if(s[i] === s[j]) state[i][j]--;\n return state[i][j];\n }\n \n return search(0, N-1);\n}", "solution_java": "class Solution {\n\npublic int strangePrinter(String s) {\n if (s.equals(\"\")) return 0;\n int len = s.length();\n int[][] dp = new int[len][len];\n for (int i = 0; i < len; i++)\n dp[i][i] = 1;\n for (int l = 2; l <= len; l++) {\n for (int i = 0; i < len && l + i - 1 < len; i++) {\n int j = l + i - 1;\n dp[i][j] = dp[i][j - 1] + (s.charAt(i) == s.charAt(j) ? 0 : 1);\n for (int k = i + 1; k < j; k++) {\n if (s.charAt(k) == s.charAt(j)) {\n dp[i][j] = Math.min(dp[i][j], dp[i][k - 1] + dp[k][j - 1]);\n }\n }\n }\n }\n return dp[0][len - 1];\n}\n}", "solution_c": "class Solution {\npublic:\n int dp[101][101];\n int solve(string s,int i,int j)\n {\n if(i>j)\n return 0;\n if(dp[i][j]!=-1)\n return dp[i][j];\n int ans=0;\n while(i O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans", "solution_js": "var maxProfitAssignment = function(difficulty, profit, worker) {\n const data = [];\n\n for (let i = 0; i < difficulty.length; i++) {\n data.push({ difficulty: difficulty[i], profit: profit[i] });\n }\n\n data.sort((a, b) => a.difficulty - b.difficulty);\n\n let maxProfit = 0;\n\n for (let i = 0; i < data.length; i++) {\n data[i].profit = maxProfit = Math.max(maxProfit, data[i].profit);\n }\n\n // worker.sort((a, b) => a - b);\n\n let ans = 0;\n let min = 0;\n\n for (const skill of worker) {\n let left = 0; // min;\n let right = data.length - 1;\n\n while (left < right) {\n const mid = Math.floor((left + right + 1) / 2);\n\n if (data[mid].difficulty > skill) {\n right = mid - 1;\n } else {\n left = mid;\n }\n }\n\n if (data[left].difficulty > skill) {\n continue;\n }\n\n // min = left;\n ans += data[left].profit;\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(b[1]-a[1]));\n for(int i=0;i=0 && !pq.isEmpty();i--)\n {\n if(worker[i]>=pq.peek()[0])\n p=p+pq.peek()[1];\n else\n {\n while(!pq.isEmpty() && worker[i]a, pairb){\n if(a.first == b.first){\n return a.secondb.first;\n }\n int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) {\n int ans = 0;\n vector>vp;\n for(int i = 0; i());\n\n //i is for traversing the vp and j is for traversing the worker\n int i = 0, j = 0;\n\n while(i=vp[i].second){\n ans+=vp[i].first;\n j++;\n }\n else{\n i++;\n }\n }\n\n return ans;\n }\n};" }, { "title": "Merge Strings Alternately", "algo_input": "You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.\n\nReturn the merged string.\n\n \nExample 1:\n\nInput: word1 = \"abc\", word2 = \"pqr\"\nOutput: \"apbqcr\"\nExplanation: The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r\n\n\nExample 2:\n\nInput: word1 = \"ab\", word2 = \"pqrs\"\nOutput: \"apbqrs\"\nExplanation: Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s\n\n\nExample 3:\n\nInput: word1 = \"abcd\", word2 = \"pq\"\nOutput: \"apbqcd\"\nExplanation: Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d\n\n\n \nConstraints:\n\n\n\t1 <= word1.length, word2.length <= 100\n\tword1 and word2 consist of lowercase English letters.\n", "solution_py": "class Solution(object):\n def mergeAlternately(self, word1, word2):\n i=0\n j=0\n st=[]\n while i int:\n total = 0\n\t\t\n # top\n total += sum([1 for i in grid for j in i if j > 0])\n \n\t\t# front\n total += sum([max(col) for col in zip(*grid)])\n \n\t\t# side\n total += sum([max(row) for row in grid])\n \n\t\treturn total", "solution_js": "var projectionArea = function(grid) {\n let maxs = new Array(grid.length).fill(0);\n\n grid.forEach(row => row.forEach((val, idx) => {\n if (maxs[idx] < val) maxs[idx] = val;\n }))\n \n const z = grid.reduce((prev, curr) => prev + curr.filter(val => val !== 0).length, 0);\n const y = grid.reduce((prev, curr) => prev + Math.max(...curr), 0);\n const x = maxs.reduce((prev, curr) => prev + curr, 0)\n \n return x + y + z;\n};", "solution_java": "class Solution {\n public int projectionArea(int[][] grid) {\n int totalArea = 0;\n \n \n for(int[] row : grid){\n int max = row[0];\n for(int c : row){\n if(max < c){\n max = c;\n }if(c != 0){\n totalArea += 1;\n }\n \n }\n totalArea += max;\n }\n \n for(int c = 0; c < grid[0].length; c++){\n int max = grid[0][c];\n for(int row = 0; row < grid.length; row++){\n if(max < grid[row][c]){\n \n max = grid[row][c];\n }\n }\n totalArea += max;\n }\n return totalArea;\n }\n}", "solution_c": "class Solution {\npublic:\n int projectionArea(vector>& grid) {\n int res=0;\n // X-Y ( top )\n for(int i=0;i int:\n perimeter = 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n perimeter += 4\n if i != 0 and grid[i-1][j] == 1:\n perimeter -= 2\n if j != 0 and grid[i][j-1] == 1:\n perimeter -= 2 \n \n return perimeter", "solution_js": "var islandPerimeter = function(grid) {\n let perimeter = 0\n let row = grid.length\n let col = grid[0].length\n \n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[i].length; j++) {\n if (grid[i][j] === 1) {\n if (i === 0 || i > 0 && grid[i-1][j] === 0) perimeter++ \n if (i === row-1 || i < row-1 && grid[i+1][j] === 0) perimeter++ \n if (j === 0 || j > 0 && grid[i][j-1] === 0) perimeter++\n if (j === col - 1 || j < col && grid[i][j+1] === 0) perimeter++\n }\n }\n }\n \n return perimeter\n};", "solution_java": "class Solution {\n public int islandPerimeter(int[][] grid) {\n if(grid == null || grid.length == 0) return 0;\n\n int row=grid.length,col=grid[0].length;\n int perimeter=0;\n\n for(int i=0;i0 && grid[i-1][j]==1){\n perimeter-=2;\n }\n\n if(j>0 && grid[i][j-1]==1){\n perimeter-=2;\n }\n }\n\n }\n }\n return perimeter;\n }\n}", "solution_c": "////** hindi me samjho ab// \n// agar mje left or right or bottom or top me 1 mila to me aaga badunga agar nahi\n//mila mtlb ya to wo boundary hai uske baad 0 ara hai agar esa hai to cnt+=1 \n//kardo kuki wo hi to meri boundary banegi . note : agar boundary hai mtlb \n//i <0 or j<0 or i>=n or j>=m to cnt+=1 kardo or agar box ke side walo me 0 hai to wahan bhi cnt+=1 . \n// hope it make sense \n// please upvote if you like my post \nclass Solution {\npublic:\n int cnt =0 ;\nbool vis[101][101] ;\n bool valid( int i , int j, int n , int m){\n if(i>=n or j>=m or i<0 or j<0 )\n return false;\n return true ;\n }\n int islandPerimeter(vector>& grid) {\n memset(vis,false , sizeof(vis)) ;\n for(int i = 0 ; i >&grid, int i , int j ){\n int n = grid.size() ; \n int m = grid[0].size() ;\n vis[i][j]=true ;\n if(!valid(i-1,j,n,m) or (valid(i-1,j,n,m) and grid[i-1][j]==0)){\n cnt++ ;\n }\n else if(valid(i-1,j,n,m)and !vis[i-1][j])\n solve(grid, i-1,j) ;\n \n if(!valid(i+1,j,n,m) or (valid(i+1,j,n,m) and grid[i+1][j]==0)){\n cnt++ ;\n }\n else if(valid(i+1,j,n,m)and !vis[i+1][j])\n solve(grid,i+1,j) ;\n \n if(!valid(i,j-1,n,m) or (valid(i,j-1,n,m) and grid[i][j-1]==0)){\n cnt++ ;\n }\n else if(valid(i,j-1,n,m)and !vis[i][j-1])\n solve(grid,i,j-1) ;\n \n if(!valid(i,j+1,n,m) or (valid(i,j+1,n,m) and grid[i][j+1]==0)){\n cnt++ ;\n }\n else if(valid(i,j+1,n,m)and !vis[i][j+1])\n solve(grid,i,j+1) ;\n \n \n \n}\n};" }, { "title": "Minimum Cost Homecoming of a Robot in a Grid", "algo_input": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).\n\nThe robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.\n\n\n\tIf the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].\n\tIf the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].\n\n\nReturn the minimum total cost for this robot to return home.\n\n \nExample 1:\n\nInput: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput: 18\nExplanation: One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2, 1). This move costs colCosts[1] = 2.\n-> It goes right to (2, 2). This move costs colCosts[2] = 6.\n-> It goes right to (2, 3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18\n\nExample 2:\n\nInput: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput: 0\nExplanation: The robot is already at its home. Since no moves occur, the total cost is 0.\n\n\n \nConstraints:\n\n\n\tm == rowCosts.length\n\tn == colCosts.length\n\t1 <= m, n <= 105\n\t0 <= rowCosts[r], colCosts[c] <= 104\n\tstartPos.length == 2\n\thomePos.length == 2\n\t0 <= startrow, homerow < m\n\t0 <= startcol, homecol < n\n\n", "solution_py": "class Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n def getRange(left, right, array):\n if left > right:\n right, left = left, right\n return sum((array[i] for i in range(left,right+1)))\n \n totalRowCost = getRange(startPos[0], homePos[0], rowCosts)\n totalColCost = getRange(startPos[1], homePos[1], colCosts)\n \n #Don't pay for the position you start out on\n return totalRowCost + totalColCost - rowCosts[startPos[0]] - colCosts[startPos[1]]", "solution_js": "var minCost = function(startPos, homePos, rowCosts, colCosts) {\n let totCosts = 0;\n\n let rowDir = startPos[0] <= homePos[0] ? 1 : -1;\n let colDir = startPos[1] <= homePos[1] ? 1 : -1;\n \n let row = startPos[0];\n\n while (row != homePos[0]) {\n row += rowDir;\n totCosts += rowCosts[row];\n }\n\n let col = startPos[1];\n\n while (col != homePos[1]) {\n col += colDir;\n totCosts += colCosts[col];\n }\n\n return totCosts;\n};", "solution_java": "class Solution {\n public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {\n int total = 0;\n \n // if home is to the down of start move, down till there\n if(homePos[0]>startPos[0]){\n int i = startPos[0]+1;\n while(i<=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is up from the start, move up till there\n else if(homePos[0]=homePos[0]){\n total += rowCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n // if home is right to the start, move right till there\n if(homePos[1]>startPos[1]){\n int i = startPos[1]+1;\n while(i<=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i++;\n }\n }\n \n // else if home is left to the start, move left till there\n else if(homePos[1]=homePos[1]){\n total += colCosts[i]; // adding cost while moving corresponding to the cell\n i--;\n }\n }\n \n return total;\n }\n}", "solution_c": "// This is Straightforward Question becuase you need to travel at least one time the incoming rows and column in path.\n// So why you need to complicate the path just traverse staright and to homePos Row and homePos column and you will get the ans...\n// This Question would have become really tough when negative values also possible in the row and column vectors because that negative values could have decresed the results...but here its simple and concise.\nclass Solution {\npublic:\n int minCost(vector& startPos, vector& homePos, vector& rowCosts, vector& colCosts) {\n int ans = 0;\n if(startPos[0] < homePos[0])\n {\n for(int i = startPos[0]+1 ; i <=homePos[0] ; i++)\n {\n ans+=rowCosts[i];\n }\n }\n if(startPos[0] > homePos[0])\n {\n for(int i = startPos[0]-1 ; i >=homePos[0] ; i--)\n {\n ans+=rowCosts[i];\n }\n }\n if(startPos[1] < homePos[1])\n {\n for(int i = startPos[1]+1 ; i <=homePos[1] ; i++)\n {\n ans+=colCosts[i];\n }\n }\n if(startPos[1] > homePos[1])\n {\n for(int i = startPos[1]-1 ; i >=homePos[1] ; i--)\n {\n ans+=colCosts[i];\n }\n }\n return ans;\n }\n};" }, { "title": "Convert Integer to the Sum of Two No-Zero Integers", "algo_input": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.\n\nGiven an integer n, return a list of two integers [A, B] where:\n\n\n\tA and B are No-Zero integers.\n\tA + B = n\n\n\nThe test cases are generated so that there is at least one valid solution. If there are many valid solutions you can return any of them.\n\n \nExample 1:\n\nInput: n = 2\nOutput: [1,1]\nExplanation: A = 1, B = 1. A + B = n and both A and B do not contain any 0 in their decimal representation.\n\n\nExample 2:\n\nInput: n = 11\nOutput: [2,9]\n\n\n \nConstraints:\n\n\n\t2 <= n <= 104\n\n", "solution_py": "class Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n for i in range(1,n//2+1):\n first = str(i)\n second = str(n-i)\n if \"0\" not in first and \"0\" not in second:\n return [i, n-i]", "solution_js": "var getNoZeroIntegers = function(n) {\n for(let i=1;i<=n;i++){\n if(!haveZero(i) && !haveZero(n-i)){\n return [i,n-i]\n }\n }\n};\n\nconst haveZero = (n) =>{\n let copy = n;\n while(copy>0){\n if(copy%10===0){\n return true\n }\n copy=Math.floor(copy/10)\n }\n return false\n}", "solution_java": "class Solution {\n public int[] getNoZeroIntegers(int n) {\n int B;\n for (int A = 1; A < n; ++A) {\n B = n - A;\n if (!(A + \"\").contains(\"0\") && !(B + \"\").contains(\"0\"))\n return new int[] {A, B};\n }\n return new int[]{};\n}\n}", "solution_c": "class Solution {\npublic:\n int has0(int x)\n{\n while (x){\n if (x % 10 == 0)\n return 1;\n x /= 10;\n }\n return 0;\n}\n vector getNoZeroIntegers(int n) {\n for(int i=1;i<=n;i++){\n if(has0(i)==false && has0(n-i)==false){\n return {i,n-i};\n }\n }\n return {1,1};\n }\n};" }, { "title": "Largest Rectangle in Histogram", "algo_input": "Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n\n \nExample 1:\n\nInput: heights = [2,1,5,6,2,3]\nOutput: 10\nExplanation: The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.\n\n\nExample 2:\n\nInput: heights = [2,4]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= heights.length <= 105\n\t0 <= heights[i] <= 104\n\n", "solution_py": "class Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n maxArea = 0\n stack = [] # (index, height)\n \n for i, h in enumerate(heights):\n startIndex = i\n while stack and stack[-1][1] > h:\n index, height = stack.pop()\n maxArea = max(maxArea, height * (i - index))\n startIndex = index\n stack.append((startIndex, h))\n \n \n \n for index, height in stack:\n maxArea = max(maxArea, height * (len(heights) - index))\n \n \n return maxArea", "solution_js": "var largestRectangleArea = function (heights) {\n let maxArea = 0;\n let stack = []; // [[index, height]]\n\n for (let i = 0; i < heights.length; i++) {\n let start = i;\n while (stack.length != 0 && stack[stack.length - 1][1] > heights[i]) {\n let [index, height] = stack.pop();\n maxArea = Math.max(maxArea, height * (i - index));\n start = index;\n }\n stack.push([start, heights[i]]);\n }\n for (let i = 0; i < stack.length; i++) {\n maxArea = Math.max(\n maxArea,\n stack[i][1] * (heights.length - stack[i][0])\n );\n }\n return maxArea;\n};", "solution_java": "class Solution {\n public int largestRectangleArea(int[] heights) {\n Stack stack1 = new Stack<>();\n Stack stack2 = new Stack<>();\n int n = heights.length;\n int[] left = new int[n];\n int[] right = new int[n];\n int[] width = new int[n];\n \n for(int i=0; i= heights[i])\n stack1.pop();\n if(!stack1.isEmpty())\n left[i] = stack1.peek();\n else\n left[i] = -1;\n stack1.push(i);\n }\n \n for(int i=n-1; i>=0; i--){\n while(!stack2.isEmpty() && heights[stack2.peek()] >= heights[i])\n stack2.pop();\n if(!stack2.isEmpty())\n right[i] = stack2.peek();\n else\n right[i] = n;\n stack2.push(i);\n }\n \n for(int i=0; i nextSmallerElement(vector& arr, int n){\n \n stack s;\n s.push(-1);\n vector ans(n);\n \n for(int i = n-1; i>=0 ; i--){\n int curr = arr[i];\n \n while(s.top()!=-1 && arr[s.top()]>=curr){\n s.pop();\n }\n ans[i] = s.top();\n s.push(i);\n }\n return ans;\n }\n vector prevSmallerElement(vector& arr, int n){\n \n stack s;\n s.push(-1);\n vector ans(n);\n \n for(int i = 0; i=curr){\n s.pop();\n }\n ans[i] = s.top();\n s.push(i);\n }\n return ans;\n }\npublic:\n int largestRectangleArea(vector& heights) {\n int n = heights.size();\n int area = 1, ans = INT_MIN;\n \n vector next(n);\n next = nextSmallerElement(heights, n);\n \n vector prev(n);\n prev = prevSmallerElement(heights, n);\n \n for(int i = 0; i int:\n\t\tpreSum = [0] * (len(s) + 1)\n\t\tsufSum = [0] * (len(s) + 1)\n\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == \"a\":\n\t\t\t\tpreSum[i] += 1 + preSum[i-1]\n\n\t\t\telse:\n\t\t\t\tpreSum[i] = preSum[i-1]\n\n\t\t\tif s[len(s)-i-1] == \"b\":\n\t\t\t\tsufSum[len(s)-i-1] += 1 + sufSum[len(s)-i]\n\n\t\t\telse:\n\t\t\t\tsufSum[len(s)-i-1] += sufSum[len(s)-i]\n\n\t\tmaxStringLength = 0\n\t\tfor i in range(len(s)):\n\t\t\tif preSum[i] + sufSum[i] > maxStringLength:\n\t\t\t\tmaxStringLength = preSum[i] + sufSum[i]\n\n\t\treturn len(s) - maxStringLength", "solution_js": "var minimumDeletions = function(s) {\n const dpA = [];\n let counter = 0;\n for (let i = 0; i < s.length; i++) {\n dpA[i] = counter;\n if (s[i] === 'b') {\n counter++;\n }\n }\n \n counter = 0;\n const dpB = [];\n for (let i = s.length - 1; i >= 0; i--) {\n dpB[i] = counter;\n if (s[i] === 'a') {\n counter++;\n }\n }\n\n let minDelete = s.length;\n for (let i = 0; i < s.length; i++) {\n minDelete = Math.min(minDelete, dpA[i] + dpB[i]);\n }\n \n return minDelete;\n};", "solution_java": "class Solution {\n public int minimumDeletions(String s) {\n //ideal case : bbbbbbbbb\n int[] dp = new int[s.length()+1];\n int idx =1;\n int bCount=0;\n\n for(int i =0 ;i deletions(s.size()+1, 0);\n int b_count = 0;\n \n for(int i = 0; i int:\n if not ops:\n return m*n\n else:\n x,y = zip(*ops)\n return min(x) * min(y)", "solution_js": "var maxCount = function(m, n, ops) {\n if( ops.length === 0 )\n return m*n\n let min_a = m , min_b = n\n for( let [x,y] of ops ){\n if( x < min_a )\n min_a = x\n if( y < min_b )\n min_b = y\n }\n return min_a * min_b\n};", "solution_java": "class Solution {\n public int maxCount(int m, int n, int[][] ops) {\n int minRow=m,minCol=n;\n for(int[] op:ops){\n minRow=Math.min(minRow,op[0]);\n minCol=Math.min(minCol,op[1]);\n }\n return minRow*minCol;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxCount(int m, int n, vector>& ops) {\n\n int mn_i = m, mn_j = n;\n for(auto &i : ops)\n mn_i = min(mn_i, i[0]), mn_j = min(mn_j, i[1]);\n\n return mn_i * mn_j;\n }\n};" }, { "title": "Maximum Number of Events That Can Be Attended", "algo_input": "You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.\n\nYou can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.\n\nReturn the maximum number of events you can attend.\n\n \nExample 1:\n\nInput: events = [[1,2],[2,3],[3,4]]\nOutput: 3\nExplanation: You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.\n\n\nExample 2:\n\nInput: events= [[1,2],[2,3],[3,4],[1,2]]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= events.length <= 105\n\tevents[i].length == 2\n\t1 <= startDayi <= endDayi <= 105\n\n", "solution_py": "class Solution(object):\n def maxEvents(self, events):\n \"\"\"\n :type events: List[List[int]]\n :rtype: int\n \"\"\"\n events = sorted(events, key=lambda x: x[0])\n current_day = 0\n min_heap = []\n event_id = 0\n total_number_of_days = max(end for start, end in events)\n total_events_attended = 0\n #total_number_of_days+1 because I want to include the last day\n for day in range(1, total_number_of_days+1):\n\n #Add all the events that can be started on that day\n while event_id < len(events) and events[event_id][0] == day:\n heapq.heappush(min_heap, events[event_id][1])\n event_id+=1\n\n #while there is something in heap and the event should have been completed before the current day\n #remove those evenets and consider them not attended\n while min_heap and min_heap[0] < day :\n heapq.heappop(min_heap)\n\n #if theere is an event present in heap\n #lets mark 1 of those events as complted today and add it to\n #total_events_attended\n\n if min_heap:\n heapq.heappop(min_heap)\n total_events_attended+=1\n return total_events_attended", "solution_js": "/**\n* O(nlogn)\n*/\nvar maxEvents = function(events) {\n\n // sort events by their start time\n events.sort((a,b) => a[0]-b[0]);\n\n // create priority queue to sort events by end time, the events that have saem start time\n let minHeap = new PriorityQueue((a, b) => a - b);\n let i = 0, len = events.length, res = 0, d = 0;\n\n while(i < len || !minHeap.isEmpty()){\n\n if (minHeap.isEmpty())\n d = events[i][0]; // start with event from events list\n\n while (i < len && events[i][0] <= d) // Add all events that have start time <= day `d` into PQ\n minHeap.add(events[i++][1]); // add ending time to the minHeap, so when we pull we get event that is ending first\n\n minHeap.poll(); // make sure we have some event attent\n ++res;\n ++d;\n\n // we finished task of day 'd' Remove events that are already closed ie endTime < d as we cant attend it\n while (!minHeap.isEmpty() && minHeap.peek() < d)\n minHeap.poll();\n }\n return res;\n};\n\n/*******************standard priority queue implementation used in all leetcode javascript solutions****************/\nclass PriorityQueue {\n\n /**\n * Create a Heap\n * @param {function} compareFunction - compares child and parent element\n * to see if they should swap. If return value is less than 0 it will\n * swap to prioritize the child.\n */\n constructor(compareFunction) {\n this.store = [];\n this.compareFunction = compareFunction;\n }\n\n peek() {\n return this.store[0];\n }\n\n size() {\n return this.store.length;\n }\n isEmpty() {\n return this.store.length === 0;\n }\n\n poll() {\n if (this.size() < 2) {\n return this.store.pop();\n }\n const result = this.store[0];\n this.store[0] = this.store.pop();\n this.heapifyDown(0);\n return result;\n }\n\n add(val) {\n this.store.push(val);\n this.heapifyUp(this.size() - 1);\n }\n\n heapifyUp(child) {\n while (child) {\n const parent = Math.floor((child - 1) / 2);\n\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n child = parent;\n } else {\n return child;\n }\n }\n }\n\n heapifyDown(parent) {\n while (true) {\n let [child, child2] = [1,2].map((x) => parent * 2 + x).filter((x) => x < this.size());\n if (this.shouldSwap(child2, child)) {\n child = child2;\n }\n\n if (this.shouldSwap(child, parent)) {\n [this.store[child], this.store[parent]] = [this.store[parent], this.store[child]]\n parent = child;\n } else {\n return parent;\n }\n }\n }\n\n shouldSwap(child, parent) {\n return child && this.compareFunction(this.store[child], this.store[parent]) < 0;\n }\n}", "solution_java": "class Solution {\n public int maxEvents(int[][] events) {\n Arrays.sort(events,(a,b)->a[1]==b[1]?a[0]-b[0]:a[1]-b[1]);\n // here sorting the array on ths basis of last day because we want to finish the events which happens first,fist.\n \n TreeSet set =new TreeSet<>();\n for(int i =1;i<=100000;i++){\n set.add(i);\n }\n //initliasing a tree set to check available days ;\n // a day can go maximum to 100000;\n int ans =0;\n for(int i =0;ievents[i][1])\n continue;\n else{\n set.remove(temp);\n ans +=1;\n }\n }\n return ans; \n }\n}", "solution_c": "class Solution {\npublic:\n int maxEvents(vector>& events) {\n int res=0;\n int m=0;\n for(auto x:events)\n m=max(m,x[1]);\n\n sort(events.begin(),events.end());\n int j=0;\n priority_queue,greater> pq;\n for(int i=1;i<=m;i++)\n {\n while(!pq.empty() && pq.top() str:\n LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR, DAY = 1, 1, 1971, 5\n DAYS = (\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\")\n\n difference = self.daysBetweenDates((LOWEST_DAY, LOWEST_MONTH, LOWEST_YEAR), (day, month, year))\n return DAYS[(difference + DAY) % 7]\n\n def daysBetweenDates(self, date1: tuple, date2: tuple) -> int:\n LOWEST_YEAR = 1971\n\n def daysSinceLowest(date: tuple) -> int:\n day, month, year = date\n\n isLeapYear = lambda x: 1 if (x % 4 == 0 and x % 100 != 0) or x % 400 == 0 else 0\n\n days: int = 0\n # days between the LOWEST_YEAR and year\n days += 365 * (year - LOWEST_YEAR) + sum(map(isLeapYear, range(LOWEST_YEAR, year)))\n # days between year and exact date\n daysInMonth = (31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)\n days += sum(daysInMonth[:month - 1]) + day\n return days\n\n return abs(daysSinceLowest(date1) - daysSinceLowest(date2))", "solution_js": "/**\n * @param {number} day\n * @param {number} month\n * @param {number} year\n * @return {string}\n */\nvar dayOfTheWeek = function(day, month, year) {\n var map = {\n 0: \"Sunday\",\n 1: \"Monday\",\n 2: \"Tuesday\",\n 3: \"Wednesday\",\n 4: \"Thursday\",\n 5: \"Friday\",\n 6: \"Saturday\"\n };\n var date = new Date(`${month}/${day}/${year}`);\n return map[date.getDay()];\n};", "solution_java": "class Solution {\n public String dayOfTheWeek(int day, int month, int year) {\n String[] week = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"};\n year--;\n int total = (year/4)*366+(year-year/4)*365;\n int[] months = {31,28,31,30,31,30,31,31,30,31,30,31};\n year++;\n if(year%4==0 && year!=2100){\n months[1]++;\n }\n for(int i=0;i Optional[ListNode]:\n if head == None:\n return None\n slow = head\n fast = head\n for i in range(n):\n fast = fast.next\n if fast == None:\n return head.next\n while fast != None and fast.next != None:\n slow = slow.next\n fast = fast.next\n slow.next = slow.next.next\n return head", "solution_js": "var removeNthFromEnd = function(head, n) {\n let start = new ListNode(0, head);\n let slow = start, fast = start;\n\n for (let i =1; i <= n; i++) {\n fast = fast.next;\n }\n\n while(fast && fast.next) {\n slow = slow.next;\n fast = fast.next;\n }\n\n let nthNode = slow.next\n slow.next = nthNode.next;\n\n return start.next;\n};", "solution_java": "class Solution {\n public ListNode removeNthFromEnd(ListNode head, int n) {\n ListNode temp = head;\n int len=0;\n\n if(head==null || head.next==null)\n return null;\n\n while(temp!=null){\n temp=temp.next;\n len++;\n }\n\n if(len==n)\n return head.next;\n\n int frontlen = len-n-1;\n\n ListNode first=head.next;\n ListNode second = head;\n\n int count=0;\n\n while(first!=null){\n if(count==frontlen){\n second.next=first.next;\n break;\n }else{\n first=first.next;\n second=second.next;\n count++;\n }\n }\n\n return head;\n }\n}", "solution_c": " * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* removeNthFromEnd(ListNode* head, int n) {\n ListNode* n1 = new ListNode();\n ListNode *temp=head;\n ListNode *p=head;\n ListNode *q=n1;\n n1->next=head;\n int count;\n while(temp)\n { \n \n if(n>0){\n n--;\n }\n else if(n==0){\n coutnext;\n q=q->next;\n }\n temp=temp->next;\n }\n q->next=p->next;\n delete p;\n return n1->next;\n }\n};" }, { "title": "Find All Duplicates in an Array", "algo_input": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.\n\nYou must write an algorithm that runs in O(n) time and uses only constant extra space.\n\n \nExample 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [2,3]\nExample 2:\nInput: nums = [1,1,2]\nOutput: [1]\nExample 3:\nInput: nums = [1]\nOutput: []\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 105\n\t1 <= nums[i] <= n\n\tEach element in nums appears once or twice.\n\n", "solution_py": "class Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n res = []\n hm = {}\n # adding entries in hashmap to check frequency\n for i, v in enumerate(nums):\n if v not in hm:\n hm[v] = 1\n else:\n hm[v] += 1\n # checking frequency of item and adding output to an array\n for key, value in hm.items():\n if value > 1:\n res.append(key)\n return res", "solution_js": "// Approach : Mark Visited Elements in the Input Array itself\nvar findDuplicates = function(nums) {\n let result = [];\n for(let i = 0; i < nums.length; i++) {\n let id = Math.abs(nums[i]) - 1;\n if(nums[id] < 0) result.push(id + 1);\n else nums[id] = - Math.abs(nums[id]);\n }\n return result;\n};", "solution_java": "class Solution {\n public List findDuplicates(int[] nums) {\n List ans = new ArrayList<>();\n for(int i=0;i findDuplicates(vector& nums) {\n int n=nums.size();\n vector a;\n vector arr(n+1,0);\n for(int i=0;i int:\n def check(x):\n return sum(ceil(ele/x) for ele in piles) <= h\n\n l = 1\n r = max(piles)\n while l < r:\n mid = (l+r) >> 1\n if not check(mid):\n l=mid+1\n else:\n r=mid\n return l", "solution_js": "var minEatingSpeed = function(piles, h) {\n /*The range of bananas that Koko can eat is k = 1 to Max(piles)*/\n let startk = 1;\n let endk = Math.max(...piles);\n \n while(startk <= endk){\n let midk = Math.floor(startk + (endk - startk)/2);\n /*midk are the count of bananas that koko decide to eat. \n So how many hours she will take to finish the piles?*/\n let hrs = 0;\n for(let pile of piles){\n /*pile is the num of bananas in piles*/\n hrs += Math.ceil(pile/midk);\n }\n if(hrs > h){\n /*Now if hrs > h she will not be to finish the pile so we have \n to increase the bananas by moving start.*/\n startk = midk + 1;\n }else{\n /*If hrs <= h she will be eating too fast so we can reduce the bananas \n so she eats slowly. So decrement end.*/\n endk = midk - 1;\n }\n }\n return startk;\n};", "solution_java": "class Solution {\n public int minEatingSpeed(int[] piles, int h) {\n int max=0;\n int ans=0;\n for(int i=0;ipiles[i]/mid)\n time+=num+1;\n else\n time+=num;\n }\n if(time<=h)\n {\n ans=mid;\n right=mid-1;\n }\n else\n left=mid+1;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minEatingSpeed(vector& piles, int h) {\n \n int mx=1000000001;\n \n \n int st=1;\n \n \n while(mx>st)\n {\n \n int k = ((mx+st)/2);\n \n int sum=0;\n \n for(int i =0 ;i < piles.size() ; i++)\n {\n sum+=ceil(1.0 *piles[i]/k);\n }\n \n if(sum>h)\n {\n st=k+1;\n }\n else\n {\n mx=k;\n }\n \n }\n \n \n return st;\n \n \n \n }\n};" }, { "title": "Finding the Users Active Minutes", "algo_input": "You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.\n\nMultiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.\n\nThe user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.\n\nYou are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.\n\nReturn the array answer as described above.\n\n \nExample 1:\n\nInput: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput: [0,2,0,0,0]\nExplanation:\nThe user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n\n\nExample 2:\n\nInput: logs = [[1,1],[2,2],[2,3]], k = 4\nOutput: [1,1,0,0]\nExplanation:\nThe user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n\n\n \nConstraints:\n\n\n\t1 <= logs.length <= 104\n\t0 <= IDi <= 109\n\t1 <= timei <= 105\n\tk is in the range [The maximum UAM for a user, 105].\n\n", "solution_py": "class Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n ret = [0] * k # UAM store\n user_acts = {} # User minutes store\n \n # Adding user minutes to hash table\n\t\tfor log in logs:\n if user_acts.get(log[0], 0):\n user_acts[log[0]].append(log[1])\n else:\n user_acts[log[0]] = [log[1]]\n \n # Calculating UAM\n\t\tfor k, v in user_acts.items():\n l = len(set(v))\n ret[l-1] += 1\n \n return ret", "solution_js": "var findingUsersActiveMinutes = function(logs, k) {\n const map = new Map();\n\n for (const [userID, minute] of logs) {\n if (!map.has(userID)) map.set(userID, new Set());\n map.get(userID).add(minute);\n }\n\n const count = new Array(k).fill(0);\n\n for (const actions of map.values()) {\n count[actions.size - 1]++;\n }\n\n return count;\n};", "solution_java": "class Solution {\n public int[] findingUsersActiveMinutes(int[][] logs, int k) {\n HashMap> usersMap = new HashMap();\n \n for(int[] log : logs){\n int user = log[0];\n int min = log[1];\n \n //add current user mapping, if not exist\n usersMap.putIfAbsent(user, new HashSet());\n \n //add unique new minute \n usersMap.get(user).add(min);\n }\n \n \n \n int[] result = new int[k];\n for(int user : usersMap.keySet()){\n int uam = usersMap.get(user).size();\n //increment users count\n result[uam - 1]++;\n }\n\n\t\treturn result;\n \n }\n \n}", "solution_c": "class Solution {\npublic:\n vector findingUsersActiveMinutes(vector>& logs, int k) \n {\n vectorans(k,0);\n unordered_map>m;\n\n for(int i = 0; i int:\n m, n = len(grid), len(grid[0])\n q = [(0, 0, 0)]\n dist = [[float('inf') for _ in range(n)] for _ in range(m)]\n\n while q:\n size = len(q)\n for _ in range(size):\n obs, x, y = heapq.heappop(q)\n if dist[x][y] < float('inf'): continue\n obs += grid[x][y]\n dist[x][y] = obs\n if x + 1 < m: heapq.heappush(q, (obs, x + 1, y))\n if x > 0: heapq.heappush(q, (obs, x - 1, y))\n if y + 1 < n: heapq.heappush(q, (obs, x, y + 1))\n if y > 0: heapq.heappush(q, (obs, x, y - 1))\n return dist[m - 1][n - 1]", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar minimumObstacles = function(grid) {\n let dx=[[0,1],[0,-1],[1,0],[-1,0]];\n let distance=[];\n for(let i=0;i0){\n let element = queue.shift();\n let row = element[0];\n let col = element[1];\n let originalDist = distance[row][col];\n for(let d=0;d=0 && i<=grid.length-1 && j>=0 && j<=grid[i].length-1){\n let dist = originalDist;\n if(grid[i][j]===1){\n dist++;\n }\n if(distance[i][j]>dist){//Update distance for this neighbour node if the new distance is smaller than the previous distance\n queue.push([i,j]);\n distance[i][j]=dist;\n }\n\n }\n }\n }\n //return the minimum distance for last cell after completing the process\n return distance[(grid.length-1)][(grid[row].length-1)];\n }\n};", "solution_java": "class Solution {\n int [][]grid;\n int n,m;\n boolean [][]seen;\n int []dx = new int[]{0,0,1,-1};\n int []dy = new int[]{1,-1,0,0};\n int [][]dp;\n int finalres;\n private boolean isValid(int i, int j) {\n return Math.min(i,j)>=0 && i=finalres) return finalres;\n if(i == n-1 && j == m-1) {\n return cnt;\n }\n if(dp[i][j]!=Integer.MAX_VALUE) return dp[i][j];\n int res = n*m+1;\n seen[i][j]=true;\n for(int k=0;k<4;k++) {\n int newI = i+dx[k], newJ = j+dy[k];\n if(isValid(newI, newJ)) {\n res = Math.min(res, solve(newI, newJ, cnt+grid[i][j]));\n }\n }\n seen[i][j]=false;\n return dp[i][j]=Math.min(dp[i][j], res);\n }\n \n public int minimumObstacles(int[][] grid) {\n this.grid = grid;\n this.n = grid.length;\n this.m = grid[0].length;\n this.seen = new boolean[n][m];\n dp = new int[n][m];\n finalres = n*m+1;\n for(int []row:dp) Arrays.fill(row, Integer.MAX_VALUE);\n return solve(0,0,0);\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumObstacles(vector>& grid) {\n int m=grid.size(), n=grid[0].size();\n vector dir={0,1,0,-1,0};\n vector> dist(m, vector (n,INT_MAX));\n vector> vis(m, vector(n,0));\n deque>q;\n dist[0][0]=0;\n q.push_front({0,0});\n while(!q.empty())\n {\n auto cur=q.front();\n q.pop_front();\n int x=cur.first;\n int y=cur.second;\n for(int i=0;i<4;i++)\n {\n int cx=x+dir[i];\n int cy=y+dir[i+1];\n if(cx>=0 and cy>=0 and cx int:\n hashMap = {}\n \n def helper(root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n if root in hashMap:\n return hashMap[root]\n ansOption1 = root.val\n if root.left is not None:\n ansOption1 += (helper(root.left.left) + helper(root.left.right))\n if root.right is not None:\n ansOption1 += (helper(root.right.left) + helper(root.right.right))\n ansOption2 = helper(root.left) + helper(root.right)\n ansFinal = max(ansOption1, ansOption2)\n hashMap[root] = ansFinal\n return ansFinal\n \n return helper(root)\n ", "solution_js": "var rob = function(root) {\n const dfs = (node = root) => {\n if (!node || node.val === null) return [0, 0];\n const { val, left, right } = node;\n const [robL, notRobL] = dfs(left);\n const [robR, notRobR] = dfs(right);\n const rob = val + notRobL + notRobR;\n const notRob = Math.max(robL, notRobL) + Math.max(robR, notRobR);\n\n return [rob, notRob];\n };\n\n return Math.max(...dfs());\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 static class Pair{\n int withRob=0;\n int withoutRob=0;\n } \n public int rob(TreeNode root) {\n Pair nodeRob=rob_(root);\n \n return Math.max(nodeRob.withRob,nodeRob.withoutRob);\n }\n \n public Pair rob_(TreeNode root){\n if(root==null){\n return new Pair();\n }\n \n Pair l=rob_(root.left);\n Pair r=rob_(root.right);\n \n Pair nodeRob=new Pair();\n nodeRob.withRob=root.val+l.withoutRob+r.withoutRob;\n nodeRob.withoutRob=Math.max(l.withRob,l.withoutRob)+Math.max(r.withRob,r.withoutRob);\n return nodeRob;\n }\n}", "solution_c": "class Solution {\npublic:\n vector dp(TreeNode* root)\n {\n vector ans(2,0); //dp[0]: maximal money you can get by robbing current node. dp[1]: maximal money you can get when not rob this node\n if(root==NULL) return ans;\n vector left=dp(root->left);\n vector right=dp(root->right);\n ans[0]=root->val+left[1]+right[1];\n ans[1]=max(left[0],left[1])+max(right[0],right[1]);\n return ans;\n }\n int rob(TreeNode* root) {\n vector ans=dp(root);\n return max(ans[0],ans[1]);\n }\n};" }, { "title": "Add Strings", "algo_input": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.\n\nYou must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.\n\n \nExample 1:\n\nInput: num1 = \"11\", num2 = \"123\"\nOutput: \"134\"\n\n\nExample 2:\n\nInput: num1 = \"456\", num2 = \"77\"\nOutput: \"533\"\n\n\nExample 3:\n\nInput: num1 = \"0\", num2 = \"0\"\nOutput: \"0\"\n\n\n \nConstraints:\n\n\n\t1 <= num1.length, num2.length <= 104\n\tnum1 and num2 consist of only digits.\n\tnum1 and num2 don't have any leading zeros except for the zero itself.\n\n", "solution_py": "class Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n def func(n):\n value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}\n result = 0\n for digit in n:\n result = 10 * result + value[digit]\n\n return result\n\n ans = func(num1) + func(num2)\n return str(ans)", "solution_js": "var addStrings = function(num1, num2) {\n let i = num1.length - 1;\n let j = num2.length - 1;\n let carry = 0;\n let sum = '';\n \n for (;i >= 0 || j >= 0 || carry > 0;i--, j--) {\n const digit1 = i < 0 ? 0 : num1.charAt(i) - '0';\n const digit2 = j < 0 ? 0 : num2.charAt(j) - '0';\n const digitsSum = digit1 + digit2 + carry;\n sum = `${digitsSum % 10}${sum}`;\n carry = Math.floor(digitsSum / 10);\n }\n \n return sum;\n};", "solution_java": "import java.math.BigInteger;\nclass Solution {\n public String addStrings(String num1, String num2) {\n return new BigInteger(num1).add(new BigInteger(num2)).toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string ans=\"\";\n int carry=0;\n string addStrings(string num1, string num2) {\n while(num1.size() && num2.size()){\n int sum= (num1.back() -'0' + num2.back() -'0' + carry) ;\n ans = (char)((sum%10) + '0') + ans;\n carry= sum/10;\n num1.pop_back();num2.pop_back();\n }\n\n while(num1.size()){\n int sum= (num1.back() -'0' + carry) ;\n ans = (char)((sum%10) + '0') + ans ;\n carry= sum/10;\n num1.pop_back();\n }\n while(num2.size()){\n int sum= (num2.back() -'0' + carry) ;\n ans = (char)((sum%10) + '0') + ans ;\n carry= sum/10;\n num2.pop_back();\n }\n if(carry) ans = (char)(carry+'0') + ans;\n return ans;\n\n }\n};" }, { "title": "Combinations", "algo_input": "Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].\n\nYou may return the answer in any order.\n\n \nExample 1:\n\nInput: n = 4, k = 2\nOutput: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation: There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.\n\n\nExample 2:\n\nInput: n = 1, k = 1\nOutput: [[1]]\nExplanation: There is 1 choose 1 = 1 total combination.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 20\n\t1 <= k <= n\n\n", "solution_py": "class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n return itertools.combinations(range(1, n+1), k)", "solution_js": "var combine = function(n, k) {\n\n function helper (start, end, combo, subset, answer) {\n if (combo==0) {\n answer.push([...subset])\n return;\n }\n if (end - start + 1 < combo) {\n return;\n }\n if (start > end) {\n return;\n }\n subset.push(start)\n helper(start+1, end, combo - 1, subset, answer)\n\n subset.pop()\n helper(start+1, end, combo, subset, answer)\n }\n\n const answer = []\n helper(1, n, k, [], answer)\n return answer\n};", "solution_java": "class Solution {\n public List> combine(int n, int k) {\n List> subsets=new ArrayList<>();\n generatesubsets(1,n,new ArrayList(),subsets,k);\n return subsets;\n }\n void generatesubsets(int start,int n,List current,List> subsets,int k){\n if(current.size()==k){\n subsets.add(new ArrayList(current));\n }\n for(int i=start;i<=n;i++){\n current.add(i);\n generatesubsets(i+1,n,current,subsets,k);\n current.remove(current.size()-1);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n void solve(vector arr,vector> &ans,vector &temp,int k,int x){\n if(temp.size()==k){\n ans.push_back(temp);\n return;\n }\n if(x>=arr.size()) return ;\n for(int i = x;i> combine(int n, int k) {\n vector> ans;\n vector temp;\n vector arr;\n for(int i = 1;i<=n;i++) arr.push_back(i);\n solve(arr,ans,temp,k,0);\n return ans;\n }\n};" }, { "title": "Longest Palindrome by Concatenating Two Letter Words", "algo_input": "You are given an array of strings words. Each element of words consists of two lowercase English letters.\n\nCreate the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.\n\nReturn the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.\n\nA palindrome is a string that reads the same forward and backward.\n\n \nExample 1:\n\nInput: words = [\"lc\",\"cl\",\"gg\"]\nOutput: 6\nExplanation: One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.\n\n\nExample 2:\n\nInput: words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput: 8\nExplanation: One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.\n\n\nExample 3:\n\nInput: words = [\"cc\",\"ll\",\"xx\"]\nOutput: 2\nExplanation: One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 105\n\twords[i].length == 2\n\twords[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution(object):\n def longestPalindrome(self, words):\n wc = collections.Counter(words)\n aa = 0 # count how many words contain only two identical letters like 'aa'\n center = 0 # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n abba = 0 # count how many word pairs like ('ab', 'ba') and they can put on both sides respectively\n\n for w, c in wc.items():\n if w[0] == w[1]: # like 'aa', 'bb', ...\n aa += c // 2 * 2 # if there are 3 'aa', we can only use 2 'aa' put on both sides respectively\n # if one count of 'aa' is odd, that means it can be the center of the palindrome, answer can plus 2\n if c % 2 == 1: center = 2\n else:\n abba += min(wc[w], wc[w[::-1]]) * 0.5 # will definitely double counting\n return aa * 2 + int(abba) * 4 + center", "solution_js": "var longestPalindrome = function(words) {\n const n = words.length;\n const map = new Map();\n\n let len = 0;\n\n for (const word of words) {\n const backward = word.split(\"\").reverse().join(\"\");\n\n if (map.has(backward)) {\n len += (word.length * 2);\n map.set(backward, map.get(backward) - 1);\n\n if (map.get(backward) === 0) map.delete(backward);\n }\n else {\n if (!map.has(word)) map.set(word, 0);\n map.set(word, map.get(word) + 1);\n }\n }\n\n let maxLenSelfPalindrome = 0;\n\n for (const word of map.keys()) {\n if (isPalindrome(word)) {\n maxLenSelfPalindrome = Math.max(maxLenSelfPalindrome, word.length);\n }\n }\n\n return len + maxLenSelfPalindrome;\n\n function isPalindrome(word) {\n let left = 0;\n let right = word.length - 1;\n\n while (left < right) {\n if (word[left] != word[right]) return false;\n left++;\n --right;\n }\n\n return true;\n }\n};", "solution_java": "class Solution {\n public int longestPalindrome(String[] words) {\n int[][] freq = new int[26][26];//array for all alphabet combinations\n for (String word : words)\n freq[word.charAt(0) - 'a'][word.charAt(1) - 'a']++;// here we first increase the freq for every word\n int left = 0;//to store freq counts\n boolean odd = false;\n for (int i = 0; i != 26; i++) {//iterate over our array\n odd |= (freq[i][i] & 1) == 1;//means odd number of freq for similar words are there\n left += freq[i][i] / 2;\n for (int j = i + 1; j != 26; j++)//nested iteration to find non similar pairs\n left += Math.min(freq[i][j], freq[j][i]);//taking min times from both present\n }\n int res = left * 2 * 2;//res from total freq found!!\n if (odd){\n res+=2;// if odd then adding 2\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestPalindrome(vector& words) {\n\n int count[26][26] = {};\n int ans =0;\n\n for(auto w : words){\n int a = w[0] - 'a';\n int b = w[1] - 'a';\n\n if(count[b][a]){\n ans+= 4;\n count[b][a]--; // decrement the count as we found mirror word\n }else\n count[a][b]++; //increment the current word count if we not find any mirror word\n }\n\n for(int i=0;i<26;i++){\n if(count[i][i]){\n ans+=2;\n break;\n }\n }\n\n return ans;\n\n }\n};" }, { "title": "Jump Game IV", "algo_input": "Given an array of integers arr, you are initially positioned at the first index of the array.\n\nIn one step you can jump from index i to index:\n\n\n\ti + 1 where: i + 1 < arr.length.\n\ti - 1 where: i - 1 >= 0.\n\tj where: arr[i] == arr[j] and i != j.\n\n\nReturn the minimum number of steps to reach the last index of the array.\n\nNotice that you can not jump outside of the array at any time.\n\n \nExample 1:\n\nInput: arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput: 3\nExplanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n\n\nExample 2:\n\nInput: arr = [7]\nOutput: 0\nExplanation: Start index is the last index. You do not need to jump.\n\n\nExample 3:\n\nInput: arr = [7,6,9,6,9,6,9,7]\nOutput: 1\nExplanation: You can jump directly from index 0 to index 7 which is last index of the array.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 5 * 104\n\t-108 <= arr[i] <= 108\n\n", "solution_py": "from collections import deque\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n minSteps = 0\n queue = deque()\n queue.append(0)\n n = len(arr)\n visited = set()\n visited.add(0)\n \n\t\td = {i:[] for i in arr}\n \n for i, val in enumerate(arr):\n d[val].append(i)\n \n while queue:\n for _ in range(len(queue)):\n idx = queue.popleft()\n if idx == n - 1:\n return minSteps\n \n for i in [*d[arr[idx]], idx - 1, idx + 1]:\n if i not in visited and 0 <= i < n:\n visited.add(i)\n queue.append(i)\n d[arr[idx]].clear()\n minSteps += 1", "solution_js": "/**\n * @param {number[]} arr\n * @return {number}\n */\nvar minJumps = function(arr) {\n if(arr.length <= 1) return 0;\n \n const graph = {};\n \n for(let idx = 0; idx < arr.length; idx ++) {\n const num = arr[idx];\n if(graph[num] === undefined) graph[num] = [];\n graph[num].push(idx);\n }\n \n let queue = [];\n const visited = new Set();\n \n queue.push(0);\n visited.add(0);\n \n let steps = 0;\n \n while(queue.length) {\n const nextQueue = [];\n \n for(const idx of queue) {\n if(idx === arr.length - 1) return steps;\n \n const num = arr[idx];\n \n for(const neighbor of graph[num]) {\n if(!visited.has(neighbor)) {\n visited.add(neighbor);\n nextQueue.push(neighbor);\n }\n }\n \n if(idx + 1 < arr.length && !visited.has(idx + 1)) {\n visited.add(idx + 1);\n nextQueue.push(idx + 1);\n }\n \n if(idx - 1 >= 0 && !visited.has(idx - 1)) {\n visited.add(idx - 1);\n nextQueue.push(idx - 1);\n }\n \n graph[num].length = 0;\n }\n \n queue = nextQueue;\n steps ++;\n }\n \n return -1;\n};", "solution_java": "/*\nHere we are using map and queue\nmap for storing the array elements and where are the other indices of the same element\nand queue for BFS\n\nInitially we start with 0 index\nSo we offer it to the queue\nNow until the queue is empty we have to do few things for a given position\ni> check the next index (i+1)\nii> check the previous index(i-1)\niii> check all the indices of the list whih are present in the map\nonce these three things have been done we will\nremove the element that is arr[i]\nbecause if we did not remove it we are going to do the same repeated task over and over again\nand this will result in stack overflow\nso it is important to remove the indices which have been visited once\nevery time we check the queue we incease the answer because viewing a queue means that\nwe are not at the last index\n\nI hope the idea was clear :) you'll understand better when you see the code\n*/\nclass Solution {\n public int minJumps(int[] arr) {\n int n = arr.length;\n\n if(n <= 1) return 0;\n Map> mp = new HashMap<>();\n for(int i = 0;i < arr.length ; i++) {\n if(!mp.containsKey(arr[i])) {\n mp.put(arr[i],new ArrayList<>());\n }\n List ls = mp.get(arr[i]);\n ls.add(i);\n }\n //System.out.print(mp);\n Queue q = new LinkedList<>();\n q.offer(0);\n int ans = 0;\n while(!q.isEmpty()) {\n ans++;\n int size = q.size();\n for(int i = 0;i < size;i++)\n {\n int j = q.poll();\n //adding j+1\n if(j+1 < n && mp.containsKey(arr[j+1])) {\n if(j+1 == n-1) return ans;\n q.offer(j+1);\n }\n //adding j-1\n if(j-1 > 0 && mp.containsKey(arr[j-1])) {\n q.offer(j-1);\n }\n\n //adding list indices\n if(mp.containsKey(arr[j])) {\n for(int k : mp.get(arr[j])) {\n //if(k == n-1) return ans;\n if(k != j) {\n if(k == n-1) return ans;\n q.offer(k);\n }\n }\n mp.remove(arr[j]);\n }\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int minJumps(vector& arr) \n {\n int n = arr.size();\n unordered_map>mp;\n for (int i = 0; i < n; i++) mp[arr[i]].push_back(i);\n \n queueq;\n vectorvisited(n, false);\n q.push(0);\n int steps = 0;\n while(!q.empty())\n {\n int size = q.size();\n while(size--)\n {\n int currIdx = q.front();\n q.pop();\n if (currIdx == n - 1) return steps;\n //================================================================\n //EXPLORE ALL POSSIBLE OPTIONS\n if (currIdx + 1 < n && !visited[currIdx + 1]) //OPTION-1 (Move Forward)\n {\n visited[currIdx + 1] = true;\n q.push(currIdx + 1);\n }\n if (currIdx - 1 >= 0 && !visited[currIdx - 1]) //OPTION-2 (Move Backward)\n {\n visited[currIdx - 1] = true;\n q.push(currIdx - 1);\n }\n for (int newIdx : mp[arr[currIdx]]) //OPTION-3 (Move to same valued idx)\n { //newIdx coud be before currIdx or after currIdx\n if (!visited[newIdx]) \n {\n visited[newIdx] = true;\n q.push(newIdx);\n }\n }\n //===================================================================\n mp[arr[currIdx]].clear(); //EXPLAINED BELOW :)\n }\n steps++;\n }\n return -1;\n }\n};" }, { "title": "Loud and Rich", "algo_input": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.\n\nYou are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).\n\nReturn an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.\n\n \nExample 1:\n\nInput: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput: [5,5,2,5,4,5,6,7]\nExplanation: \nanswer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.\n\n\nExample 2:\n\nInput: richer = [], quiet = [0]\nOutput: [0]\n\n\n \nConstraints:\n\n\n\tn == quiet.length\n\t1 <= n <= 500\n\t0 <= quiet[i] < n\n\tAll the values of quiet are unique.\n\t0 <= richer.length <= n * (n - 1) / 2\n\t0 <= ai, bi < n\n\tai != bi\n\tAll the pairs of richer are unique.\n\tThe observations in richer are all logically consistent.\n\n", "solution_py": "class Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n length = len(quiet)\n arr = [i for i in range(length)]\n indegree = [0 for _ in range(length)]\n graph = collections.defaultdict(list)\n dq = collections.deque([])\n \n for a, b in richer:\n # Note that the graph is uni-directional\n graph[a].append(b)\n indegree[b] += 1\n\n for i in range(length):\n if not indegree[i]: \n dq.append(i)\n \n while dq:\n node = dq.popleft()\n \n for vertex in graph[node]:\n indegree[vertex] -= 1\n if quiet[arr[node]] < quiet[arr[vertex]]:\n arr[vertex] = arr[node]\n if not indegree[vertex]:\n dq.append(vertex)\n return arr", "solution_js": "var loudAndRich = function(richer, quiet) {\n const map = new Map();\n for (const [rich, poor] of richer) {\n map.set(poor, (map.get(poor) || new Set()).add(rich)); \n }\n \n const memo = new Map();\n const getQuietest = (person) => {\n if (memo.has(person)) return memo.get(person);\n const richerList = map.get(person);\n let min = quiet[person];\n let quietest = person;\n if (!richerList) {\n memo.set(person, quietest);\n return quietest;\n }\n for (const rich of richerList) { \n if (quiet[getQuietest(rich)] < min) {\n min = quiet[getQuietest(rich)];\n quietest = getQuietest(rich);\n } \n }\n memo.set(person, quietest);\n return quietest;\n }\n const answer = [];\n for (let i=0; i> adj =new ArrayList<>();\n int res[];\n public int[] loudAndRich(int[][] richer, int[] quiet) {\n int n=quiet.length;\n res=new int[n];\n Arrays.fill(res,-1);\n for(int i=0;i());\n for(int i=0;i());\n adj.get(richer[i][1]).add(richer[i][0]);\n }\n for(int i=0;i &answer,vector adjList[],vector& quiet)\n {\n if(answer[node]==-1)\n {\n answer[node] = node;\n for(int child:adjList[node])\n {\n int cand = dfs(child,answer,adjList,quiet);\n if(quiet[cand] loudAndRich(vector>& richer, vector& quiet) {\n\n int n = quiet.size();\n\n vector adjList[n];\n\n for(auto x:richer)\n {\n int v = x[0];\n int u = x[1];\n adjList[u].push_back(v);\n }\n\n vector answer(n,-1);\n\n for(int node =0;node int:\n n_to_list = list(str(n))\n \n sum_of_digits = 0 \n for num in n_to_list:\n sum_of_digits = sum_of_digits + int(num)\n \n product_of_digits = 1\n for num in n_to_list:\n product_of_digits = product_of_digits * int(num)\n \n answer = product_of_digits - sum_of_digits\n \n return answer", "solution_js": "var subtractProductAndSum = function(n) {\n let product=1,sum=0\n n=n.toString().split('')\n n.forEach((x)=>{\n product *=parseInt(x)\n sum +=parseInt(x)\n }\n )\n return product-sum\n };", "solution_java": "class Solution {\n public int subtractProductAndSum(int n) {\n int mul=1,sum=0;\n while(n!=0){\n sum=sum+n%10;\n mul=mul*(n%10);\n n=n/10;\n }\n return mul-sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int subtractProductAndSum(int n) {\n vector digit;\n int product=1;\n int sum=0;\n while(n>0){\n digit.push_back(n%10);\n n/=10;\n }\n for(int i=0;i List[int]:\n result = []\n min_ = 0\n max_ = len(s)\n for x in s:\n if x==\"I\":\n result.append(min_)\n min_ += 1\n elif x==\"D\":\n result.append(max_)\n max_ -= 1\n result.append(min_)\n return result", "solution_js": "var diStringMatch = function(s) {\n let i = 0, d = s.length, arr = [];\n \n for(let j = 0; j <= s.length; j += 1) {\n if(s[j] === 'I') arr.push(i++);\n else arr.push(d--);\n }\n \n return arr;\n};", "solution_java": "class Solution {\n public int[] diStringMatch(String s) {\n int low = 0;\n int high = s.length();\n int[] ans = new int[s.length() + 1];\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'I'){\n ans[i] = low++;\n } else{\n ans[i] = high--;\n }\n }\n ans[s.length()] = high;\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector diStringMatch(string s) {\n int p=0, j=s.size();\n vectorv;\n for(int i=0; i<=s.size(); i++)\n {\n if(s[i]=='I')v.push_back(p++);\n else v.push_back(j--);\n }\n return v;\n }\n};" }, { "title": "Partition Array Such That Maximum Difference Is K", "algo_input": "You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.\n\nReturn the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.\n\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n\n \nExample 1:\n\nInput: nums = [3,6,1,2,5], k = 2\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.\n\n\nExample 2:\n\nInput: nums = [1,2,3], k = 1\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].\n\n\nExample 3:\n\nInput: nums = [2,2,4,5], k = 0\nOutput: 3\nExplanation:\nWe can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\t0 <= k <= 105\n\n", "solution_py": "class Solution:\n def partitionArray(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = 1\n\t\t# To keep track of starting element of each subsequence\n start = nums[0]\n \n for i in range(1, len(nums)):\n diff = nums[i] - start\n if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n ans += 1\n start = nums[i]\n \n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar partitionArray = function(nums, k) {\n\n nums.sort((a,b) =>{ return a-b})\n\n let n = nums.length ,ans=0\n\n for(let i=0 ; i& nums, int k) {\n \n int n(size(nums)), res(0);\n sort(begin(nums), end(nums));\n \n for (int start=0, next=0; start int:\n # Complexity:\n # - Time: O(N*K)\n # - Space: O(K)\n\n # Special cases that can be short-circuited right away\n # - For k=0, there's only one solution, which is having the numbers in sorted order\n # DP(n, 0) = 1\n if k == 0:\n return 1\n # - There can't be more than n*(n-1)/2 inverse pairs, which corresponds to the numbers in reverse order\n # DP(n, k) = 0 for all k > n*(n-1)/2\n if k > n * (n - 1) // 2:\n return 0\n\n # For the general case, we notice that:\n # DP(n+1, k) = sum(DP(n, i) for i in [max(0, k-n), k])\n # i.e., adding an additional number (the biggest one n+1):\n # - We can have it at the end, in which case it doesn't create any reverse pairs,\n # and so the number of configurations with k reverse pairs is DP(n,k)\n # - Or we can have it one before the end, in which case it creates exactly reverse pairs,\n # and so the number of configurations with k reverse pairs is DP(n,k-1)\n # - And so on and so forth, such that having it `i` places before the end create exactly `i` reverse pairs,\n # and so the number of configurations with k reverse pairs is DP(n,k-i)\n # This relationship allows us to compute things iteratively with a rolling window sum\n kLine = [0] * (k + 1)\n kLine[0] = 1\n previousKLine = kLine.copy()\n maxFeasibleK = 0\n for m in range(2, n + 1):\n previousKLine, kLine = kLine, previousKLine\n rollingWindowSum = 1\n maxFeasibleK += m - 1\n endKLineIdx = min(k, maxFeasibleK) + 1\n intermediateKLineIdx = min(endKLineIdx, m)\n for kLineIdx in range(1, intermediateKLineIdx):\n rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx]) % _MODULO\n kLine[kLineIdx] = rollingWindowSum\n for kLineIdx in range(intermediateKLineIdx, endKLineIdx):\n rollingWindowSum = (rollingWindowSum + previousKLine[kLineIdx] - previousKLine[kLineIdx - m]) % _MODULO\n kLine[kLineIdx] = rollingWindowSum\n return kLine[k]\n\n\n_MODULO = 10 ** 9 + 7", "solution_js": "var kInversePairs = function(n, k) {\n const dp = new Array(n+1).fill(0).map(el => new Array(k+1).fill(0))\n const MOD = Math.pow(10, 9) + 7\n\n for(let i = 0; i < n+1; i++) {\n dp[i][0] = 1\n }\n\n for(let i = 1; i <= n; i++) {\n for(let j = 1; j <= k; j++) {\n dp[i][j] = (dp[i][j-1] + dp[i-1][j] % MOD) - (j >= i ? dp[i-1][j-i] : 0)%MOD\n }\n }\n\n return dp[n][k] % MOD\n};", "solution_java": "class Solution {\n public int kInversePairs(int n, int k) {\n int MOD = 1000000007;\n int[][] opt = new int[k + 1][n];\n for (int i = 0; i <= k; i++) {\n for (int j = 0; j < n; j++) {\n if (i == 0) {\n opt[i][j] = 1;\n } else if (j > 0) {\n opt[i][j] = (opt[i - 1][j] + opt[i][j - 1]) % MOD;\n if (i >= j + 1) {\n opt[i][j] = (opt[i][j] - opt[i - j - 1][j - 1] + MOD) % MOD;\n }\n }\n }\n }\n\n return opt[k][n - 1];\n }\n}", "solution_c": "class Solution {\npublic:\n int mod = (int)(1e9 + 7);\n int dp[1001][1001] = {};\n \n int kInversePairs(int n, int k) {\n //base case\n if(k<=0) return k==0;\n \n if(dp[n][k]==0){\n dp[n][k] = 1;\n \n for(int i=0; i Optional[TreeNode]:\n def search(root):\n if not root:return None\n if root.val==val:\n return root\n elif root.val val ? node.left : node.right\n }\n\n return node\n}", "solution_java": "class Solution {\n public TreeNode searchBST(TreeNode root, int val) {\n if (root == null) return root;\n if (root.val == val) {\n return root;\n } else {\n return val < root.val ? searchBST(root.left, val) : searchBST(root.right, val);\n }\n }\n}", "solution_c": "// Recursive\nclass Solution {\npublic:\n TreeNode* searchBST(TreeNode* root, int& val) {\n if(root==NULL) return NULL;\n if(root->val==val) return root;\n if(root->val>val) return searchBST(root->left,val);\n return searchBST(root->right,val);\n }\n};\n\n// Iterative\nclass Solution {\npublic:\n TreeNode* searchBST(TreeNode* root, int val) {\n while(root){\n if(root->val==val) return root;\n root=root->val>val?root->left:root->right;\n }\n return NULL;\n }\n};" }, { "title": "The Score of Students Solving Math Expression", "algo_input": "You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:\n\n\n\tCompute multiplication, reading from left to right; Then,\n\tCompute addition, reading from left to right.\n\n\nYou are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:\n\n\n\tIf an answer equals the correct answer of the expression, this student will be rewarded 5 points;\n\tOtherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;\n\tOtherwise, this student will be rewarded 0 points.\n\n\nReturn the sum of the points of the students.\n\n \nExample 1:\n\nInput: s = \"7+3*1*2\", answers = [20,13,42]\nOutput: 7\nExplanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\n\n\nExample 2:\n\nInput: s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput: 19\nExplanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\n\n\nExample 3:\n\nInput: s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput: 10\nExplanation: The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 31\n\ts represents a valid expression that contains only digits 0-9, '+', and '*' only.\n\tAll the integer operands in the expression are in the inclusive range [0, 9].\n\t1 <= The count of all operators ('+' and '*') in the math expression <= 15\n\tTest data are generated such that the correct answer of the expression is in the range of [0, 1000].\n\tn == answers.length\n\t1 <= n <= 104\n\t0 <= answers[i] <= 1000\n\n", "solution_py": "class Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \n @cache\n def fn(lo, hi): \n \"\"\"Return possible answers of s[lo:hi].\"\"\"\n if lo+1 == hi: return {int(s[lo])}\n ans = set()\n for mid in range(lo+1, hi, 2): \n for x in fn(lo, mid): \n for y in fn(mid+1, hi): \n if s[mid] == \"+\" and x + y <= 1000: ans.add(x + y)\n elif s[mid] == \"*\" and x * y <= 1000: ans.add(x * y)\n return ans \n \n target = eval(s)\n cand = fn(0, len(s))\n ans = 0 \n for x in answers: \n if x == target: ans += 5\n elif x in cand: ans += 2\n return ans ", "solution_js": "var scoreOfStudents = function(s, answers) {\n let correct=s.split('+').reduce((a,c)=>a+c.split('*').reduce((b,d)=>b*d,1),0),\n n=s.length,dp=[...Array(n)].map(d=>[...Array(n)])\n let dfs=(i=0,j=n-1)=>{\n if(dp[i][j]!==undefined)\n return dp[i][j]\n if(i===j)\n return dp[i][j]=[Number(s[i])]\n let ans=new Set()\n for(let k=i+1;k<=j-1;k+=2)\n for(let a1 of dfs(i,k-1))\n for(let a2 of dfs(k+1,j))\n if(s[k]==='*')\n ans.add(Number(a1)*Number(a2))\n else\n ans.add(Number(a1)+Number(a2))\n return dp[i][j]=Array.from(ans).filter(d=>d<=1000)\n }\n dfs()\n dp[0][n-1]=new Set(dp[0][n-1])\n return answers.reduce( (a,c)=> a+ (c===correct?5:(dp[0][n-1].has(c)?2:0)) ,0)\n};", "solution_java": "class Solution {\n\n HashMap> cache ;\n\n public int scoreOfStudents(String s, int[] answers) {\n\n cache = new HashMap();\n HashSet total_possible_ans = getPossibleAns(s);\n\n int correct_ans = getCorrectAns(s);\n\n int total_score = 0 ;\n for(int i=0 ; i getPossibleAns(String s){\n\n if(cache.containsKey(s)){\n return cache.get(s) ;\n }\n\n HashSet possible_ans = new HashSet() ;\n\n for(int i = 0 ; i left = new HashSet() ;\n HashSet right = new HashSet() ;\n\n if(cur == '+' || cur == '*'){\n left = getPossibleAns(s.substring(0 , i));\n right = getPossibleAns(s.substring(i+1));\n }\n\n for(Integer l : left){\n for(Integer r : right){\n if(cur == '+'){\n if(l+r > 1000) continue ; // skiping for ans that are greater than 1000\n possible_ans.add(l+r);\n }else if(cur == '*'){\n if(l*r > 1000) continue ; // skiping for ans that are greater than 1000\n possible_ans.add(l*r);\n }\n }\n }\n }\n\n if(possible_ans.isEmpty() && s.length() <= 1){\n possible_ans.add(Integer.parseInt(s));\n }\n\n cache.put(s , possible_ans);\n\n return possible_ans ;\n }\n\n public int getCorrectAns(String s) {\n\n Stack stack = new Stack() ;\n\n for(int i = 0 ; i> mp;\n unordered_set potential;\n \n unordered_set& solve(string_view s) {\n if (auto it = mp.find(s); it != mp.end()) {\n return it->second;\n }\n \n bool res = true;\n int n = 0;\n unordered_set ans;\n for (int i = 0; i < s.size(); i++) {\n char c = s[i];\n if (c >= '0' && c <= '9') {\n n = n * 10 + (c - '0');\n } else {\n n = 0;\n res = false;\n for (int l : solve(s.substr(0, i))) {\n for (int r : solve(s.substr(i + 1))) {\n int res2 = eval(l, r, c);\n if (res2 <= 1000) {\n ans.insert(res2);\n }\n }\n }\n }\n }\n if (res) {\n ans.insert(n);\n }\n return mp[s] = ans;\n }\n \npublic:\n int scoreOfStudents(string s, vector& answers) {\n int ans = 0, correct = 0;\n stack ns, op;\n unordered_map prec{\n {'+', 1},\n {'*', 2},\n {'(', 0}\n };\n int n = 0;\n for (int i = 0; i < s.size(); i++) {\n char c = s[i];\n if (c >= '0' && c <= '9') {\n n = n * 10 + (c - '0');\n } else if (c == '(') {\n op.push(c);\n } else if (c == ')') {\n ns.push(n);\n while (op.top() != '(') {\n int b = ns.top();\n ns.pop();\n int a = ns.top();\n ns.pop();\n ns.push(eval(a, b, op.top()));\n op.pop();\n }\n op.pop();\n n = ns.top();\n ns.pop();\n } else {\n ns.push(n);\n n = 0;\n int p = prec[c];\n while (!op.empty() && prec[op.top()] >= p) {\n int b = ns.top();\n ns.pop();\n int a = ns.top();\n ns.pop();\n ns.push(eval(a, b, op.top()));\n op.pop();\n }\n op.push(c);\n }\n }\n ns.push(n);\n while (!op.empty()) {\n int b = ns.top();\n ns.pop();\n int a = ns.top();\n ns.pop();\n ns.push(eval(a, b, op.top()));\n op.pop();\n }\n correct = ns.top();\n \n string_view sv{s.data(), s.size()};\n solve(sv);\n for (int n2 : mp[sv]) {\n potential.insert(n2);\n }\n \n for (int n2 : answers) {\n if (n2 == correct) {\n ans += 5;\n } else if (potential.find(n2) != potential.end()) {\n ans += 2;\n }\n }\n return ans;\n }\n};" }, { "title": "Cut Off Trees for Golf Event", "algo_input": "You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:\n\n\n\t0 means the cell cannot be walked through.\n\t1 represents an empty cell that can be walked through.\n\tA number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.\n\n\nIn one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\n\nYou must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).\n\nStarting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.\n\nNote: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.\n\n \nExample 1:\n\nInput: forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput: 6\nExplanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n\n\nExample 2:\n\nInput: forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput: -1\nExplanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n\n\nExample 3:\n\nInput: forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput: 6\nExplanation: You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n\n\n \nConstraints:\n\n\n\tm == forest.length\n\tn == forest[i].length\n\t1 <= m, n <= 50\n\t0 <= forest[i][j] <= 109\n\tHeights of all trees are distinct.\n\n", "solution_py": "from collections import deque\n\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n a = []\n n = len(forest)\n m = len(forest[0])\n for i in range(n):\n for j in range(m):\n if forest[i][j] > 1:\n a.append(forest[i][j])\n a.sort()\n \n s = 0\n ux = 0\n uy = 0\n for h in a:\n dist = [[None] * m for i in range(n)]\n q = deque()\n q.append((ux, uy))\n dist[ux][uy] = 0\n while q:\n ux, uy = q.popleft()\n if forest[ux][uy] == h:\n break\n d = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n for dx, dy in d:\n vx = ux + dx\n vy = uy + dy\n if vx < 0 or vx >= n or vy < 0 or vy >= m:\n continue\n if forest[vx][vy] == 0:\n continue\n if dist[vx][vy] is None:\n q.append((vx, vy))\n dist[vx][vy] = dist[ux][uy] + 1\n if forest[ux][uy] == h:\n s += dist[ux][uy]\n else:\n return -1\n return s", "solution_js": "var cutOffTree = function(forest) {\n const trees = forest.flat().filter(x => x && x !== 1).sort((a, b) => b - a);\n let currPos = [0, 0], totalDist = 0;\n\n while(trees.length) {\n const grid = [...forest.map(row => [...row])];\n const res = getDist(currPos, trees.pop(), grid);\n if(res == null) return -1;\n const [pos, dist] = res;\n currPos = pos;\n totalDist += dist;\n }\n return totalDist; \n \n function getDist(start, target, grid) {\n const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]];\n let queue = [start], dist = 0;\n \n while(queue.length) {\n const next = [];\n \n for(let [r, c] of queue) {\n if(grid[r][c] === target) return [[r, c], dist];\n if(!grid[r][c]) continue;\n \n for(let [x, y] of dir) {\n x += r; y += c;\n if(x >= 0 && x < grid.length && y >= 0 && \n y < grid[0].length && grid[x][y]) next.push([x, y])\n }\n grid[r][c] = 0; \n }\n dist++;\n queue = next;\n }\n return null;\n }\n};", "solution_java": "class Solution {\n //approach: 1st store all the positions in the min heap acc. to their height\n //now start removing the elements from the heap and calculate their dis using bfs\n // if at any point we cann't reach at the next position return -1;\n // else keep on adding the distances and return;\n public int cutOffTree(List> forest) {\n PriorityQueue pq=new PriorityQueue<>((a,b)->(forest.get(a[0]).get(a[1])-forest.get(b[0]).get(b[1])));\n for(int i=0;i1)\n pq.add(new int[]{i,j});\n }\n }\n int ans=0;\n int curr[]={0,0};\n while(pq.size()>0){\n int[] temp=pq.poll();\n int dis=calcDis(forest,curr,temp);\n //System.out.println(dis+\" \"+temp.height);\n if(dis==-1)\n return -1;\n ans+=dis;\n curr=temp;\n }\n return ans;\n }\n int calcDis(List> forest,int start[],int end[]){\n int n=forest.size(),m=forest.get(0).size();\n boolean vis[][]=new boolean[n][m];\n Queue queue=new LinkedList<>();\n queue.add(start);\n vis[start[0]][start[1]]=true;\n int dis=0;\n while(queue.size()>0){\n int len =queue.size();\n while(len-->0){\n int temp[]=queue.remove();\n int r=temp[0],c=temp[1];\n if(r==end[0] && c==end[1])\n return dis;\n if(r+1=0 && !vis[r-1][c] && forest.get(r-1).get(c)!=0){\n queue.add(new int[]{r-1,c});\n vis[r-1][c]=true;\n }if(c-1>=0 && !vis[r][c-1] && forest.get(r).get(c-1)!=0){\n queue.add(new int[]{r,c-1});\n vis[r][c-1]=true;\n }if(c+1\n #define vvi vector\n \n vvi forests;\n vvi moves;\n int R;\n int C;\n \n \n bool isValid(int x,int y){\n return x>=0&&x=0&&y>Q;\n Q.push({sx,sy});\n \n vis[sx][sy] = 1;\n \n \n int level = 0;\n \n while(!Q.empty()){\n \n queue>childQ;\n \n while(!Q.empty()){\n \n auto x = Q.front().first;\n auto y = Q.front().second;\n \n Q.pop();\n \n if(x==ex&&y==ey)\n return level;\n \n for(auto ele:moves){\n \n int nextX = x+ele[0];\n int nextY = y+ele[1];\n \n if(isValid(nextX,nextY)&&!vis[nextX][nextY]&&forests[nextX][nextY]>0){\n childQ.push({nextX,nextY});\n vis[nextX][nextY]=1;\n }\n \n }\n \n \n }\n Q=childQ;\n \n level++;\n }\n \n return -1;\n }\n \n int cutOffTree(vector>& forest) {\n \n moves={\n {0,1},\n {1,0},\n {0,-1},\n {-1,0}\n };\n \n forests = forest;\n \n R = forest.size();\n C = forest[0].size();\n \n if(forest[0][0]==0)\n return -1;\n \n vector>trees;\n int i=0;\n \n while(i1)\n trees.push_back({forest[i][j],i,j});\n \n j++;\n }\n i++;\n }\n \n if(trees.empty())\n return -1;\n \n sort(trees.begin(),trees.end());\n \n int sx = 0;\n int sy = 0;\n \n int ans = 0;\n \n for(auto it:trees){\n \n int dis = getShortestDistance(sx,sy,it[1],it[2]);\n \n if(dis==-1)\n return -1;\n ans+=dis;\n sx = it[1];\n sy = it[2];\n }\n \n return ans;\n \n }\n};" }, { "title": "Paint House III", "algo_input": "There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.\n\nA neighborhood is a maximal group of continuous houses that are painted with the same color.\n\n\n\tFor example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].\n\n\nGiven an array houses, an m x n matrix cost and an integer target where:\n\n\n\thouses[i]: is the color of the house i, and 0 if the house is not painted yet.\n\tcost[i][j]: is the cost of paint the house i with the color j + 1.\n\n\nReturn the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.\n\n \nExample 1:\n\nInput: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 9\nExplanation: Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n\n\nExample 2:\n\nInput: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 11\nExplanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.\n\n\nExample 3:\n\nInput: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput: -1\nExplanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n\n\n \nConstraints:\n\n\n\tm == houses.length == cost.length\n\tn == cost[i].length\n\t1 <= m <= 100\n\t1 <= n <= 20\n\t1 <= target <= m\n\t0 <= houses[i] <= n\n\t1 <= cost[i][j] <= 104\n\n", "solution_py": "class Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n @cache\n def dp(i, p, h):\n if (h > target) or (i == m and h != target):\n return inf\n if i == m:\n return 0\n if houses[i] != 0:\n return dp(i + 1, houses[i], h + int(p != houses[i]))\n\n best = inf\n for j, c in enumerate(cost[i], 1):\n best = min(best, dp(i + 1, j, h + int(p != j)) + c)\n return best\n\n res = dp(0, 0, 0)\n return res if res != inf else -1", "solution_js": "var minCost = function(houses, cost, m, n, target) {\n let map = new Map();\n\n function dfs(idx = 0, prevColor = -1, neighborhoods = 0) {\n if (idx === m) return neighborhoods === target ? 0 : Infinity;\n\n let key = `${idx}-${prevColor}-${neighborhoods}`;\n if (map.has(key)) return map.get(key);\n \n let color = houses[idx];\n // If the current house is already painted\n if (color > 0) {\n return color !== prevColor ? dfs(idx + 1, color, neighborhoods + 1) : dfs(idx + 1, color, neighborhoods);\n }\n\n let minCost = Infinity;\n for (let i = 1; i <= n; i++) {\n let potentialCost;\n // If color i is !== prevColor, increment the neighborhood count\n if (i !== prevColor) potentialCost = dfs(idx + 1, i, neighborhoods + 1);\n // Otherwise, the neighborhood simply expanded so the neighborhood count stays the same\n else potentialCost = dfs(idx + 1, i, neighborhoods);\n \n if (potentialCost === Infinity) continue;\n minCost = Math.min(minCost, cost[idx][i - 1] + potentialCost);\n }\n map.set(key, minCost);\n return minCost;\n }\n \n let minCost = dfs();\n return minCost === Infinity ? -1 : minCost;\n};", "solution_java": "class Solution {\n public int helper(int idx, int[] houses, int[][] cost,int target, int prevColor,int neigh,Integer[][][] dp)\n {\n if(idx==houses.length || neigh>target)\n {\n if(neigh==target)\n return 0;\n return Integer.MAX_VALUE;\n }\n if(dp[idx][prevColor][neigh]!=null)\n return dp[idx][prevColor][neigh];\n int minCost = Integer.MAX_VALUE;\n\n if(houses[idx]==0)\n {\n for(int j = 0;j h;//m\n vector> c;//n\n int mm; int nn; int t;\n int dfs(int idx, int prev, int curt){\n if(curt<1)\n return INT_MAX;\n if(idx==mm)\n return (curt==1)?0:INT_MAX;\n if(dp[idx][prev][curt]!=-1)\n return dp[idx][prev][curt];\n int res=INT_MAX;\n int color=h[idx];\n if(color==0){\n for(int x=0;x& houses, vector>& cost, int m, int n, int target) {\n h=houses,c=cost,mm=m,nn=n,t=target;\n memset(dp,-1,sizeof(dp));\n int res=dfs(0,21,t);\n return res==INT_MAX?-1:res;\n }\n};" }, { "title": "Basic Calculator", "algo_input": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.\n\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n\n \nExample 1:\n\nInput: s = \"1 + 1\"\nOutput: 2\n\n\nExample 2:\n\nInput: s = \" 2-1 + 2 \"\nOutput: 3\n\n\nExample 3:\n\nInput: s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput: 23\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 3 * 105\n\ts consists of digits, '+', '-', '(', ')', and ' '.\n\ts represents a valid expression.\n\t'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).\n\t'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).\n\tThere will be no two consecutive operators in the input.\n\tEvery number and running calculation will fit in a signed 32-bit integer.\n\n", "solution_py": "```class Solution:\n def calculate(self, s: str) -> int:\n curr,output,sign,stack = 0,0,1,[]\n\n for ch in s:\n if ch.isdigit():\n curr = curr * 10 + int(ch)\n\n elif ch == '+':\n output += sign * curr\n sign = 1\n curr = 0\n\n elif ch == '-':\n output += sign * curr\n sign = -1\n curr = 0\n\n elif ch == '(':\n #push the result and then the sign\n stack.append(output)\n stack.append(sign)\n sign = 1\n output = 0\n\n elif ch == ')':\n output += sign * curr\n output *= stack.pop()\n output += stack.pop()\n curr = 0\n return output + sign*curr``", "solution_js": "var calculate = function(s) {\n\n\tconst numStack = [[]];\n\tconst opStack = [];\n\n\tconst isNumber = char => !isNaN(char);\n\n\tfunction calculate(a, b, op){\n\t\tif(op === '+') return a + b;\n\t\tif(op === '-') return a - b;\n\t}\n\n\tlet number = '';\n\tfor (let i = 0; i < s.length; i++) {\n\t\tconst char = s[i];\n\n\t\tif (char === ' ') continue;\n\n\t\tif (isNumber(char)) {\n\t\t\tnumber += char;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(number) { // i.e. char is not a number so the number has ended\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(+number);\n\t\t\t} else {\n\t\t\t\tconst a = numStack[numStack.length - 1].pop();\n\t\t\t\tconst op = opStack.pop();\n\t\t\t\tnumStack[numStack.length - 1].push(calculate(a, +number, op));\n\t\t\t}\n\n\t\t\tnumber = '';\n\t\t}\n\n\t\tif (char === '(') {\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(0);\n\t\t\t\topStack.push('+');\n\t\t\t}\n\n\t\t\tnumStack.push([]); // Start a new stack for this parenthesis\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === ')') {\n\t\t\tconst b = numStack.pop().pop();\n\t\t\tconst a = numStack[numStack.length - 1].pop();\n\t\t\tconst op = opStack.pop();\n\t\t\tnumStack[numStack.length - 1].push(calculate(a, b, op));\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '+' || char === '-') {\n\t\t\tif (numStack[numStack.length - 1].length === 0) {\n\t\t\t\tnumStack[numStack.length - 1].push(0);\n\t\t\t}\n\n\t\t\topStack.push(char);\n\t\t\tcontinue;\n\t\t}\n\n\n\t\t// We should never reach here\n\t\tthrow new Error('Unexpected input: ' + char);\n\t}\n\n\tif(number){\n\t\tif (numStack[numStack.length - 1].length === 0) return +number;\n\n\t\tconst a = numStack[numStack.length - 1].pop();\n\t\tconst op = opStack.pop();\n\t\tnumStack[0].push(calculate(a, +number, op));\n\t}\n\n\treturn numStack.pop().pop();\n};", "solution_java": "class Solution {\n int idx; // this index traverse the string in one pass, between different level of recursion\n public int calculate(String s) {\n idx = 0; // Initialization should be here\n return helper(s);\n }\n \n private int helper(String s) {\n int res = 0, num = 0, preSign = 1, n = s.length();\n while (idx < n) {\n char c = s.charAt(idx++);\n if (c == '(') num = helper(s); // Let recursion solve the sub-problem\n else if (c >= '0' && c <= '9') num = num * 10 + c - '0';\n if (c == '+' || c == '-' || c == ')' || idx == n) { // we need one more calculation when idx == n\n res += preSign * num;\n if (c == ')') return res; // end of a sub-problem\n num = 0;\n preSign = c == '+' ? 1 : -1;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int calculate(string s) {\n stack> st; // pair(prev_calc_value , sign before next bracket () )\n \n long long int sum = 0;\n int sign = +1;\n \n for(int i = 0 ; i < s.size() ; ++i)\n {\n char ch = s[i];\n \n if(isdigit(ch))\n {\n long long int num = 0;\n while(i < s.size() and isdigit(s[i]))\n {\n num = (num * 10) + s[i] - '0';\n i++;\n }\n i--; // as for loop also increase i , so if we don't decrease i here a sign will be skipped\n sum += (num * sign);\n sign = +1; // reseting sign\n }\n else if(ch == '(')\n {\n // Saving current state of (sum , sign) in stack\n st.push(make_pair(sum , sign));\n \n // Reseting sum and sign for inner bracket calculation\n sum = 0; \n sign = +1;\n }\n else if(ch == ')')\n {\n sum = st.top().first + (st.top().second * sum);\n st.pop();\n }\n else if(ch == '-')\n {\n // toggle sign\n sign = (-1 * sign);\n }\n }\n return sum;\n }\n};" }, { "title": "Evaluate Division", "algo_input": "You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.\n\nYou are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.\n\nReturn the answers to all queries. If a single answer cannot be determined, return -1.0.\n\nNote: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.\n\n \nExample 1:\n\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput: [6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation: \nGiven: a / b = 2.0, b / c = 3.0\nqueries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?\nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\n\n\nExample 2:\n\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput: [3.75000,0.40000,5.00000,0.20000]\n\n\nExample 3:\n\nInput: equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput: [0.50000,2.00000,-1.00000,-1.00000]\n\n\n \nConstraints:\n\n\n\t1 <= equations.length <= 20\n\tequations[i].length == 2\n\t1 <= Ai.length, Bi.length <= 5\n\tvalues.length == equations.length\n\t0.0 < values[i] <= 20.0\n\t1 <= queries.length <= 20\n\tqueries[i].length == 2\n\t1 <= Cj.length, Dj.length <= 5\n\tAi, Bi, Cj, Dj consist of lower case English letters and digits.\n\n", "solution_py": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n graph = dict()\n \n for (n, d), v in zip(equations, values):\n if n not in graph:\n graph[n] = []\n if d not in graph:\n graph[d] = []\n \n graph[n].append((d, v))\n graph[d].append((n, 1/v))\n \n def dfs(node, target, product, visited):\n if n not in graph or d not in graph:\n return -1\n \n if node == target:\n return product\n \n visited.add(node)\n \n for neighbor, quotient in graph[node]:\n if neighbor not in visited:\n soln = dfs(neighbor, target, product * quotient, visited)\n if soln != -1:\n return soln\n \n return -1\n \n solns = []\n for n, d in queries:\n solns.append(dfs(n, d, 1, set()))\n \n return solns", "solution_js": "var calcEquation = function(equations, values, queries) {\n const res = []\n \n for(let i = 0; i < queries.length; i++) {\n const currQuery = queries[i]\n \n const [currStart, currDestination] = currQuery\n \n const adj = {}\n \n const additionalEdges = []\n const additionalValues = []\n \n const visited = new Set()\n \n equations.forEach((el,idx) => {\n const [to, from] = el\n const val = values[idx]\n \n additionalEdges.push([from, to])\n additionalValues.push(1/val)\n })\n \n values = [...values, ...additionalValues]\n let idx = 0\n for(const [from, to] of [...equations, ...additionalEdges]) {\n if(!(from in adj)) adj[from] = []\n \n adj[from].push([to, values[idx]])\n \n idx++\n }\n \n if(!(currStart in adj) || !(currDestination in adj)) {\n res.push(-1)\n continue\n }\n \n if(currStart === currDestination) {\n res.push(1)\n continue\n }\n \n \n let currEvaluation = 1\n let found = false\n const subResult = dfs(currStart)\n if(!found) res.push(-1)\n \n \n \n function dfs(node) {\n if(!node) return null\n if(node === currDestination) {\n return true\n }\n \n const children = adj[node] // [ [to, val] ]\n \n if(!children) return false\n \n for(const child of children) {\n if(visited.has(node)) continue\n visited.add(node)\n \n currEvaluation = currEvaluation*child[1]\n\n if(dfs(child[0]) === true) {\n !found && res.push(currEvaluation)\n found = true\n return \n }\n visited.delete(node)\n currEvaluation /= child[1]\n }\n }\n \n }\n return res\n};", "solution_java": "class Solution {\n public double[] calcEquation(List> equations, double[] values, List> queries) {\n int len = equations.size();\n Map varMap = new HashMap<>();\n int varCnt = 0;\n for (int i = 0; i < len; i++) {\n if (!varMap.containsKey(equations.get(i).get(0))) {\n varMap.put(equations.get(i).get(0), varCnt++);\n }\n if (!varMap.containsKey(equations.get(i).get(1))) {\n varMap.put(equations.get(i).get(1), varCnt++);\n }\n }\n\n List[] edges = new List[varCnt];\n for (int i = 0; i < varCnt; i++) {\n edges[i] = new ArrayList<>();\n }\n\n for (int i = 0; i < len; i++) {\n int va = varMap.get(equations.get(i).get(0));\n int vb = varMap.get(equations.get(i).get(1));\n edges[va].add(new Pair(vb, values[i]));\n edges[vb].add(new Pair(va, 1.0 / values[i]));\n }\n\n int queriesCnt = queries.size();\n double[] ans = new double[queriesCnt];\n for (int i = 0; i < queriesCnt; i++) {\n List query = queries.get(i);\n double result = -1.0;\n if (varMap.containsKey(query.get(0)) && varMap.containsKey(query.get(1))) {\n int idxA = varMap.get(query.get(0));\n int idxB = varMap.get(query.get(1));\n if (idxA == idxB) {\n result = 1.0;\n } else {\n Queue points = new LinkedList<>();\n points.offer(idxA);\n double[] ratios = new double[varCnt];\n Arrays.fill(ratios, -1.0);\n ratios[idxA] = 1.0;\n while (!points.isEmpty() && ratios[idxB] < 0) {\n int cur = points.poll();\n for (Pair pair : edges[cur]) {\n int y = pair.index;\n double value = pair.value;\n if (ratios[y] < 0) {\n ratios[y] = ratios[cur] * value;\n points.offer(y);\n }\n }\n }\n\n result = ratios[idxB];\n }\n }\n\n ans[i] = result;\n }\n\n return ans;\n }\n\n class Pair {\n int index;\n double value;\n\n public Pair(int index, double value) {\n this.index = index;\n this.value = value;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n vector calcEquation(vector>& equations, vector& values, vector>& queries) {\n map>> graph;\n\t\tmap dist;\n map visited;\n for(int i=0;i result;\n for(int i=0;i, vector>, greater>> pq;\n dist[queries[i][0]] = 1;;\n pq.push({1, queries[i][0]});\n bool flag=false;\n while(!pq.empty()){\n auto k = pq.top();\n pq.pop();\n visited[k.second] = true;\n if(k.second==queries[i][1]){\n flag=true;\n result.push_back(dist[k.second]);\n break;\n }\n for(int j=0;j int:\n ce, co = 0, 0\n s = 0\n for x in arr:\n if x % 2 == 0:\n ce += 1\n else:\n old_co = co\n co = ce + 1\n ce = old_co\n \n s += co\n \n return s % (10**9+7)", "solution_js": "var numOfSubarrays = function(arr) {\n let mod=1e9+7,sum=0,odds=0,evens=0\n\t//Notice that I do not need to keep track of the prefixSums, I just need the total count of odd and even PrefixSums\n for(let i=0;i &arr, int req, vector> &dp) {\n \n if(ind == n) return 0;\n if(dp[ind][req] != -1) return dp[ind][req];\n if(req == 1) {\n if(arr[ind] % 2 == 0) {\n return dp[ind][req] = solve(ind + 1, n, arr, req, dp);\n }\n else {\n return dp[ind][req] = (1 + solve(ind + 1, n, arr, !req, dp)) %mod;\n }\n }\n else {\n if(arr[ind] % 2 == 0) {\n return dp[ind][req] = (1 + solve(ind + 1, n, arr, req, dp)) %mod;\n }\n else {\n return dp[ind][req] = solve(ind + 1, n, arr, !req, dp);\n }\n }\n }\n int numOfSubarrays(vector& arr) {\n int n = arr.size();\n vector> dp(n, vector (2, -1));\n int count = 0;\n for(int i = 0; i < n; i++) {\n count = (count + solve(i, n, arr, 1, dp))% mod;\n }\n return count;\n }\n};" }, { "title": "Concatenation of Consecutive Binary Numbers", "algo_input": "Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 1\nExplanation: \"1\" in binary corresponds to the decimal value 1. \n\n\nExample 2:\n\nInput: n = 3\nOutput: 27\nExplanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.\n\n\nExample 3:\n\nInput: n = 12\nOutput: 505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\n", "solution_py": "class Solution:\n def concatenatedBinary(self, n: int) -> int:\n modulo = 10 ** 9 + 7\n shift = 0 # tracking power of 2\n res = 0\n \n for i in range(1, n+1):\n if i & (i - 1) == 0: # see if num reaches a greater power of 2\n shift += 1\n res = ((res << shift) + i) % modulo # do the simulation\n \n return res", "solution_js": "var concatenatedBinary = function(n) {\n let num = 0;\n \n for(let i = 1; i <= n; i++) {\n //OR num *= (1 << i.toString(2).length)\n num *= (2 ** i.toString(2).length) \n num += i;\n num %= (10 ** 9 + 7)\n }\n return num;\n};", "solution_java": "class Solution {\n public int concatenatedBinary(int n) {\n long res = 0;\n for (int i = 1; i <= n; i++) {\n res = (res * (int) Math.pow(2, Integer.toBinaryString(i).length()) + i) % 1000000007;\n }\n return (int) res;\n }\n}", "solution_c": "class Solution {\npublic:\n \n int numberOfBits(int n) {\n\t\t return log2(n) + 1;\n }\n \n int concatenatedBinary(int n) {\n long ans = 0, MOD = 1e9 + 7;\n \n for (int i = 1; i <= n; ++i) {\n int len = numberOfBits(i);\n ans = ((ans << len) % MOD + i) % MOD;\n }\n return ans;\n }\n};" }, { "title": "Valid Parentheses", "algo_input": "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n\nAn input string is valid if:\n\n\n\tOpen brackets must be closed by the same type of brackets.\n\tOpen brackets must be closed in the correct order.\n\n\n \nExample 1:\n\nInput: s = \"()\"\nOutput: true\n\n\nExample 2:\n\nInput: s = \"()[]{}\"\nOutput: true\n\n\nExample 3:\n\nInput: s = \"(]\"\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of parentheses only '()[]{}'.\n\n", "solution_py": "class Solution:\n def isValid(self, string: str) -> bool:\n while True:\n if '()' in string:\n string = string.replace('()', '')\n elif '{}' in string:\n string = string.replace('{}', '')\n elif '[]' in string:\n string = string.replace('[]', '')\n\n else:\n return not string", "solution_js": "var isValid = function(s) { \n const stack = [];\n \n for (let i = 0 ; i < s.length ; i++) {\n let c = s.charAt(i);\n switch(c) {\n case '(': stack.push(')');\n break;\n case '[': stack.push(']');\n break;\n case '{': stack.push('}');\n break;\n default:\n if (c !== stack.pop()) {\n return false;\n }\n }\n }\n \n return stack.length === 0;\n};", "solution_java": "class Solution {\n public boolean isValid(String s) {\n Stack stack = new Stack(); // create an empty stack\n for (char c : s.toCharArray()) { // loop through each character in the string\n if (c == '(') // if the character is an opening parenthesis\n stack.push(')'); // push the corresponding closing parenthesis onto the stack\n else if (c == '{') // if the character is an opening brace\n stack.push('}'); // push the corresponding closing brace onto the stack\n else if (c == '[') // if the character is an opening bracket\n stack.push(']'); // push the corresponding closing bracket onto the stack\n else if (stack.isEmpty() || stack.pop() != c) // if the character is a closing bracket\n // if the stack is empty (i.e., there is no matching opening bracket) or the top of the stack\n // does not match the closing bracket, the string is not valid, so return false\n return false;\n }\n // if the stack is empty, all opening brackets have been matched with their corresponding closing brackets,\n // so the string is valid, otherwise, there are unmatched opening brackets, so return false\n return stack.isEmpty();\n }\n}", "solution_c": "class Solution {\npublic:\n// Ref: balanced parenthesis video from LUV bhaiya YT channel \nunordered_mapsymbols={{'[',-1},{'{',-2},{'(',-3},{']',1},{'}',2},{')',3}};\n stackst;\n bool isValid(string s) {\n for(auto &i:s){\n if(symbols[i]<0){\n st.push(i);\n }\n else{\n if(st.empty()) return false;\n char top=st.top();\n st.pop();\n if(symbols[i]+symbols[top]!=0) return false;\n }\n }\n if(st.empty()) return true;\n return false;\n \n }\n};" }, { "title": "Top K Frequent Elements", "algo_input": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\n \nExample 1:\nInput: nums = [1,1,1,2,2,3], k = 2\nOutput: [1,2]\nExample 2:\nInput: nums = [1], k = 1\nOutput: [1]\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\tk is in the range [1, the number of unique elements in the array].\n\tIt is guaranteed that the answer is unique.\n\n\n \nFollow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.\n", "solution_py": "class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n return [i[0] for i in Counter(nums).most_common(k)]", "solution_js": "var topKFrequent = function(nums, k) {\n let store = {};\n for(let i=0;istore[a]-store[b])\n let arrLength = keyArr.length;\n let slicedArr = keyArr.slice(arrLength-k,arrLength)\n return slicedArr\n};", "solution_java": "class Solution {\n\tpublic int[] topKFrequent(int[] nums, int k) {\n\t\tMap map = new HashMap<>();\n\n\t\tfor (int num : nums) { \n\t\t\tmap.merge(num, 1, Integer::sum);\n\t\t}\n\n\t\treturn map.entrySet()\n\t\t\t.stream()\n\t\t\t.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n\t\t\t.map(Map.Entry::getKey)\n\t\t\t.mapToInt(x -> x)\n\t\t\t.limit(k)\n\t\t\t.toArray();\n\t}\n}", "solution_c": "class Solution {\npublic:\n vector topKFrequent(vector& nums, int k) {\n unordered_map map;\n for(int num : nums){\n map[num]++;\n }\n \n vector res;\n // pair: first is frequency, second is number\n priority_queue> pq; \n for(auto it = map.begin(); it != map.end(); it++){\n pq.push(make_pair(it->second, it->first));\n if(pq.size() > (int)map.size() - k){\n res.push_back(pq.top().second);\n pq.pop();\n }\n }\n return res;\n }\n};" }, { "title": "Number of Operations to Make Network Connected", "algo_input": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.\n\nYou are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.\n\nReturn the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.\n\n \nExample 1:\n\nInput: n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput: 1\nExplanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\n\n\nExample 2:\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput: 2\n\n\nExample 3:\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput: -1\nExplanation: There are not enough cables.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\t1 <= connections.length <= min(n * (n - 1) / 2, 105)\n\tconnections[i].length == 2\n\t0 <= ai, bi < n\n\tai != bi\n\tThere are no repeated connections.\n\tNo two computers are connected by more than one cable.\n\n", "solution_py": "class Solution(object):\n def __init__(self):\n self.parents = []\n self.count = []\n\n def makeConnected(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: int\n \"\"\"\n if len(connections) < n-1:\n return -1\n self.parents = [i for i in range(n)]\n self.count = [1 for _ in range(n)]\n for connection in connections:\n a, b = connection[0], connection[1]\n self.union(a, b)\n return len({self.find(i) for i in range(n)}) - 1\n\n def find(self, node):\n \"\"\"\n :type node: int\n :rtype: int\n \"\"\"\n while(node != self.parents[node]):\n node = self.parents[node];\n return node\n\n def union(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: None\n \"\"\"\n a_parent, b_parent = self.find(a), self.find(b)\n a_size, b_size = self.count[a_parent], self.count[b_parent]\n\n if a_parent != b_parent:\n if a_size < b_size:\n self.parents[a_parent] = b_parent\n self.count[b_parent] += a_size\n else:\n self.parents[b_parent] = a_parent\n self.count[a_parent] += b_size", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} connections\n * @return {number}\n */\nclass UnionFind {\n constructor(n) {\n this.root = new Array(n).fill().map((_, index)=>index);\n this.components = n;\n }\n find(x) {\n if(x == this.root[x]) return x;\n return this.root[x] = this.find(this.root[x]);\n }\n union(x, y) {\n const rootX = this.find(x);\n const rootY = this.find(y);\n if(rootX != rootY) {\n this.root[rootY] = rootX;\n this.components--;\n }\n }\n}\nvar makeConnected = function(n, connections) {\n // We need at least n - 1 cables to connect all nodes (like a tree).\n if(connections.length < n-1) return -1;\n const uf = new UnionFind(n);\n for(const [a, b] of connections) {\n uf.union(a, b);\n }\n return uf.components - 1;\n};", "solution_java": "class Solution {\n public int makeConnected(int n, int[][] connections) {\n int m = connections.length;\n if(m < n - 1) return -1;\n UnionFind uf = new UnionFind(n);\n \n for(int[] connection: connections){\n uf.union(connection[0], connection[1]);\n }\n return uf.getIsolated();\n }\n}\nclass UnionFind{\n int[] root;\n int[] rank;\n int isolated;\n public UnionFind(int n){\n root = new int[n];\n rank = new int[n];\n for(int i = 0; i < n; i++){\n root[i] = i;\n rank[i] = 1;\n }\n isolated = 0;\n }\n public int find(int x){\n if(root[x] != x) root[x] = find(root[x]);\n return root[x];\n }\n public void union(int x, int y){\n int rootx = find(x);\n int rooty = find(y);\n if(rootx == rooty) return;\n if(rank[rootx] > rank[rooty]){\n root[rooty] = rootx;\n }else if(rank[rootx] < rank[rooty]){\n root[rootx] = rooty;\n }else{\n root[rootx] = rooty;\n rank[rooty] += 1;\n }\n }\n public int getIsolated(){\n for(int i = 0; i < root.length; i ++){\n if(root[i] == i) isolated++;\n }\n return isolated - 1;\n }\n}", "solution_c": "class Solution {\npublic:\n\n\t// Union Find Approach\n\n\tvector root;\n\n\tint find(int node){\n\t\tif(root[node] != node){\n\t\t\treturn find(root[node]);\n\t\t}\n\t\treturn node;\n\t}\n\n\tint makeConnected(int n, vector>& connections) {\n\n\t\tint m = connections.size();\n\n\t\tif(m < n-1){\n\t\t\treturn -1;\n\t\t}\n\n\t\tfor(int i=0 ; i bool:\n if len(s) != len(t):\n return False\n\n cycles, extra = divmod(k, 26)\n shifts = [cycles + (shift <= extra) for shift in range(26)]\n\n for cs, ct in zip(s, t):\n shift = (ord(ct) - ord(cs)) % 26\n if shift == 0:\n continue\n if not shifts[shift]:\n return False\n shifts[shift] -= 1\n\n return True", "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @param {number} k\n * @return {boolean}\n */\n var canConvertString = function(s, t, k) {\n let res = true;\n if(s.length === t.length){\n let tmp = [];\n let countMap = new Map();\n for(let i=0; i 0){\n // Considering repeated letters, the unrepeated move should change to r + 26*n (n>=0)\n // use hash table to count the same letter\n if(!countMap.has(r)){\n // first time to move\n countMap.set(r, 1);\n tmp.push(r);\n }else{\n // n time to move, n means the count of the same letter\n let c = countMap.get(r);\n tmp.push(r + c * 26);\n // update count\n countMap.set(r, c+1);\n }\n }\n }\n // check all possible move in range\n for(let i=0; i k){\n res = false;\n break;\n }\n }\n }else{\n res = false;\n }\n\n return res;\n};", "solution_java": "class Solution {\n public boolean canConvertString(String s, String t, int k) {\n //if strings lengths not equal return false\n if(s.length()!=t.length())return false;\n //array to count number of times a difference can repeat\n int b[]=new int[26];\n int h=k/26;\n int h1=k%26;\n //count of each number from 1 to 26 from 1 to k\n for(int i=0;i<26;i++){\n b[i]+=h;\n if(i<=h1)b[i]++;\n }\n\n int i=0;\n while(i mp;\n for (int i = 0; i < m; i++) {\n if (t[i] == s[i]) continue;\n int diff = t[i] - s[i] < 0 ? 26 + t[i] - s[i] : t[i] - s[i];\n if (mp.find(diff) == mp.end()) {\n count = max(count, diff);\n } else {\n count = max(count, (mp[diff] * 26) + diff);\n }\n mp[diff]++;\n if (count > k) return false;\n }\n return count <= k;\n }\n \n}; " }, { "title": "Shifting Letters", "algo_input": "You are given a string s of lowercase English letters and an integer array shifts of the same length.\n\nCall the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').\n\n\n\tFor example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.\n\n\nNow for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.\n\nReturn the final string after all such shifts to s are applied.\n\n \nExample 1:\n\nInput: s = \"abc\", shifts = [3,5,9]\nOutput: \"rpl\"\nExplanation: We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.\n\n\nExample 2:\n\nInput: s = \"aaa\", shifts = [1,2,3]\nOutput: \"gfd\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of lowercase English letters.\n\tshifts.length == s.length\n\t0 <= shifts[i] <= 109\n\n", "solution_py": "class Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n n = len(s)\n nums = []\n sums = 0\n for i in shifts[::-1]:\n sums = (sums+i)%26\n nums.append(sums)\n nums = nums[::-1]\n \n res = ''\n for i, ch in enumerate(s):\n val = ord(s[i]) + nums[i]\n while val > 122:\n val -= 26\n res += chr(val)\n \n return res", "solution_js": "// 848. Shifting Letters\nvar shiftingLetters = function(s, shifts) {\n\tlet res = '', i = shifts.length;\n\tshifts.push(0);\n\twhile (--i >= 0) {\n\t\tshifts[i] += shifts[i+1];\n\t\tres = String.fromCharCode((s.charCodeAt(i) - 97 + shifts[i]) % 26 + 97) + res;\n\t}\n\treturn res;\n};", "solution_java": "class Solution {\n public String shiftingLetters(String s, int[] shifts) {\n char[] arr = s.toCharArray();\n int[] arr1 = new int[shifts.length];\n arr1[arr1.length-1] = (shifts[shifts.length-1])%26;\n for(int i =shifts.length -2 ;i>=0 ;i--){\n arr1[i] = (shifts[i] + arr1[i+1])%26;\n }\n for(int i =0; i122){\n int m = arr1[i] -(122-c);\n n = m+96;\n }\n char ch = (char)n;\n arr[i] = ch;\n\n }\n String string = new String(arr);\n return string;\n\n }\n}", "solution_c": "class Solution {\n void shift(string& s, int times, int amt)\n {\n const int clampL = 97;\n const int clampR = 123;\n \n for (int i = 0; i <= times; i++)\n {\n int op = (s[i] + amt) % clampR;\n \n if (op < clampL)\n op += clampL;\n \n s[i] = op;\n }\n }\npublic:\n string shiftingLetters(string s, vector& shifts) {\n \n for (int i = 0; i < shifts.size(); i++)\n shift(s,i,shifts[i]);\n \n return s;\n }\n};" }, { "title": "Range Frequency Queries", "algo_input": "Design a data structure to find the frequency of a given value in a given subarray.\n\nThe frequency of a value in a subarray is the number of occurrences of that value in the subarray.\n\nImplement the RangeFreqQuery class:\n\n\n\tRangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.\n\tint query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right].\n\n\nA subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).\n\n \nExample 1:\n\nInput\n[\"RangeFreqQuery\", \"query\", \"query\"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]\nOutput\n[null, 1, 2]\n\nExplanation\nRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t1 <= arr[i], value <= 104\n\t0 <= left <= right < arr.length\n\tAt most 105 calls will be made to query\n\n", "solution_py": "class RangeFreqQuery:\n def __init__(self, arr: List[int]):\n self.l = [[] for _ in range(10001)]\n for i, v in enumerate(arr):\n self.l[v].append(i)\n def query(self, left: int, right: int, v: int) -> int:\n return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)", "solution_js": " var RangeFreqQuery = function(arr) {\n\n this.array = arr;\n this.subRangeSize = Math.sqrt(this.array.length) >> 0;\n this.subRangeFreqs = [];\n\n let freq = {};\n\n for(let i = 0; i < arr.length; i++) {\n\n const num = arr[i];\n \n if(i >= this.subRangeSize && i % this.subRangeSize === 0) {\n this.subRangeFreqs.push({...freq});\n freq = {};\n }\n \n freq[num] = (freq[num] || 0) + 1; \n }\n\n this.subRangeFreqs.push(freq);\n\n};\n\nRangeFreqQuery.prototype.query = function(left, right, value) {\n\n let fr = 0;\n\n const leftIdx = left / this.subRangeSize >> 0, rightIdx = right / this.subRangeSize >> 0;\n\n for(let i = leftIdx; i <= rightIdx; i++) {\n fr += this.subRangeFreqs[i][value] || 0;\n }\n\n for(let i = leftIdx * this.subRangeSize; i < left; i++) {\n fr -= this.array[i] === value ? 1 : 0;\n }\n\n for(let i = right + 1; i < Math.min((rightIdx + 1) * this.subRangeSize, this.array.length); i++) {\n fr -= this.array[i] === value ? 1 : 0;\n }\n return fr;\n};", "solution_java": "class RangeFreqQuery {\n //Use map's key to store arr's value, map's value to keep \n HashMap> map;\n public RangeFreqQuery(int[] arr) {\n //O(nlog(n))\n map = new HashMap<>();\n for(int i = 0; i < arr.length; i++){\n map.putIfAbsent(arr[i], new TreeMap<>());\n TreeMap tree = map.get(arr[i]);\n //i = value's location\n //tree.size() = cummulative arr's value count - 1\n tree.put(i, tree.size());\n }\n }\n \n public int query(int left, int right, int value) {\n //O(log(n))\n \n //check if value exist in map\n if(!map.containsKey(value)){\n return 0;\n }\n TreeMap tree = map.get(value);\n \n //check if there exist position >= left and position <= right\n //if not, return 0\n if(tree.ceilingKey(left) == null || tree.floorKey(right) == null){\n return 0;\n }\n //get leftMost position's cummulative count\n int leftMost = tree.get(tree.ceilingKey(left));\n //get rightMost position's cummulative count\n int rightMost = tree.get(tree.floorKey(right));\n \n return rightMost - leftMost + 1;\n }\n}\n\n/**\n * Your RangeFreqQuery object will be instantiated and called as such:\n * RangeFreqQuery obj = new RangeFreqQuery(arr);\n * int param_1 = obj.query(left,right,value);\n */", "solution_c": "class RangeFreqQuery {\nprivate:\n int size;\n unordered_map< int, vector > mp;\npublic:\n RangeFreqQuery(vector& arr) {\n size=arr.size();\n for (int i=0; i int:\n def valid(r,c,matrix):\n return r >= 0 and c >= 0 and r < len(matrix) and c < len(matrix[0])\n\n dp = [[0] * len(obstacleGrid[0]) for _ in range(len(obstacleGrid))]\n dp[0][0] = 1 ^ obstacleGrid[0][0]\n\n for r in range(len(obstacleGrid)):\n for c in range(len(obstacleGrid[0])):\n if obstacleGrid[r][c] != 1:\n if valid(r-1, c, dp) and obstacleGrid[r-1][c] != 1:\n dp[r][c] += dp[r-1][c]\n if valid(r, c-1, dp) and obstacleGrid[r][c-1] != 1:\n dp[r][c] += dp[r][c-1]\n\n return dp[-1][-1]", "solution_js": "var uniquePathsWithObstacles = function(grid) {\n let m=grid.length, n=grid[0].length;\n const dp = [...Array(m+1)].map((e) => Array(n+1).fill(0));\n dp[0][1]=1;\n for(let i=1;i0)\n path[i][j] += path[i-1][j];\n if(j>0)\n path[i][j] += path[i][j-1];\n }\n }\n }\n return path[--m][--n];\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[101][101];\n int paths(int i,int j,int &m, int &n,vector> &grid){\n if(i>=m || j>=n) return 0;\n \n if(grid[i][j] == 1) return 0;\n \n if(i== m-1 && j== n-1) return 1;\n \n if(dp[i][j] != -1) return dp[i][j];\n \n int v = paths(i,j+1,m,n,grid);\n int h = paths(i+1,j,m,n,grid);\n \n return dp[i][j] = v + h;\n }\n int uniquePathsWithObstacles(vector>& obstacleGrid) {\n int m = obstacleGrid.size();\n int n = obstacleGrid[0].size();\n \n memset(dp,-1,sizeof(dp));\n \n return paths(0,0,m,n,obstacleGrid);\n }\n};" }, { "title": "Ransom Note", "algo_input": "Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.\n\nEach letter in magazine can only be used once in ransomNote.\n\n \nExample 1:\nInput: ransomNote = \"a\", magazine = \"b\"\nOutput: false\nExample 2:\nInput: ransomNote = \"aa\", magazine = \"ab\"\nOutput: false\nExample 3:\nInput: ransomNote = \"aa\", magazine = \"aab\"\nOutput: true\n\n \nConstraints:\n\n\n\t1 <= ransomNote.length, magazine.length <= 105\n\transomNote and magazine consist of lowercase English letters.\n\n", "solution_py": "from collections import Counter\nclass Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n \n ransomNote_count = dict(Counter(ransomNote))\n magazine_count = dict(Counter(magazine))\n \n for key , value in ransomNote_count.items():\n \n if key in magazine_count:\n if value <= magazine_count[key]:\n continue\n else:\n return False\n \n return False\n \n return True", "solution_js": "var canConstruct = function(ransomNote, magazine) {\n map = {};\n for(let i of magazine){\n map[i] = (map[i] || 0) + 1;\n }\n for(let i of ransomNote){\n if(!map[i]){\n return false\n }\n map[i]--;\n }\n return true\n};", "solution_java": "class Solution {\n public boolean canConstruct(String ransomNote, String magazine) {\n char[] rs = ransomNote.toCharArray();\n char[] ms = magazine.toCharArray();\n \n HashMap rm = new HashMap<>();\n HashMap mz = new HashMap<>();\n \n for (char c : rs) {\n if (rm.containsKey(c)) {\n rm.put(c, rm.get(c) + 1);\n } else {\n rm.put(c, 1);\n }\n }\n\n for (char c : ms) {\n if (mz.containsKey(c)) {\n mz.put(c, mz.get(c) + 1);\n } else {\n mz.put(c, 1);\n }\n }\n\n for (char c : rm.keySet()) {\n if (!mz.containsKey(c) || mz.get(c) < rm.get(c)) {\n return false;\n }\n }\n return true; \n }\n}", "solution_c": "class Solution {\npublic:\n bool canConstruct(string ransomNote, string magazine) {\n int cnt[26] = {0};\n for(char x: magazine)\n cnt[x-'a']++;\n \n for(char x: ransomNote) {\n if(cnt[x-'a'] == 0)\n return false;\n cnt[x-'a']--;\n }\n \n return true;\n }\n};" }, { "title": "Redistribute Characters to Make All Strings Equal", "algo_input": "You are given an array of strings words (0-indexed).\n\nIn one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].\n\nReturn true if you can make every string in words equal using any number of operations, and false otherwise.\n\n \nExample 1:\n\nInput: words = [\"abc\",\"aabc\",\"bc\"]\nOutput: true\nExplanation: Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so return true.\n\n\nExample 2:\n\nInput: words = [\"ab\",\"a\"]\nOutput: false\nExplanation: It is impossible to make all the strings equal using the operation.\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length <= 100\n\twords[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def makeEqual(self, words: List[str]) -> bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map_.items():\n if (v%n) != 0:\n return False\n return True", "solution_js": "/**\n * @param {string[]} words\n * @return {boolean}\n */\nvar makeEqual = function(words) {\n\n let length = words.length\n\n let map = {}\n for( let word of words ) {\n for( let ch of word ) {\n map[ch] = ( map[ch] || 0 ) + 1\n }\n }\n\n for( let key of Object.keys(map)) {\n if( map[key] % length !=0 ) return false\n }\n\n return true\n\n};", "solution_java": "class Solution {\n public boolean makeEqual(String[] words) {\n \n HashMap map = new HashMap<>();\n \n for(String str : words){\n \n for(int i=0; i& words) {\n int mp[26] = {0};\n for(auto &word: words){\n for(auto &c: word){\n mp[c - 'a']++;\n }\n }\n \n for(int i = 0;i<26;i++){\n if(mp[i] % words.size() != 0) return false;\n }\n return true; \n }\n};" }, { "title": "Lexicographically Smallest String After Applying Operations", "algo_input": "You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\n\nYou can apply either of the following two operations any number of times and in any order on s:\n\n\n\tAdd a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = \"3456\" and a = 5, s becomes \"3951\".\n\tRotate s to the right by b positions. For example, if s = \"3456\" and b = 1, s becomes \"6345\".\n\n\nReturn the lexicographically smallest string you can obtain by applying the above operations any number of times on s.\n\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9'.\n\n \nExample 1:\n\nInput: s = \"5525\", a = 9, b = 2\nOutput: \"2050\"\nExplanation: We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\n​​​​​​​Add: \"2050\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"2050\".\n\n\nExample 2:\n\nInput: s = \"74\", a = 5, b = 1\nOutput: \"24\"\nExplanation: We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\n​​​​​​​Add: \"42\"\n​​​​​​​Rotate: \"24\"​​​​​​​​​​​​\nThere is no way to obtain a string that is lexicographically smaller then \"24\".\n\n\nExample 3:\n\nInput: s = \"0011\", a = 4, b = 2\nOutput: \"0011\"\nExplanation: There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 100\n\ts.length is even.\n\ts consists of digits from 0 to 9 only.\n\t1 <= a <= 9\n\t1 <= b <= s.length - 1\n\n", "solution_py": "'''\nw: BFS\nh: for each possible number (node), we have two possible operations (add, rotate)\n it seems to be a 2^100 possible number, however, note:\n 1) add a to number of odd index, we will get to the same number after 10 rounds of add\n 2) s has even length, if b is odd, we can get the same number after n round\n 3) for each shift, we would get different number at even index in 10 rounds\n \n so we would have 10 * n * 10 number at most, then we can use BFS + memo\n'''\nimport collections\n\nclass Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n seen = set()\n deque = collections.deque([s])\n\n while deque:\n #print(deque)\n curr = deque.popleft()\n seen.add(curr)\n \n #1.add\n ad = self.add_(curr, a)\n if ad not in seen:\n deque.append(ad)\n seen.add(ad)\n\n \n #2. rotate:\n ro = self.rotate_(curr, b)\n if ro not in seen:\n deque.append(ro)\n seen.add(ro)\n\n return min(seen)\n \n \n def add_(self,s,a):\n res = ''\n for idx, i in enumerate(s):\n if idx % 2 == 1:\n num = (int(i) + a) % 10\n res += str(num)\n else:\n res += i\n \n return res\n \n \n def rotate_(self, s, b):\n idx = len(s)-b\n res = s[idx:] + s[0:idx]\n return res", "solution_js": "var findLexSmallestString = function(s, a, b) {\n const n = s.length;\n const visited = new Set();\n const queue = [];\n\n visited.add(s);\n queue.push(s);\n\n let minNum = s;\n\n while (queue.length > 0) {\n const currNum = queue.shift();\n\n if (currNum < minNum) minNum = currNum;\n\n const justRotate = rotate(currNum);\n const justAdd = add(currNum);\n\n if (!visited.has(justRotate)) {\n visited.add(justRotate);\n queue.push(justRotate);\n }\n\n if (!visited.has(justAdd)) {\n visited.add(justAdd);\n queue.push(justAdd);\n }\n }\n\n return minNum;\n\n function rotate(num) {\n let rotatedNum = \"\";\n const start = n - b;\n\n for (let i = 0; i < b; i++) {\n rotatedNum += num.charAt(start + i);\n }\n\n const restDigs = num.substring(0, n - b);\n rotatedNum += restDigs;\n\n return rotatedNum;\n }\n\n function add(num) {\n let nextNum = \"\";\n\n for (let i = 0; i < n; i++) {\n let currDig = num.charAt(i);\n\n if (i % 2 == 0) {\n nextNum += currDig;\n }\n else {\n let newDig = (parseInt(currDig) + a) % 10;\n nextNum += newDig;\n }\n }\n\n return nextNum;\n }\n};", "solution_java": "class Solution {\n private String result;\n public String findLexSmallestString(String s, int a, int b) {\n result = \"z\";\n HashSet set = new HashSet<>();\n dfs(s, a, b, set);\n return result;\n }\n private void dfs(String s, int a, int b, HashSet set) {\n if(set.contains(s))\n return;\n set.add(s);\n String s1, s2;\n s1 = addA(s, a);\n s2 = rotateB(s, b);\n dfs(s1, a , b, set);\n dfs(s2, a , b, set);\n }\n private String addA(String s, int a) {\n char c[] = s.toCharArray();\n int i, temp;\n for(i=1;i 0)\n result = s;\n return s;\n }\n private String rotateB(String s, int b) {\n if(b < 0)\n b += s.length();\n b = b % s.length();\n b = s.length() - b;\n s = s.substring(b) + s.substring(0, b);\n if(result.compareTo(s) > 0)\n result = s;\n return s;\n }\n}", "solution_c": "class Solution {\npublic:\n void dfs(string &s, string &small, int a, int b, unordered_map &memo) {\n if (memo.count(s)) return;\n string res = s, str = res;\n memo[s] = res;\n rotate(str.begin(), str.begin() + b, str.end()); // rotate current string\n dfs(str, small, a, b, memo);\n if (memo[str] < res) res = memo[str];\n \n for (int i = 0; i < 9; i++) { // or add it\n for (int j = 1; j < s.length(); j+=2)\n s[j] = '0' + ((s[j] - '0') + a) % 10;\n if (s < res) res = s;\n dfs(s, small, a, b, memo);\n }\n if (small > res) small = res;\n memo[s] = res;\n }\n string findLexSmallestString(string s, int a, int b) {\n unordered_map memo;\n string res = s;\n dfs(s, res, a, b, memo);\n return res;\n }\n};" }, { "title": "Next Greater Element I", "algo_input": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.\n\nYou are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.\n\nFor each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.\n\nReturn an array ans of length nums1.length such that ans[i] is the next greater element as described above.\n\n \nExample 1:\n\nInput: nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput: [-1,3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n\n\nExample 2:\n\nInput: nums1 = [2,4], nums2 = [1,2,3,4]\nOutput: [3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length <= nums2.length <= 1000\n\t0 <= nums1[i], nums2[i] <= 104\n\tAll integers in nums1 and nums2 are unique.\n\tAll the integers of nums1 also appear in nums2.\n\n\n \nFollow up: Could you find an O(nums1.length + nums2.length) solution?", "solution_py": "class Solution:\n def nextGreaterElement(self, nums1, nums2):\n dic, stack = {}, []\n \n for num in nums2[::-1]:\n while stack and num > stack[-1]:\n stack.pop()\n if stack:\n dic[num] = stack[-1]\n stack.append(num)\n \n return [dic.get(num, -1) for num in nums1]", "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number[]}\n */\nvar nextGreaterElement = function(nums1, nums2) {\n // [Value, Index] of all numbers in nums2\n const indexMap = new Map()\n for(let i = 0; i < nums2.length; i++){\n indexMap.set(nums2[i], i)\n }\n\n // Stores the next greatest elements\n let result = []\n\n // Iterate through all the numbers of interest. Remember that all numbers in nums1 are present in nums2.\n for(let num of nums1){\n\n // Check to see those numbers were present in the nums2 indexMap\n if(indexMap.has(num)){\n\n // If they were, we must find the next greatest element.\n // Set it to -1 by default in case we cannot find it.\n let nextGreatest = -1\n\n // Iterate through all numbers in nums2 to the right of the index of the target number. (index of the target + 1)\n for(let i = indexMap.get(num) + 1; i < nums2.length; i++){\n // Check to see if the current number is greater than the target.\n if(nums2[i] > num){\n // If it is, this is the next greatest element.\n nextGreatest = nums2[i]\n // Break the loop.\n break;\n }\n }\n // Add the next greatest element (if found). Otherwise, add -1 (default)\n result.push(nextGreatest)\n }\n }\n\n // Return the array of next greatest elements.\n return result\n};", "solution_java": "class Solution {\n public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n HashMap map = new HashMap<>();\n Stack stack = new Stack<>();\n int[] ans = new int[nums1.length];\n for(int i = 0; i < nums2.length; i++){\n while(!stack.isEmpty() && nums2[i] > stack.peek()){\n int temp = stack.pop();\n map.put(temp, nums2[i]);\n }\n stack.push(nums2[i]);\n }\n for(int i = 0; i < nums1.length; i++){\n ans[i] = map.getOrDefault(nums1[i], -1);\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector nextGreaterElement(vector& nums1, vector& nums2) {\n vectorvc;\n int len1=nums1.size();\n int len2=nums2.size();\n unordered_mapump;\n int e,f;\n for(e=0;enums2[e])\n {\n ump[nums2[e]]=nums2[f];\n break;\n }\n\n }\n if(f==len2) ump[nums2[e]]=-1;\n\n }\n unordered_map::iterator it;\n for(int e=0;esecond);\n }\n }\n\n return vc;\n\n }\n};" }, { "title": "All Elements in Two Binary Search Trees", "algo_input": "Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.\n\n \nExample 1:\n\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\n\n\nExample 2:\n\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in each tree is in the range [0, 5000].\n\t-105 <= Node.val <= 105\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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n \n \n l1,l2=[],[]\n def preorder(root,l):\n if root is None:\n return \n preorder(root.left,l)\n l.append(root.val)\n preorder(root.right,l)\n preorder(root1,l1)\n preorder(root2,l2)\n return sorted(l1+l2)", "solution_js": "var getAllElements = function(root1, root2) {\n const ans = [];\n const traverse = (r) => {\n if(!r) return;\n traverse(r.left);\n ans.push(r.val);\n traverse(r.right);\n }\n traverse(root1);\n traverse(root2);\n return ans.sort((a, b) => a - b);\n};", "solution_java": "class Solution {\n public List getAllElements(TreeNode root1, TreeNode root2) {\n Stack st1 = new Stack<>();\n Stack st2 = new Stack<>();\n \n List res = new ArrayList<>();\n \n while(root1 != null || root2 != null || !st1.empty() || !st2.empty()){\n while(root1 != null){\n st1.push(root1);\n root1 = root1.left;\n }\n while(root2 != null){\n st2.push(root2);\n root2 = root2.left;\n }\n if(st2.empty() || (!st1.empty() && st1.peek().val <= st2.peek().val)){\n root1 = st1.pop();\n res.add(root1.val);\n root1 = root1.right;\n }\n else{\n root2 = st2.pop();\n res.add(root2.val);\n root2 = root2.right;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector v;\n void Temp(TreeNode* root)\n {\n if(root!=NULL){\n Temp(root->left);\n v.push_back(root->val);\n Temp(root->right);\n }\n }\n vector getAllElements(TreeNode* root1, TreeNode* root2) {\n Temp(root1);\n Temp(root2);\n sort(v.begin(), v.end());\n\n return v;\n }\n};" }, { "title": "Zigzag Conversion", "algo_input": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\n\nP A H N\nA P L S I I G\nY I R\n\n\nAnd then read line by line: \"PAHNAPLSIIGYIR\"\n\nWrite the code that will take a string and make this conversion given a number of rows:\n\nstring convert(string s, int numRows);\n\n\n \nExample 1:\n\nInput: s = \"PAYPALISHIRING\", numRows = 3\nOutput: \"PAHNAPLSIIGYIR\"\n\n\nExample 2:\n\nInput: s = \"PAYPALISHIRING\", numRows = 4\nOutput: \"PINALSIGYAHRPI\"\nExplanation:\nP I N\nA L S I G\nY A H R\nP I\n\n\nExample 3:\n\nInput: s = \"A\", numRows = 1\nOutput: \"A\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts consists of English letters (lower-case and upper-case), ',' and '.'.\n\t1 <= numRows <= 1000\n\n", "solution_py": "class Solution:\n def convert(self, s: str, numRows: int) -> str:\n\n # safety check to not process single row\n if numRows == 1:\n return s\n\n # safety check to not process strings shorter/equal than numRows\n if len(s) <= numRows:\n return s\n\n # safety check to not process double rows\n if numRows == 2:\n # slice every other character\n return s[0::2] + s[1::2]\n\n # list that stores the lines\n # add lines with initial letters\n lines: list[str] = [letter for letter in s[:numRows]]\n\n # positive direction goes down\n # lines are created, so it's going up\n direction: int = -1\n\n # track the position at which the letter will be added\n # position after bouncing off, after adding initial lines\n line_index: int = numRows - 2\n\n # edge indexes\n # 0 can only be reached by going up\n # numRows only by going down\n edges: set[int] = {0, numRows}\n\n for letter in s[numRows:]:\n # add letter at tracked index position\n lines[line_index] += letter\n\n # prepare index before next loop iteration\n line_index += direction\n\n # reaching one of the edges\n if line_index in edges:\n # change direction\n direction = -direction\n # bounce off if bottom edge\n if line_index == numRows:\n line_index += direction * 2\n\n return \"\".join(lines)", "solution_js": "var convert = function(s, numRows) {\n let result = [];\n let row = 0;\n let goingUp = false;\n for (let i = 0; i < s.length; i++) {\n result[row] = (result[row] || '') + s[i]; // append letter to active row\n if (goingUp) {\n row--;\n if (row === 0) goingUp = false; // reverse direction if goingUp and reaching top\n } else {\n row++;\n if (row === numRows - 1) goingUp = true; // reverse direction after reaching bottom\n }\n\n }\n return result.join('');\n};", "solution_java": "class Solution {\n public String convert(String s, int numRows) {\n if (numRows==1)return s;\n StringBuilder builder = new StringBuilder();\n for (int i=1;i<=numRows;i++){\n int ind = i-1;\n boolean up = true;\n while (ind < s.length()){\n builder.append(s.charAt(ind));\n if (i==1){\n ind += 2*(numRows-i);\n } else if (i==numRows){\n ind += 2*(i-1);\n } else {\n ind += up ? 2*(numRows-i) : 2*(i-1);\n up=!up;\n }\n }\n }\n return builder.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string convert(string s, int numRows) {\n vector> v(numRows);\n int j=0,t=1;\n if(numRows ==1)\n return s;\n for(int i=0;i int:\n\n # When goal 0 we can just choose no elements \n if goal == 0: return 0\n\n n = len(nums)\n mid = n // 2\n # Split the list in 2 parts and then find all possible subset sums \n # T = O(2^n/2) to build all subset sums\n leftList = nums[:mid]\n leftSums = []\n rightList = nums[mid:]\n rightSums = []\n\n # T = O(2^n/2) to build all subset sums (we only consider half list)\n def buildSubsetSums(usedNums, numsToChooseFrom, ind, storeIn):\n if ind == len(numsToChooseFrom):\n # We also keep elements with sum 0 to deal with cases like this where we don't select nums\n # List: [1,2,3], Target: -7 (choosing no elements will give a sum close to goal)\n # We can also have cases where we want to take only 1 element from the list\n # so sum 0 for left and right list needs to be an option\n storeIn.append(sum(usedNums))\n return \n\n usedNums.append(numsToChooseFrom[ind])\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n usedNums.pop()\n buildSubsetSums(usedNums, numsToChooseFrom, ind+1, storeIn)\n\n\n buildSubsetSums([], leftList, 0, leftSums)\n buildSubsetSums([], rightList, 0, rightSums)\n # 2^n/2 log(2^n/2) = n/2 * 2^n/2 time to sort\n rightSums.sort()\n\n diff = float('inf')\n\n # Loop runs 2^n/2 times and inside binary search tale n/2 time \n # So total time is n/2 * 2^n/2\n for leftSum in leftSums:\n complement = goal - leftSum\n # Bisect left takes log(2^n/2) = n/2 search time\n idx = bisect.bisect_left(rightSums, complement)\n\n for i in [idx - 1, idx, idx + 1]:\n if 0 <= i < len(rightSums):\n finalSum = leftSum + rightSums[i]\n diff = min(diff, abs(goal - finalSum))\n \n # Over all time complexity is - n/2 * 2^n/2\n # 1. Making subset sums will take - 2^n/2\n # 2. Sorting right list takes - 2^n/2 * n/2\n # 3. Iterating one list and finding closest complement in other \n # takes n/2 * 2^n/2\n # Space will be O(n/2) for the list and call stack for building subset \n return diff", "solution_js": "var minAbsDifference = function(nums, goal) {\n let mid = Math.floor(nums.length / 2);\n let part1 = nums.slice(0, mid), part2 = nums.slice(mid);\n\n function findSubsetSums(arr, set, idx = 0, sum = 0) {\n if (idx === arr.length) return set.add(sum);\n findSubsetSums(arr, set, idx + 1, sum);\n findSubsetSums(arr, set, idx + 1, sum + arr[idx]);\n }\n\n let sum1 = new Set(), sum2 = new Set();\n findSubsetSums(part1, sum1);\n findSubsetSums(part2, sum2);\n\n sum1 = [...sum1.values()];\n sum2 = [...sum2.values()];\n sum2.sort((a, b) => a - b);\n\n let min = Infinity;\n for (let num1 of sum1) {\n let l = 0, r = sum2.length - 1;\n while (l <= r) {\n let mid = l + Math.floor((r - l) / 2);\n let num2 = sum2[mid];\n min = Math.min(min, Math.abs(num1 + num2 - goal));\n if (num1 + num2 < goal) l = mid + 1;\n else r = mid - 1;\n }\n }\n return min;\n};", "solution_java": "class Solution {\n int[] arr;\n public int minAbsDifference(int[] nums, int goal) {\n arr = nums;\n int n = nums.length;\n \n \n List first = new ArrayList<>();\n List second = new ArrayList<>();\n \n generate(0,n/2,0, first); //generate all possible subset sums from half the array\n generate(n/2, n , 0, second);//generate all possible subset sums from the second half of the array\n \n \n Collections.sort(first);\n int ans = Integer.MAX_VALUE;\n \n \n for(int secondSetSum : second ) {\n int left = goal - secondSetSum; // How far off are we from the desired goal?\n \n if(first.get(0) > left) { // all subset sums from first half are too big => Choose the smallest\n ans = (int)(Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal)));\n continue;\n }\n if(first.get(first.size() - 1) < left) { // all subset sums from first half are too small => Choose the largest\n ans = (int)(Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal)));\n continue;\n }\n int pos = Collections.binarySearch(first, left);\n if(pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal\n return 0;\n else // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1)\n pos = -1 * (pos + 1);\n int low = pos - 1;\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(low) - goal)); // Checking for the floor value (largest sum < goal)\n ans = (int)Math.min(ans, Math.abs(secondSetSum + first.get(pos) - goal)); //Checking for the ceiling value (smallest sum > goal)\n }\n return ans;\n }\n\n /**\n * Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick \n */\n void generate(int i, int end, int sum, List listOfSubsetSums) {\n if (i == end) {\n listOfSubsetSums.add(sum); //add\n return;\n }\n generate(i + 1, end, sum + arr[i], set);\n generate(i + 1, end, sum, set);\n \n }\n \n \n \n}", "solution_c": "class Solution {\npublic:\n void find(vector&v, int i, int e, int sum, vector&sumv){\n if(i==e){\n sumv.push_back(sum);\n return;\n }\n find(v,i+1,e,sum+v[i],sumv);\n find(v,i+1,e,sum,sumv);\n }\n\n int minAbsDifference(vector& nums, int goal) {\n int n=nums.size();\n\n //Step 1: Divide nums into 2 subarrays of size n/2 and n-n/2\n\n vectorA,B;\n for(int i=0;isumA,sumB;\n find(A,0,A.size(),0,sumA);\n find(B,0,B.size(),0,sumB);\n\n sort(sumA.begin(),sumA.end());\n sort(sumB.begin(),sumB.end());\n\n //Step 3: Find combinations from sumA & sumB such that abs(sum-goal) is minimized\n\n int ans=INT_MAX;\n\n for(int i=0;igoal){\n r=mid-1;\n }\n else{\n l=mid+1;\n }\n }\n }\n\n return ans;\n }\n};" }, { "title": "Find Words That Can Be Formed by Characters", "algo_input": "You are given an array of strings words and a string chars.\n\nA string is good if it can be formed by characters from chars (each character can only be used once).\n\nReturn the sum of lengths of all good strings in words.\n\n \nExample 1:\n\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n\n\nExample 2:\n\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 1000\n\t1 <= words[i].length, chars.length <= 100\n\twords[i] and chars consist of lowercase English letters.\n\n", "solution_py": "class Solution(object):\n def countCharacters(self, words, chars):\n \"\"\"\n :type words: List[str]\n :type chars: str\n :rtype: int\n \"\"\"\n b = set(chars)\n anwser = 0\n for i in words:\n a = set(i)\n if a.issubset(b):\n test = [o for o in a if chars.count(o) < i.count(o)]\n if len(test) == 0: \n anwser += len(i)\n return anwser", "solution_js": "var countCharacters = function(words, chars) {\n let arr = [];\n loop1: for(word of words){\n let characters = chars;\n loop2: for( char of word ){\n if(characters.indexOf(char) === -1){\n continue loop1;\n }\n characters = characters.replace(char,'');\n }\n arr.push(word);\n }\n return arr.join('').length;\n};", "solution_java": "class Solution {\n public int countCharacters(String[] words, String chars) {\n int[] freq = new int[26];\n for (int i = 0; i < chars.length(); i++) {\n // char - char is a kind of clever way to get the position of\n // the character in the alphabet. 'a' - 'a' would give you 0.\n // 'b' - 'a' would give you 1. 'c' - 'a' would give you 2, and so on.\n freq[chars.charAt(i) - 'a'] ++;\n }\n\n int result = 0;\n for (String word : words) {\n int[] copy = Arrays.copyOf(freq, freq.length);\n boolean pass = true;\n for (int j = 0; j < word.length(); j++) {\n // decrement the frequency of this char in array for using\n // if there are less than 1 chance for using this character, invalid,\n // move to next word in words\n if (-- copy[word.charAt(j) - 'a'] < 0) {\n pass = false;\n break;\n }\n }\n if (pass) {\n result += word.length();\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n int countCharacters(vector& words, string chars) {\n vector dp(26,0);\n vector dp2(26,0);\n for(int i=0;i0){\n dp[a[j]-'a']--;\n }\n else{\n flg = true;\n dp = dp2;\n break;\n }\n }\n if(!flg){\n cnt += a.size();\n }\n dp = dp2;\n flg = false;\n }\n return cnt;\n }\n};" }, { "title": "Subarray Sum Equals K", "algo_input": "Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n \nExample 1:\nInput: nums = [1,1,1], k = 2\nOutput: 2\nExample 2:\nInput: nums = [1,2,3], k = 3\nOutput: 2\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t-1000 <= nums[i] <= 1000\n\t-107 <= k <= 107\n\n", "solution_py": "class Solution:\n\tdef subarraySum(self, nums: List[int], k: int) -> int:\n\n\t\tans=0\n\t\tprefsum=0\n\t\td={0:1}\n\n\t\tfor num in nums:\n\t\t\tprefsum = prefsum + num\n\n\t\t\tif prefsum-k in d:\n\t\t\t\tans = ans + d[prefsum-k]\n\n\t\t\tif prefsum not in d:\n\t\t\t\td[prefsum] = 1\n\t\t\telse:\n\t\t\t\td[prefsum] = d[prefsum]+1\n\n\t\treturn ans", "solution_js": " var subarraySum = function(nums, k) {\n const obj = {};\n let res = 0;\n let sum = 0;\n\n for (let i = 0; i < nums.length; i++) {\n\n sum += nums[i];\n if (sum == k) res++;\n\n if (obj[sum - k]) res += obj[sum - k];\n\n obj[sum] ? obj[sum] += 1 : obj[sum] = 1;\n }\n return res;\n };", "solution_java": "/*\n*/\nclass Solution {\n public int subarraySum(int[] nums, int k) {\n\n HashMap map = new HashMap<>();\n map.put(0,1);\n int count = 0;\n int sum = 0;\n\n for(int i=0; i& nums, int k) {\n \n unordered_map prefixSum {{0, 1}};\n \n int sum = 0;\n int numOfSubArr = 0;\n int size = nums.size();\n \n \n for (int index = 0; index < size; index++){\n \n sum += nums[index];\n if (prefixSum.find(sum-k) != prefixSum.end()) \n numOfSubArr += prefixSum[sum-k];\n \n prefixSum[sum]++;\n }\n \n return numOfSubArr;\n }\n};" }, { "title": "Smallest Range Covering Elements from K Lists", "algo_input": "You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.\n\nWe define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.\n\n \nExample 1:\n\nInput: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput: [20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].\n\n\nExample 2:\n\nInput: nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput: [1,1]\n\n\n \nConstraints:\n\n\n\tnums.length == k\n\t1 <= k <= 3500\n\t1 <= nums[i].length <= 50\n\t-105 <= nums[i][j] <= 105\n\tnums[i] is sorted in non-decreasing order.\n\n", "solution_py": "from queue import PriorityQueue\nclass Solution:\n\tdef smallestRange(self, nums: List[List[int]]) -> List[int]:\n\t\tq = PriorityQueue()\n\t\tmaxi = -10**7\n\t\tmini = 10**7\n\t\tfor i in range(len(nums)):\n\t\t\tmaxi = max(maxi,nums[i][0]) \n\t\t\tmini = min(mini,nums[i][0])\n\t\t\tq.put((nums[i][0],i,0)) \n\n\t\ts, e = mini, maxi\n\t\twhile not q.empty() :\n\t\t\tmini, i, j = q.get()\n\t\t\tif maxi - mini < e-s:\n\t\t\t\ts,e = mini, maxi\n\t\t\tif j+1 < len(nums[i]):\n\t\t\t\tmaxi = max(maxi,nums[i][j+1])\n\t\t\t\tq.put((nums[i][j+1],i,j+1))\n\t\t\telse: break\n\t\treturn [s,e]", "solution_js": "var smallestRange = function(nums) {\n let minHeap = new MinPriorityQueue({\n compare: (a,b) => a[0] - b[0]\n });\n let start = 0, end = Infinity;\n let maxSoFar = -Infinity;\n\t\n for (let num of nums) {\n minHeap.enqueue([num[0], 0, num]);\n maxSoFar = Math.max(maxSoFar, num[0]);\n }\n\t\n while (minHeap.size() == nums.length) {\n let [num, i, list] = minHeap.dequeue();\n \n if (end - start > maxSoFar - num) {\n start = num;\n end = maxSoFar;\n }\n \n if (list.length > i + 1) {\n minHeap.enqueue([list[i + 1], i + 1, list]);\n maxSoFar = Math.max(maxSoFar, list[i + 1]);\n }\n }\n \n return [start, end];\n};", "solution_java": "class Solution {\n \n class Pair implements Comparable {\n int val;\n int li;\n int di;\n \n public Pair(int val, int li, int di) {\n this.val = val;\n this.li = li;\n this.di = di;\n }\n \n public int compareTo(Pair other) {\n return this.val - other.val;\n }\n }\n \n public int[] smallestRange(List> nums) {\n PriorityQueue pq = new PriorityQueue<>();\n int max = Integer.MIN_VALUE;\n for(int i=0; i\n#include \n#include \n\nusing namespace std;\n\nstruct Item {\n int val;\n int r;\n int c;\n \n Item(int val, int r, int c): val(val), r(r), c(c) {\n }\n};\n\nstruct Comp {\n bool operator() (const Item& it1, const Item& it2) {\n return it2.val < it1.val;\n }\n};\n\nclass Solution {\npublic:\n vector smallestRange(vector>& nums) {\n priority_queue, Comp> pq;\n \n int high = numeric_limits::min();\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n pq.push(Item(nums[i][0], i, 0));\n high = max(high , nums[i][0]);\n }\n int low = pq.top().val;\n \n vector res{low, high};\n \n while (pq.size() == (size_t)n) {\n auto it = pq.top();\n pq.pop();\n \n if ((size_t)it.c + 1 < nums[it.r].size()) {\n pq.push(Item(nums[it.r][it.c + 1], it.r, it.c + 1));\n high = max(high, nums[it.r][it.c + 1]);\n low = pq.top().val;\n if (high - low < res[1] - res[0]) {\n res[0] = low;\n res[1] = high;\n }\n }\n }\n \n return res;\n }\n};" }, { "title": "Number of Substrings With Only 1s", "algo_input": "Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: s = \"0110111\"\nOutput: 9\nExplanation: There are 9 substring in total with only 1's characters.\n\"1\" -> 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.\n\nExample 2:\n\nInput: s = \"101\"\nOutput: 2\nExplanation: Substring \"1\" is shown 2 times in s.\n\n\nExample 3:\n\nInput: s = \"111111\"\nOutput: 21\nExplanation: Each substring contains only 1's characters.\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(object):\n def numSub(self, s):\n res, currsum = 0,0\n for digit in s:\n if digit == '0':\n currsum = 0\n else:\n currsum += 1 \n res+=currsum \n return res % (10**9+7)", "solution_js": "var numSub = function(s) {\n const mod = Math.pow(10, 9)+7;\n let r = 0, tot = 0;\n \n while (r str:\n s=list(s)\n vow=[]\n for i,val in enumerate(s):\n if val in ('a','e','i','o','u','A','E','I','O','U'):\n vow.append(val)\n s[i]='_'\n \n vow=vow[::-1]\n c=0\n print(vow)\n for i,val in enumerate(s):\n if val =='_':\n s[i]=vow[c]\n c+=1\n return \"\".join(s)", "solution_js": "var reverseVowels = function(s) {\n const VOWELS = { 'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1, 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1 };\n const arr = s.split('');\n let i = 0, j = arr.length - 1;\n while (i < j) {\n if (VOWELS[arr[i]] && VOWELS[arr[j]]) {\n [arr[i], arr[j]] = [arr[j], arr[i]];\n i++;\n j--;\n } else if (VOWELS[arr[i]]) {\n j--;\n } else {\n i++;\n }\n }\n return arr.join('');\n};", "solution_java": "class Solution {\n public String reverseVowels(String s) {\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n \n StringBuilder str = new StringBuilder(s);\n int left = 0, right = str.length() - 1;\n while (left < right) {\n if (!set.contains(str.charAt(left))) {\n left++;\n }\n if (!set.contains(str.charAt(right))) {\n right--;\n }\n if (set.contains(str.charAt(left)) && set.contains(s.charAt(right))) {\n char temp = str.charAt(left);\n str.setCharAt(left++, str.charAt(right));\n str.setCharAt(right--, temp);\n }\n }\n return str.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n \n bool isVowel(char s)\n {\n if(s == 'a' or s == 'e' or s == 'i' or s == 'o' or s == 'u'\n or s == 'A' or s == 'E' or s == 'I' or s == 'O' or s == 'U') return true;\n return false;\n }\n \n string reverseVowels(string s) {\n if(s.size() == 0) return \"\";\n int left = 0, right = s.size() - 1;\n \n while(left < right)\n {\n if(isVowel(s[left]) and isVowel(s[right]))\n {\n swap(s[left], s[right]);\n left++;\n right--;\n }\n else if(isVowel(s[left])) right--;\n else if(isVowel(s[right])) left++;\n else {\n left++;\n right--;\n }\n }\n \n \n return s;\n }\n};" }, { "title": "Palindrome Partitioning II", "algo_input": "Given a string s, partition s such that every substring of the partition is a palindrome.\n\nReturn the minimum cuts needed for a palindrome partitioning of s.\n\n \nExample 1:\n\nInput: s = \"aab\"\nOutput: 1\nExplanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n\n\nExample 2:\n\nInput: s = \"a\"\nOutput: 0\n\n\nExample 3:\n\nInput: s = \"ab\"\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 2000\n\ts consists of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def isPallindrom(self, s: str, l, r) -> bool:\n st = s[l: r+1]\n rev = st[::-1]\n return st == rev\n \n def minCut(self, s: str) -> int:\n N = len(s)\n if not s: return 0\n if self.isPallindrom(s, 0, N-1): return 0\n dp = [sys.maxsize] * (N+1)\n dp[-1] = 0\n \n for i in range(N-1, -1, -1):\n for j in range(i, N):\n if self.isPallindrom(s, i, j):\n dp[i] = min(dp[i], 1 + dp[j+1])\n \n return dp[0]-1", "solution_js": "var minCut = function(s) {\n function isPal(l, r) {\n while (l < r) {\n if (s[l] === s[r]) l++, r--;\n else return false;\n } return true;\n }\n\n let map = new Map();\n function dfs(idx = 0) {\n if (idx === s.length) return 0;\n if (map.has(idx)) return map.get(idx);\n let min = Infinity;\n for (let i = idx; i < s.length; i++) {\n if (isPal(idx, i)) min = Math.min(min, 1 + dfs(i + 1));\n }\n map.set(idx, min);\n return min;\n }\n\n return dfs() - 1;\n};", "solution_java": "class Solution {\nint dp[];\n\n public boolean pali(int i,int j,String s){\n \n // int j=s.length()-1,i=0;\n \n while(i<=j){\n \n if(s.charAt(i)!=s.charAt(j))return false;\n \n i++;j--;\n \n }\n \n return true;\n \n}\npublic int cut(String s,int i,int n,int dp[]){\n \n if(i==n)return 0;\n if(dp[i]!=-1)return dp[i];\n \n int min=Integer.MAX_VALUE;\n \n for(int j=i;j> isPalindrome(string& s){\n int n = s.size();\n vector> dp(n, vector(n, false));\n \n for(int i=0; i>& palin, vector& memo){\n if(i==n){\n return 0;\n }\n if(memo[i] != -1){\n return memo[i];\n }\n \n int result = INT_MAX;\n \n for(int j=i+1; j<=n; j++){\n if(palin[i][j-1]){\n result = min(result, 1+solve(s, n, j, palin, memo));\n }\n }\n \n return memo[i] = result;\n }\n \n int minCut(string s) {\n int n = s.size();\n vector memo(n, -1);\n vector> palin = isPalindrome(s);\n return solve(s, n, 0, palin, memo)-1;\n }\n};" }, { "title": "Number of Different Integers in a String", "algo_input": "You are given a string word that consists of digits and lowercase English letters.\n\nYou will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123  34 8  34\". Notice that you are left with some integers that are separated by at least one space: \"123\", \"34\", \"8\", and \"34\".\n\nReturn the number of different integers after performing the replacement operations on word.\n\nTwo integers are considered different if their decimal representations without any leading zeros are different.\n\n \nExample 1:\n\nInput: word = \"a123bc34d8ef34\"\nOutput: 3\nExplanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.\n\n\nExample 2:\n\nInput: word = \"leet1234code234\"\nOutput: 2\n\n\nExample 3:\n\nInput: word = \"a1b01c001\"\nOutput: 1\nExplanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.\n\n\n \nConstraints:\n\n\n\t1 <= word.length <= 1000\n\tword consists of digits and lowercase English letters.\n\n", "solution_py": "class Solution:\n def numDifferentIntegers(self, word: str) -> int:\n\n word = re.findall('(\\d+)', word)\n numbers = [int(i) for i in word]\n\n return len(set(numbers))", "solution_js": "const CC0 = '0'.charCodeAt(0);\n\nvar numDifferentIntegers = function(word) {\n const numStrSet = new Set();\n \n // get numbers as strings\n const numStrs = word.split(/[^0-9]+/);\n \n // drop leading zeros\n for (const numStr of numStrs) {\n if (numStr.length > 0) {\n let i = 0;\n while (numStr.charCodeAt(i) === CC0) i++;\n \n // make sure that we preserve last 0 if string is composed of zeros only\n numStrSet.add(numStr.slice(i) || '0');\n }\n }\n \n return numStrSet.size;\n};", "solution_java": "class Solution {\n public int numDifferentIntegers(String word) {\n String[] arr = word.replaceAll(\"[a-zA-Z]\", \" \").split(\"\\\\s+\");\n Set set = new HashSet();\n\n for (String str : arr) {\n if (!str.isEmpty())\n set.add(String.valueOf(str.replaceAll(\"^0*\",\"\")));\n }\n\n return set.size();\n }\n}", "solution_c": "class Solution {\npublic:\n int numDifferentIntegers(string word) {\n unordered_map hmap;\n for (int i = 0; i < word.size(); i++) {\n if (isdigit(word[i])) {\n string str;\n while (word[i] == '0')\n i++;\n while (isdigit(word[i]))\n str += word[i++];\n hmap[str]++;\n }\n }\n return hmap.size();\n }\n};" }, { "title": "Design HashMap", "algo_input": "Design a HashMap without using any built-in hash table libraries.\n\nImplement the MyHashMap class:\n\n\n\tMyHashMap() initializes the object with an empty map.\n\tvoid put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.\n\tint get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.\n\tvoid remove(key) removes the key and its corresponding value if the map contains the mapping for the key.\n\n\n \nExample 1:\n\nInput\n[\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\nOutput\n[null, null, null, 1, -1, null, 1, null, -1]\n\nExplanation\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]\n\n\n \nConstraints:\n\n\n\t0 <= key, value <= 106\n\tAt most 104 calls will be made to put, get, and remove.\n\n", "solution_py": "class MyHashMap:\n def __init__(self):\n self.data = [None] * 1000001\n def put(self, key: int, val: int) -> None:\n self.data[key] = val\n def get(self, key: int) -> int:\n val = self.data[key]\n return val if val != None else -1\n def remove(self, key: int) -> None:\n self.data[key] = None", "solution_js": "var MyHashMap = function() {\n this.hashMap = [];\n};\n\n/**\n * @param {number} key\n * @param {number} value\n * @return {void}\n */\nMyHashMap.prototype.put = function(key, value) {\n this.hashMap[key] = [key, value];\n};\n\n/**\n * @param {number} key\n * @return {number}\n */\nMyHashMap.prototype.get = function(key) {\n return this.hashMap[key] ? this.hashMap[key][1] : -1;\n};\n\n/**\n * @param {number} key\n * @return {void}\n */\nMyHashMap.prototype.remove = function(key) {\n delete this.hashMap[key];\n};\n\n/**\n * Your MyHashMap object will be instantiated and called as such:\n * var obj = new MyHashMap()\n * obj.put(key,value)\n * var param_2 = obj.get(key)\n * obj.remove(key)\n */", "solution_java": "class MyHashMap {\n\n\t/** Initialize your data structure here. */\n\tLinkedList[] map;\n\tpublic static int SIZE = 769;\n\tpublic MyHashMap() {\n\t\tmap = new LinkedList[SIZE];\n\t}\n\n\t/** value will always be non-negative. */\n\tpublic void put(int key, int value) {\n\t\tint bucket = key % SIZE;\n\t\tif(map[bucket] == null) {\n\t\t\tmap[bucket] = new LinkedList();\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key){\n\t\t\t\t\tentry.val = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmap[bucket].add(new Entry(key, value));\n\t\t}\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tpublic int get(int key) {\n\t\tint bucket = key % SIZE;\n\t\tLinkedList entries = map[bucket];\n\t\tif(entries == null) return -1;\n\t\tfor(Entry entry : entries) {\n\t\t\tif(entry.key == key) return entry.val;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tpublic void remove(int key) {\n\t\tint bucket = key % SIZE;\n\t\tEntry toRemove = null;\n\t\tif(map[bucket] == null) return;\n\t\telse {\n\t\t\tfor(Entry entry : map[bucket]){\n\t\t\t\tif(entry.key == key) {\n\t\t\t\t\ttoRemove = entry;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(toRemove == null) return;\n\t\t\tmap[bucket].remove(toRemove);\n\t\t}\n\t}\n}\n\nclass Entry {\n\tpublic int key;\n\tpublic int val;\n\n\tpublic Entry(int key, int val){\n\t\tthis.key = key;\n\t\tthis.val = val;\n\t}\n}", "solution_c": "class MyHashMap {\n\tvector>> map;\n\tconst int size = 10000;\npublic:\n\t/** Initialize your data structure here. */\n\tMyHashMap() {\n\t\tmap.resize(size);\n\t}\n\n\t/** value will always be non-negative. */\n\tvoid put(int key, int value) {\n\t\tint index = key % size;\n vector> &row = map[index];\n for(auto iter = row.begin(); iter != row.end(); iter++)\n {\n if(iter->first == key)\n {\n iter->second = value;\n return;\n }\n }\n\t\trow.push_back(make_pair(key, value));\n\t}\n\n\t/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */\n\tint get(int key) {\n\t\tint index = key % size;\n vector> &row = map[index];\n\t\tfor (auto iter = row.begin(); iter != row.end(); iter++)\n\t\t{\n\t\t\tif (iter->first == key)\n\t\t\t{\n\t\t\t\treturn iter->second;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\t/** Removes the mapping of the specified value key if this map contains a mapping for the key */\n\tvoid remove(int key) {\n\t\tint index = key % size;\n vector> &row = map[index];\n\t\tfor (auto iter = row.begin(); iter != row.end(); iter++)\n\t\t{\n\t\t\tif (iter->first == key)\n\t\t\t{\n\t\t\t\trow.erase(iter);\n return;\n\t\t\t}\n\t\t}\n\t}\n};\n\n/**\n * Your MyHashMap object will be instantiated and called as such:\n * MyHashMap* obj = new MyHashMap();\n * obj->put(key,value);\n * int param_2 = obj->get(key);\n * obj->remove(key);\n */" }, { "title": "Sum of All Odd Length Subarrays", "algo_input": "Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\n\nA subarray is a contiguous subsequence of the array.\n\n \nExample 1:\n\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\n\nExample 2:\n\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\n\nExample 3:\n\nInput: arr = [10,11,12]\nOutput: 66\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 100\n\t1 <= arr[i] <= 1000\n\n\n \nFollow up:\n\nCould you solve this problem in O(n) time complexity?\n", "solution_py": "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n n = len(arr)\n ans = 0\n for i in range(n):\n total = (i+1) * (n-1-i+1)\n ans = ans + (total//2 + total%2) * arr[i]\n return ans", "solution_js": "/*\nSuppose N is the length of given array.\nNumber of subarrays including element arr[i] is\ni * (N-i) + (N-i) because there are N-i subarrays with arr[i] as first element\nand i * (N-i) subarrays with arr[i] as a not-first element. arr[i] appears in \n(N-i) subarrays for each preceding element and therefore we have i*(N-i).\n\nSuppose i * (N-i) + (N-i) is `total`. Ceil(total / 2) is the number of odd-length subarrays and Floor(total / 2) is the number of even-length subarrays. \nWhen total is odd, there is one more odd-length subarray because of a single-element subarray.\n \nFor each number, we multiply its value with the total number of subarrays it appears and\nadd it to a sum.\n*/\nvar sumOddLengthSubarrays = function(arr) {\n let sum = 0, N = arr.length;\n for (let i = 0; i < arr.length; i++) {\n let total = i * (N-i) + (N-i);\n sum += Math.ceil(total / 2) * arr[i];\n }\n return sum;\n // T.C: O(N)\n // S.C: O(1)\n};", "solution_java": "class Solution {\n public int sumOddLengthSubarrays(int[] arr) {\n \n // Using two loops in this question...\n int sum = 0;\n for(int i=0 ; i& arr) {\n int sum=0;\n int sum1=0;\n for(int i=0;i str:\n knowledge = dict(knowledge)\n answer, start = [], None\n for i, char in enumerate(s):\n if char == '(': \n start = i + 1\n elif char == ')':\n answer.append(knowledge.get(s[start:i], '?'))\n start = None\n elif start is None: \n answer.append(char)\n return ''.join(answer)", "solution_js": "var evaluate = function(s, knowledge) {\n // key => value hash map can be directly constructed using the Map constructor\n const map = new Map(knowledge);\n \n\t// since bracket pairs can't be nested we can use a RegExp to capture keys and replace using a map constructed in the line above\n\treturn s.replace(/\\(([a-z]+)\\)/g, (_, p1) => map.get(p1) ?? \"?\");\n};", "solution_java": "class Solution {\n public String evaluate(String s, List> knowledge) {\n Map map = new HashMap<>();\n for(List ele : knowledge) {\n map.put(ele.get(0), ele.get(1));\n }\n StringBuilder sb = new StringBuilder();\n int b_start = -1;\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) == '(') {\n b_start = i;\n } else if(s.charAt(i) == ')') {\n String key = s.substring(b_start + 1, i);\n sb.append(map.getOrDefault(key, \"?\"));\n b_start = -1;\n } else {\n if(b_start == -1) {\n sb.append(s.charAt(i));\n }\n }\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string evaluate(string s, vector>& knowledge) {\n string ans; // resultant string\n int n = s.size();\n if(n < 2) return s; // because () will come in pair so, size should be more than 2\n int sz = knowledge.size();\n for(int i=0; i int:\n batteries.sort()\n total=sum(batteries)\n while batteries[-1]>total//n:\n n-=1\n total-=batteries.pop()\n return total//n", "solution_js": "var maxRunTime = function(n, batteries) {\n let total = batteries.reduce((acc,x)=>acc+x,0)\n let batts = batteries.sort((a,b)=>b-a)\n let i = 0\n while(1){\n let average_truncated = parseInt(total / n)\n let cur = batts[i]\n if(cur > average_truncated){\n total -= cur // remove all of that batteries charge from the equation\n n -- // remove the computer from the equation\n i++\n } else {\n return average_truncated\n }\n }\n};", "solution_java": "class Solution {\n\n private boolean canFit(int n, long k, int[] batteries) {\n long currBatSum = 0;\n long target = n * k;\n\n for (int bat : batteries) {\n if (bat < k) {\n currBatSum += bat;\n } else {\n currBatSum += k;\n }\n\n if (currBatSum >= target) {\n return true;\n }\n }\n\n return currBatSum >= target;\n\n }\n\n public long maxRunTime(int n, int[] batteries) {\n long batSum = 0;\n for (int bat : batteries) {\n batSum += bat;\n }\n \n long lower = 0;\n long upper = batSum / n;\n long res = -1;\n\n\t\t// binary search\n while (lower <= upper) {\n long mid = lower + (upper - lower) / 2;\n\n if (canFit(n, mid, batteries)) {\n res = mid;\n lower = mid + 1;\n } else {\n upper = mid - 1;\n }\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\nbool canFit(int n,long timeSpan,vectorbatteries)\n{\n long currBatSum=0;\n\tlong targetBatSum=n*timeSpan; \n for(auto it:batteries)\n {\n if(it=targetBatSum)\n return true; \n }\n \n return false;\n }\n\nlong long maxRunTime(int n, vector& batteries) {\n long totalSum=0;\n long low=*min_element(batteries.begin(),batteries.end());\n \n for(auto it:batteries)\n {\n totalSum+=it; \n }\n \n long high = totalSum/n;\n long ans=-1;\n \n while(low<=high)\n {\n \n long mid = low+(high-low)/2; \n if(canFit(n,mid,batteries))\n {\n ans=mid;\n low=mid+1;\n }\n else\n {\n high=mid-1;\n }\n \n } \n return ans; \n}" }, { "title": "Beautiful Arrangement", "algo_input": "Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:\n\n\n\tperm[i] is divisible by i.\n\ti is divisible by perm[i].\n\n\nGiven an integer n, return the number of the beautiful arrangements that you can construct.\n\n \nExample 1:\n\nInput: n = 2\nOutput: 2\nExplanation: \nThe first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 15\n\n", "solution_py": "class Solution:\n def countArrangement(self, n: int) -> int:\n self.count = 0\n self.backtrack(n, 1, [])\n return self.count\n \n def backtrack(self, N, idx, temp):\n if len(temp) == N:\n self.count += 1\n return\n \n for i in range(1, N+1):\n if i not in temp and (i % idx == 0 or idx % i == 0):\n temp.append(i)\n self.backtrack(N, idx+1, temp)\n temp.pop()", "solution_js": "var countArrangement = function(n) {\n let result = 0;\n const visited = Array(n + 1).fill(false);\n const dfs = (next = n) => {\n if (next === 0) {\n result += 1;\n return;\n }\n\n for (let index = 1; index <= n; index++) {\n if (visited[index] || index % next && next % index) continue;\n visited[index] = true;\n dfs(next - 1);\n visited[index] = false;\n }\n };\n\n dfs();\n return result;\n};", "solution_java": "class Solution {\n int N;\n Integer[][] memo;\n public int countArrangement(int n) {\n this.N = n;\n memo = new Integer[n+1][1< &v) {\n int i = v.size() - 1;\n if (v[i] % (i + 1) == 0 || (i + 1) % v[i] == 0) return true;\n return false;\n }\n\n void solve(int n, vector &p, vector &seen) {\n if (p.size() == n) {\n ans++;\n return;\n }\n for (int i = 1; i <= n; i++) {\n\n if (seen[i]) continue;\n p.push_back(i);\n\n if (isBeautiful(p)) {\n seen[i] = true;\n solve(n, p, seen);\n seen[i] = false;\n }\n p.pop_back();\n }\n }\n int countArrangement(int n) {\n\n vector p;\n vector seen(n + 1, false);\n solve(n, p, seen);\n\n return ans;\n }\n};" }, { "title": "24 Game", "algo_input": "You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.\n\nYou are restricted with the following rules:\n\n\n\tThe division operator '/' represents real division, not integer division.\n\n\t\n\t\tFor example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.\n\t\n\t\n\tEvery operation done is between two numbers. In particular, we cannot use '-' as a unary operator.\n\t\n\t\tFor example, if cards = [1, 1, 1, 1], the expression \"-1 - 1 - 1 - 1\" is not allowed.\n\t\n\t\n\tYou cannot concatenate numbers together\n\t\n\t\tFor example, if cards = [1, 2, 1, 2], the expression \"12 + 12\" is not valid.\n\t\n\t\n\n\nReturn true if you can get such expression that evaluates to 24, and false otherwise.\n\n \nExample 1:\n\nInput: cards = [4,1,8,7]\nOutput: true\nExplanation: (8-4) * (7-1) = 24\n\n\nExample 2:\n\nInput: cards = [1,2,1,2]\nOutput: false\n\n\n \nConstraints:\n\n\n\tcards.length == 4\n\t1 <= cards[i] <= 9\n\n", "solution_py": "class Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n return self.allComputeWays(cards, 4, 24)\n \n def allComputeWays(self, nums, l, target):\n if l == 1:\n if abs(nums[0] - target) <= 1e-6:\n return True\n return False\n for first in range(l):\n for second in range(first + 1, l):\n tmp1, tmp2 = nums[first], nums[second]\n nums[second] = nums[l - 1]\n \n nums[first] = tmp1 + tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 - tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp2 - tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first] = tmp1 * tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp2:\n nums[first] = tmp1 / tmp2\n if self.allComputeWays(nums, l - 1, target):\n return True\n if tmp1:\n nums[first] = tmp2 / tmp1\n if self.allComputeWays(nums, l - 1, target):\n return True\n nums[first], nums[second] = tmp1, tmp2\n return False", "solution_js": "/**\n * @param {number[]} cards\n * @return {boolean}\n1487\n7-1 8-4\n */\nvar judgePoint24 = function(cards) {\n let minV = 0.00000001;\n let numL = [];\n cards.forEach(card=>numL.push(card));\n function judge(nums){\n if(nums.length === 1) return Math.abs(nums[0]-24)<=minV;\n else{\n for(let i = 0 ;i EPS) {\n A[i] = a / b;\n if(backtrack(A, n - 1)) return true;\n }\n if(Math.abs(a) > EPS) {\n A[i] = b / a;\n if(backtrack(A, n - 1)) return true;\n }\n A[i] = a; A[j] = b;\n }\n }\n return false;\n }\n public boolean judgePoint24(int[] nums) {\n double[] A = new double[nums.length];\n for(int i = 0; i < nums.length; i++) A[i] = nums[i];\n return backtrack(A, A.length);\n }\n}", "solution_c": "class Solution {\npublic:\n double cor=0.001;\n void dfs(vector &cards,bool &res){\n if(res==true) return;\n if(cards.size()==1){\n if(abs(cards[0]-24) t{p+q,q-p,p-q,p*q};\n if(p>cor) t.push_back(q/p);\n if(q>cor) t.push_back(p/q);\n cards.erase(cards.begin()+i);\n cards.erase(cards.begin()+j);\n for(double d:t){\n cards.push_back(d);\n dfs(cards,res);\n cards.pop_back();\n }\n cards.insert(cards.begin()+j,q);\n cards.insert(cards.begin()+i,p);\n }\n }\n }\n bool judgePoint24(vector& cards) {\n bool res=false;\n vector card (cards.begin(),cards.end());\n dfs(card,res);\n return res;\n }\n};" }, { "title": "Largest Magic Square", "algo_input": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.\n\nGiven an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.\n\n \nExample 1:\n\nInput: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput: 3\nExplanation: The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12\n\n\nExample 2:\n\nInput: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput: 2\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 50\n\t1 <= grid[i][j] <= 106\n\n", "solution_py": "class Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n for j in range(n): \n rows[i][j+1] = grid[i][j] + rows[i][j]\n cols[i+1][j] = grid[i][j] + cols[i][j]\n \n ans = 1\n for i in range(m): \n for j in range(n): \n diag = grid[i][j]\n for k in range(min(i, j)): \n ii, jj = i-k-1, j-k-1\n diag += grid[ii][jj]\n ss = {diag}\n for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])\n for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])\n ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal\n if len(ss) == 1: ans = max(ans, k+2)\n return ans ", "solution_js": "var largestMagicSquare = function(grid) {\n const row = grid.length;\n const col = grid[0].length;\n const startSize = row <= col ? row : col;\n for(let s = startSize; s > 1; s--){\n for(let r = 0; r < grid.length - s + 1; r++){\n for(let c = 0; c < grid[0].length - s + 1; c++){\n if(isMagic(grid, r, c, s)){\n return s;\n }\n }\n }\n }\n return 1;\n};\n\nconst isMagic = (grid, i, j, size) => {\n let targetSum = 0;\n for(let c = j; c < j + size; c++){\n targetSum += grid[i][c];\n }\n //check rows\n for(let r = i; r < i + size; r++){\n let sum = 0;\n for(let c = j; c < j + size; c++){\n sum += grid[r][c];\n }\n if(targetSum !== sum){\n return false;\n }\n }\n //check cols\n for(let c = j; c < j + size; c++){\n let sum = 0;\n for(let r = i; r < i + size; r++){\n sum += grid[r][c];\n }\n if(targetSum !== sum){\n return false;\n }\n }\n //check diagonals\n let diagSum = 0, antiDiagSum = 0;\n for(let c = 0; c < size; c++){\n diagSum += grid[i + c][j+c];\n antiDiagSum += grid[i + c][j + size - 1 - c];\n }\n if(diagSum !== antiDiagSum || diagSum !== targetSum){\n return false\n }\n return true;\n}", "solution_java": "class Solution {\n public int largestMagicSquare(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n // every row prefix sum\n int[][] rowPrefix = new int[m][n];\n for (int i = 0; i < m; i++) {\n rowPrefix[i][0] = grid[i][0];\n for (int j = 1; j < n; j++) {\n rowPrefix[i][j] = rowPrefix[i][j - 1] + grid[i][j];\n }\n }\n\n // every column prefix sum\n int[][] columnPrefix = new int[m][n];\n for (int i = 0; i < n; i++) {\n columnPrefix[0][i] = grid[0][i];\n for (int j = 1; j < m; j++) {\n columnPrefix[j][i] = columnPrefix[j - 1][i] + grid[j][i];\n }\n }\n\n int result = 1;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n // length of square\n int l = Math.min(m - i, n - j);\n // only check square's length is better than previous result\n for (int k = l; k > result; k--) {\n if (magic(i, j, k, grid, rowPrefix, columnPrefix)) {\n result = k;\n break;\n }\n }\n }\n }\n return result;\n }\n\n private boolean magic(\n int i, int j, int l, int[][] grid, int[][] rowPrefix, int[][] columnPrefix) {\n // check every row\n int target = rowPrefix[i][j + l - 1] - rowPrefix[i][j] + grid[i][j];\n for (int k = 0; k < l; k++) {\n if (rowPrefix[i + k][j + l - 1] - rowPrefix[i + k][j] + grid[i + k][j] != target) {\n return false;\n }\n }\n\n // check every column\n for (int k = 0; k < l; k++) {\n if (columnPrefix[i + l - 1][j + k] - columnPrefix[i][j + k] + grid[i][j + k] != target) {\n return false;\n }\n }\n\n // check both diagonal\n int diagonal = 0;\n // \\\n // \\\n for (int k = 0; k < l; k++) {\n diagonal += grid[i + k][j + k];\n }\n\n if (diagonal != target) {\n return false;\n }\n\n // /\n // /\n for (int k = 0; k < l; k++) {\n diagonal -= grid[i + l - 1 - k][j + k];\n }\n\n return diagonal == 0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isValid(int r1, int r2, int c1, int c2, vector>& grid, vector>& rg, vector>& cg,int checkSum){\n //Checking all row sums between top and bottom row\n for(int i = r1 + 1; i0)sum-=rg[i][c1-1];\n if(sum!=checkSum)return false;\n }\n //Checking all columns between left and right column \n for(int j = c1 + 1; j0)sum-=cg[r1-1][j];\n if(sum!=checkSum)return false;\n }\n int sum = 0;\n //right diagonal\n for(int i = r1, j = c1; i<=r2&&j<=c2; i++, j++){\n sum+=grid[i][j];\n }\n if(sum!=checkSum)return false;\n sum = 0;\n //left diagonal\n for(int i = r1, j = c2; i<=r2&&j>=c1; i++, j--){\n sum+=grid[i][j];\n }\n if(sum!=checkSum)return false;\n return true;\n }\n int largestMagicSquare(vector>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector>rg, cg;\n rg = grid;\n cg = grid;\n //Generating row prefix sum matrix\n for(int i = 0; i= this dimension, we can simply return our answer\n //Pruning step -->\n //We only need to consider squares whose sizes our greater than our current answer, so we prune our search by starting from squares having side-lengths greater than ans.\n int r = i + ans;\n int c = j + ans;\n while(r0 ? rg[i][c] - rg[i][j-1] : rg[i][c];//top row sum\n int csum1 = i>0 ? cg[r][j] - cg[i-1][j] : cg[r][j];//left column sum\n int rsum2 = j>0 ? rg[r][c] - rg[r][j-1] : rg[r][c];//bottom row sum\n int csum2 = i>0 ? cg[r][c] - cg[i-1][c] : cg[r][c];//right column sum\n if(rsum1==csum2&&rsum2==csum2&&isValid(i,r,j,c,grid, rg, cg, rsum1)){\n ans = max(ans, r-i+1);\n }\n r++;\n c++;\n }\n }\n }\n return ans;\n }\n};" }, { "title": "Longest Substring Without Repeating Characters", "algo_input": "Given a string s, find the length of the longest substring without repeating characters.\n\n \nExample 1:\n\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\n\n\nExample 2:\n\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\n\n\nExample 3:\n\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\n\n \nConstraints:\n\n\n\t0 <= s.length <= 5 * 104\n\ts consists of English letters, digits, symbols and spaces.\n\n", "solution_py": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \n longest_s = ''\n curr_s = ''\n for i in s:\n if i not in curr_s:\n curr_s += i\n if len(curr_s) >= len(longest_s):\n longest_s = curr_s\n else:\n curr_s = curr_s[curr_s.index(i)+1:]+i\n \n return len(longest_s)", "solution_js": "var lengthOfLongestSubstring = function(s) {\n // keeps track of the most recent index of each letter.\n const seen = new Map();\n // keeps track of the starting index of the current substring.\n let start = 0;\n // keeps track of the maximum substring length.\n let maxLen = 0;\n\n for(let i = 0; i < s.length; i++) {\n // if the current char was seen, move the start to (1 + the last index of this char)\n // max prevents moving backward, 'start' can only move forward\n if(seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start)\n seen.set(s[i], i);\n // maximum of the current substring length and maxLen\n maxLen = Math.max(i - start + 1, maxLen);\n }\n\n return maxLen;\n};", "solution_java": "class Solution {\n public int lengthOfLongestSubstring(String s) {\n Map hash = new HashMap<>();\n int count = 0;\n int ans = 0;\n for(int i=0; i < s.length(); i++){\n if(hash.containsKey(s.charAt(i))){\n i = hash.get(s.charAt(i)) + 1;\n hash.clear();\n count = 0;\n }\n if(!hash.containsKey(s.charAt(i))){\n hash.put(s.charAt(i), i);\n count++;\n ans = Math.max(ans, count);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n map mp;\n int ans = 1;\n for(auto ch : s) {\n if(mp.find(ch) != mp.end()) {\n while(mp.find(ch) != mp.end()) mp.erase(mp.begin());\n }\n mp.insert({ch, 1});\n if(mp.size() > ans) ans = mp.size();\n }\n return ans;\n }\n};" }, { "title": "Patching Array", "algo_input": "Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.\n\nReturn the minimum number of patches required.\n\n \nExample 1:\n\nInput: nums = [1,3], n = 6\nOutput: 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\n\n\nExample 2:\n\nInput: nums = [1,5,10], n = 20\nOutput: 2\nExplanation: The two patches can be [2, 4].\n\n\nExample 3:\n\nInput: nums = [1,2,2], n = 5\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 104\n\tnums is sorted in ascending order.\n\t1 <= n <= 231 - 1\n\n", "solution_py": "class Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n\t#pre-process for convenience\n nums.append(n+1)\n t=1\n sum=1\n rs=0\n if nums[0]!=1:\n nums=[1]+nums\n rs+=1\n# the idea is sum from index 0 to index i should cover 1 to that sum*2 then we go form left to right to cover upto n\n while sum= nums.length && sumCanCreate+1 < n)) {\n patchCount++;\n // because we \"patch\" the next number in the sequence.\n sumCanCreate += (sumCanCreate+1);\n // if we can create nums[index].\n } else {\n // we can create anything from current sumCanCreate to (sumCanCreate + nums[index]).\n sumCanCreate += nums[index];\n index++;\n }\n }\n return patchCount;\n};", "solution_java": "class Solution {\n public int minPatches(int[] nums, int n) {\n long sum = 0;\n int count = 0;\n for (int x : nums) {\n if (sum >= n) break;\n while (sum+1 < x && sum < n) { \n ++count;\n sum += sum+1;\n }\n sum += x;\n }\n while (sum < n) {\n sum += sum+1;\n ++count;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int minPatches(vector& nums, int n) {\n nums.push_back(0);\n sort(nums.begin(), nums.end());\n long sum = 0;\n int ans = 0;\n for(int i = 1; i < nums.size(); i++){\n while((long)nums[i] > (long)(sum + 1)){\n ans++;\n sum += (long)(sum + 1);\n if(sum >= (long)n)\n return ans;\n }\n sum += nums[i];\n if(sum >= (long)n)\n return ans;\n }\n while(sum < (long)n){\n ans++;\n sum += (long)(sum + 1);\n }\n return ans;\n }\n};" }, { "title": "Simple Bank System", "algo_input": "You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i].\n\nExecute all the valid transactions. A transaction is valid if:\n\n\n\tThe given account number(s) are between 1 and n, and\n\tThe amount of money withdrawn or transferred from is less than or equal to the balance of the account.\n\n\nImplement the Bank class:\n\n\n\tBank(long[] balance) Initializes the object with the 0-indexed integer array balance.\n\tboolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise.\n\tboolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise.\n\tboolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.\n\n\n \nExample 1:\n\nInput\n[\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]\nOutput\n[null, true, true, true, false, false]\n\nExplanation\nBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.\n\n\n \nConstraints:\n\n\n\tn == balance.length\n\t1 <= n, account, account1, account2 <= 105\n\t0 <= balance[i], money <= 1012\n\tAt most 104 calls will be made to each function transfer, deposit, withdraw.\n\n", "solution_py": "class Bank:\n\n def __init__(self, bal: List[int]):\n self.store = bal # storage list\n\n def transfer(self, a1: int, a2: int, money: int) -> bool:\n try:\n # checking if both accounts exist. and if the transaction would be valid\n if self.store[a1 - 1] >= money and self.store[a2 - 1] >= 0:\n # performing the transaction\n self.store[a1 - 1] -= money\n self.store[a2 - 1] += money\n return True\n else:\n # retrning false on invalid transaction\n return False\n except:\n # returning false when accounts don't exist\n return False\n\n def deposit(self, ac: int, mn: int) -> bool:\n try:\n # if account exists performing transaction\n self.store[ac - 1] += mn\n return True\n except:\n # returning false when account doesn't exist\n return False\n\n def withdraw(self, ac: int, mn: int) -> bool:\n try:\n # checking if transaction is valid\n if self.store[ac - 1] >= mn:\n # performing the transaction\n self.store[ac - 1] -= mn\n return True\n else:\n # returning false in case on invalid transaction\n return False\n except:\n # returning false when account doesn't exist\n return False", "solution_js": "/**\n * @param {number[]} balance\n */\nvar Bank = function(balance) {\n this.arr = balance; \n};\n\n/** \n * @param {number} account1 \n * @param {number} account2 \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.transfer = function(account1, account2, money) {\n if (this.arr[account1-1] >= money && this.arr.length >= account1 && this.arr.length >= account2) {\n this.arr[account1-1] -= money;\n this.arr[account2-1] += money;\n return true;\n }\n return false;\n};\n\n/** \n * @param {number} account \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.deposit = function(account, money) {\n if (this.arr.length >= account) {\n this.arr[account-1] += money;\n return true;\n }\n return false;\n};\n\n/** \n * @param {number} account \n * @param {number} money\n * @return {boolean}\n */\nBank.prototype.withdraw = function(account, money) {\n if (this.arr.length >= account && this.arr[account-1] >= money) {\n this.arr[account-1] -= money\n return true;\n }\n return false;\n};\n\n/** \n * Your Bank object will be instantiated and called as such:\n * var obj = new Bank(balance)\n * var param_1 = obj.transfer(account1,account2,money)\n * var param_2 = obj.deposit(account,money)\n * var param_3 = obj.withdraw(account,money)\n */", "solution_java": "class Bank {\n\n int N;\n long[] balance;\n public Bank(long[] balance) {\n this.N = balance.length;\n this.balance = balance;\n }\n\n public boolean transfer(int account1, int account2, long money) {\n if(account1 < 1 || account1 > N || account2 < 1 || account2 > N || balance[account1 - 1] < money)\n return false;\n balance[account1 - 1] -= money;\n balance[account2 - 1] += money;\n return true;\n }\n\n public boolean deposit(int account, long money) {\n if(account < 1 || account > N)\n return false;\n balance[account - 1] += money;\n return true;\n }\n\n public boolean withdraw(int account, long money) {\n if(account < 1 || account > N || balance[account - 1] < money)\n return false;\n balance[account - 1] -= money;\n return true;\n }\n}", "solution_c": "class Bank {\npublic:\n\tvector temp;\n\tint n;\n\tBank(vector& balance) {\n\t\ttemp=balance;\n\t\tn=balance.size();\n\t}\n\n\tbool transfer(int account1, int account2, long long money) {\n\t\tif(account1<=n && account2<=n && account1>0 && account2>0 && temp[account1-1]>=money){\n\t\t\ttemp[account1-1]-=money;\n\t\t\ttemp[account2-1]+=money;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool deposit(int account, long long money) {\n\t\tif(account>n || account<0)return false;\n\t\ttemp[account-1]+=money;\n\t\treturn true;\n\t}\n\n\tbool withdraw(int account, long long money) {\n\t\tif(account<=n && account>0 && temp[account-1]>=money){\n\t\t\ttemp[account-1]-=money;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n};" }, { "title": "Subarray With Elements Greater Than Varying Threshold", "algo_input": "You are given an integer array nums and an integer threshold.\n\nFind any subarray of nums of length k such that every element in the subarray is greater than threshold / k.\n\nReturn the size of any such subarray. If there is no such subarray, return -1.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n \nExample 1:\n\nInput: nums = [1,3,4,3,1], threshold = 6\nOutput: 3\nExplanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.\nNote that this is the only valid subarray.\n\n\nExample 2:\n\nInput: nums = [6,5,6,5,8], threshold = 7\nOutput: 1\nExplanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i], threshold <= 109\n\n", "solution_py": "class Solution:\n def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n nums = [0] + nums + [0]\n stack = [0]\n for i in range(1,len(nums)):\n while nums[i] < nums[stack[-1]]:\n tmp = nums[stack.pop()]\n if tmp > threshold / (i - stack[-1] - 1):\n return i - stack[-1] - 1\n stack.append(i)\n return -1", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} threshold\n * @return {number}\n */\nvar validSubarraySize = function(nums, threshold) {\n /*\n Approach: Use monotonous increasing array\n */\n let stack=[];\n for(let i=0;i0 && stack[stack.length-1][0]>nums[i]){\n let popped = stack.pop();\n let min = popped[0];\n let len = i-popped[1];\n if(min>threshold/len){\n return len;\n }\n start = popped[1];\n }\n stack.push([nums[i],start]);\n }\n let end = nums.length-1;\n for(let i=0;ithreshold/len){\n return len;\n }\n }\n return -1;\n};", "solution_java": "class Solution {\n public int validSubarraySize(int[] nums, int threshold) {\n int n = nums.length;\n int[] next_small = new int[n];\n int[] prev_small = new int[n];\n Stack stack = new Stack<>();\n stack.push(0);\n Arrays.fill(next_small, n);\n Arrays.fill(prev_small, -1);\n for(int i=1;i= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n prev_small[i] = stack.peek();\n }\n stack.push(i);\n }\n stack = new Stack<>();\n stack.push(n-1);\n for(int i=n-2;i>=0;i--){\n while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){\n stack.pop();\n } \n if(stack.size()!=0){\n next_small[i] = stack.peek();\n }\n stack.push(i);\n }\n for(int i=0;i& nums, int threshold) {\n int n = nums.size();\n vector lr(n, n), rl(n, -1);\n \n vector s;\n for(int i = 0; i < n; ++i) {\n while(!s.empty() and nums[i] < nums[s.back()]) {\n lr[s.back()] = i;\n s.pop_back();\n }\n s.push_back(i);\n }\n s.clear();\n for(int i = n - 1; ~i; --i) {\n while(!s.empty() and nums[i] < nums[s.back()]) {\n rl[s.back()] = i;\n s.pop_back();\n }\n s.push_back(i);\n }\n \n for(int i = 0; i < n; ++i) {\n long long length = lr[i] - rl[i] - 1;\n if(1LL * nums[i] * length > threshold) return length;\n }\n \n return -1;\n }\n};\n// please upvote if you like" }, { "title": "Increasing Subsequences", "algo_input": "Given an integer array nums, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.\n\nThe given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.\n\n \nExample 1:\n\nInput: nums = [4,6,7,7]\nOutput: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n\n\nExample 2:\n\nInput: nums = [4,4,3,2,1]\nOutput: [[4,4]]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 15\n\t-100 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n def backtracking(nums,path):\n # to ensure that the base array has at least 2 elements\n if len(path)>=2:\n res.add(tuple(path))\n for i in range(len(nums)):\n # to ensure that every element to be added is equal or larger than the former\n if not path or path[-1] <= nums[i]:\n backtracking(nums[i+1:],path+[nums[i]])\n\n res=set()\n backtracking(nums,[])\n return res", "solution_js": "var findSubsequences = function(nums) {\n \n const result = [];\n const set = new Set();\n \n function bt(index=0,ar=[]){\n if(!set.has(ar.join(\"_\")) && ar.length >=2){\n set.add(ar.join(\"_\"));\n result.push(ar);\n }\n for(let i =index; i= ar[ar.length-1] || ar.length===0){\n bt(i+1, [...ar, nums[i]]);\n }\n }\n }\n \n bt();\n return result;\n};", "solution_java": "class Solution {\n HashSet> set;\n public List> findSubsequences(int[] nums) {\n set=new HashSet<>();\n\n dfs(nums,0,new ArrayList<>());\n\n List> ans=new ArrayList<>();\n if(set.size()>0){\n ans.addAll(set);\n }\n return ans;\n }\n\n private void dfs(int nums[], int start, List temp){\n if(start==nums.length) return;\n\n for(int i=start;i=2) set.add(new ArrayList<>(temp));\n\n dfs(nums,i+1,temp);\n temp.remove(temp.size()-1);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n set>ans;\n void solve(int start, int n, vector&nums, vector&result){\n if(result.size()>1)ans.insert(result);\n if(start==n){\n return;\n }\n for(int i=start; i> findSubsequences(vector& nums) {\n int n = nums.size();\n vectorresult;\n solve(0, n, nums, result);\n return vector>(ans.begin(), ans.end());\n }\n};" }, { "title": "Decrypt String from Alphabet to Integer Mapping", "algo_input": "You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:\n\n\n\tCharacters ('a' to 'i') are represented by ('1' to '9') respectively.\n\tCharacters ('j' to 'z') are represented by ('10#' to '26#') respectively.\n\n\nReturn the string formed after mapping.\n\nThe test cases are generated so that a unique mapping will always exist.\n\n \nExample 1:\n\nInput: s = \"10#11#12\"\nOutput: \"jkab\"\nExplanation: \"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".\n\n\nExample 2:\n\nInput: s = \"1326#\"\nOutput: \"acz\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts consists of digits and the '#' letter.\n\ts will be a valid string such that mapping is always possible.\n\n", "solution_py": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n for i in range(26,0,-1): s = s.replace(str(i)+\"#\"*(i>9),chr(96+i))\n return s", "solution_js": "var freqAlphabets = function(s) {\n const ans = []\n for (let i = 0, len = s.length; i < len; ++i) {\n const c = s.charAt(i)\n if (c === '#') {\n ans.length = ans.length - 2\n ans.push(String.fromCharCode(parseInt(`${s.charAt(i - 2)}${s.charAt(i - 1)}`, 10) + 96))\n continue\n }\n ans.push(String.fromCharCode(+c + 96))\n }\n return ans.join('')\n};", "solution_java": "class Solution {\n public String freqAlphabets(String str) {\n HashMap map = new HashMap<>();\n int k = 1;\n for (char ch = 'a'; ch <= 'z'; ch++) {\n if (ch < 'j')\n map.put(String.valueOf(k++), ch);\n else\n map.put(String.valueOf(k++)+\"#\", ch);\n }\n \n StringBuilder sb = new StringBuilder();\n int i = str.length() - 1;\n while (i >= 0) {\n if (str.charAt(i) == '#') {\n sb.append(map.get(str.substring(i - 2, i+1)));\n i -= 3;\n } else {\n sb.append(map.get(str.substring(i, i + 1)));\n i--;\n }\n }\n \n return sb.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n\tstring freqAlphabets(string s) {\n\t\tint n=s.size(); \n\t\tstring ans=\"\";\n\t\tfor(int i=0;i bool:\n\n # intuition:\n # write each numbes as fraction: num / den\n # then compare the two fractions.\n\n num1, den1 = self.toFraction(s)\n num2, den2 = self.toFraction(t)\n\n return den1 * num2 == den2 * num1\n\n def toFraction(self, s: str) -> typing.Tuple[int, int]:\n if \".\" not in s:\n return int(s), 1\n\n intp, frac = s.split(\".\")\n # decimal dot, but no repeating part:\n # xyz.abc = xyzabc / 1000\n if \"(\" not in frac:\n ifrac = int(frac) if len(frac) > 0 else 0\n num = int(intp) * (10 ** len(frac)) + ifrac\n den = 10 ** len(frac)\n return num, den\n\n # this is for cases like a.b(c)\n # let n = a.b(c)\n # then, 10^(len(b+c)) * n = abc.(c)\n # and 10^(len(b)) * n = ab.(c)\n # subtract the two, and solve for n:\n # n = (abc - ab) / (10^len(b + c) - 10^len(b))\n frac, repfrac = frac.split(\"(\")\n repfrac = repfrac[:-1]\n\n iintp = int(intp)\n ifrac = int(frac) if len(frac) > 0 else 0\n irep = int(repfrac)\n\n return (\n (iintp * (10 ** (len(frac + repfrac))) + ifrac * 10 ** len(repfrac) + irep) - (iintp * 10 ** len(frac) + ifrac),\n (10** len(frac+repfrac) - 10 **len(frac))\n )\n ```", "solution_js": "var isRationalEqual = function(s, t) {\n return calculate(s) === calculate(t);\n\n function calculate(v) {\n let start = v.split('(')[0] || v;\n let newer = v.split('(')[1] && v.split('(')[1].split(')')[0] || '0';\n\n start = start.includes('.') ? start : start + '.';\n newer = newer.padEnd(100, newer);\n\n return parseFloat(start + newer);\n }\n};", "solution_java": "class Solution {\n\n private List ratios = Arrays.asList(1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999);\n\n public boolean isRationalEqual(String S, String T) {\n return Math.abs(computeValue(S) - computeValue(T)) < 1e-9;\n }\n\n private double computeValue(String s) {\n if (!s.contains(\"(\")) {\n return Double.valueOf(s);\n } else {\n double intNonRepeatingValue = Double.valueOf(s.substring(0, s.indexOf('(')));\n int nonRepeatingLength = s.indexOf('(') - s.indexOf('.') - 1;\n int repeatingLength = s.indexOf(')') - s.indexOf('(') - 1;\n int repeatingValue = Integer.parseInt(s.substring(s.indexOf('(') + 1, s.indexOf(')')));\n return intNonRepeatingValue + repeatingValue * Math.pow(0.1, nonRepeatingLength) * ratios.get(repeatingLength);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n double toDouble(string s){\n\n // Strings for each integral, fractional, and repeating part\n string in=\"\", fn=\"\", rn=\"\";\n\n int i=0;\n\n // Integral\n while(i List[str]:\n pattern = r\"(?<=\\b\" + first +\" \" + second + r\" )[a-z]*\"\n txt = re.findall(pattern,text)\n return txt", "solution_js": "var findOcurrences = function(text, first, second) {\n let result = [];\n let txt = text.split(' ');\n for(let i = 0; i list = new ArrayList<>();\n \n String[] arr = text.split(\" \");\n \n for(int i = 0; i < arr.length - 2; i++) {\n if(arr[i].equals(first) && arr[i + 1].equals(second)) {\n list.add(arr[i + 2]);\n }\n }\n \n String[] result = list.toArray(new String[0]);\n \n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n\tvector findOcurrences(string text, string first, string second) {\n\t\tvectorans;\n\t\tint i=0;\n\t\twhile(i int:\n fib_sq = [1, 1]\n while fib_sq[-1] + fib_sq[-2] <= k:\n fib_sq.append(fib_sq[-1]+fib_sq[-2])\n counter = 0\n for i in range(len(fib_sq)-1, -1, -1):\n if fib_sq[i] <= k:\n counter += 1\n k -= fib_sq[i]\n return counter", "solution_js": "var findMinFibonacciNumbers = function(k) {\n let sequence = [1, 1], sum = sequence[0] + sequence[1];\n let i = 2;\n while (sum <= k) {\n sequence.push(sum);\n i++;\n sum = sequence[i-1]+sequence[i-2];\n }\n let j = sequence.length-1, res = 0;\n while (k) {\n if (k >= sequence[j]) k -= sequence[j], res++;\n j--;\n }\n return res;\n // Time Complexity: O(n)\n // Space Complexity: O(n)\n};", "solution_java": "class Solution {\n public int findMinFibonacciNumbers(int k) {\n int ans = 0;\n\n while (k > 0) {\n\t\t\t// Run until solution is reached\n int fib2prev = 1;\n int fib1prev = 1;\n while (fib1prev <= k) {\n\t\t\t\t// Generate Fib values, stop when fib1prev is > k, we have the fib number we want stored in fib2prev\n int temp = fib2prev + fib1prev;\n fib2prev = fib1prev;\n fib1prev = temp;\n }\n k -= fib2prev;\n ans += 1;\n }\n return ans;\n }\n}", "solution_c": "class Solution\n{\npublic:\n int findMinFibonacciNumbers(int k)\n {\n vector fibb;\n int a = 1;\n int b = 1;\n fibb.push_back(a);\n fibb.push_back(b);\n int next = a + b;\n\n while (next <= k)\n {\n fibb.push_back(next);\n a = b;\n b = next;\n next = a + b;\n }\n\n int res = 0;\n int j = fibb.size() - 1;\n while (j >= 0 and k > 0)\n {\n if (fibb[j] <= k)\n {\n k -= fibb[j];\n res++;\n }\n j--;\n }\n\n return res;\n }\n};" }, { "title": "Rotate List", "algo_input": "Given the head of a linked list, rotate the list to the right by k places.\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [4,5,1,2,3]\n\n\nExample 2:\n\nInput: head = [0,1,2], k = 4\nOutput: [2,0,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 500].\n\t-100 <= Node.val <= 100\n\t0 <= k <= 2 * 109\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n if k==0 or head is None or head.next is None:\n return head\n cur=head\n n=0\n while cur is not None:\n cur=cur.next\n n+=1\n k=n-k%n\n if k==n:\n return head\n cur=head\n prev=None\n while k>0 and cur is not None:\n prev=cur\n cur=cur.next\n k-=1\n prev.next=None\n prev=cur\n while cur.next is not None:\n cur=cur.next\n cur.next=head\n return prev\n ", "solution_js": "var rotateRight = function(head, k) {\n if(k === 0 || !head) return head;\n\n let n = 0;\n let end = null;\n\n let iterator = head;\n while(iterator) {\n n += 1;\n end = iterator;\n iterator = iterator.next;\n }\n\n const nodesToRotate = k % n;\n if(nodesToRotate === 0) return head;\n\n let breakAt = n - nodesToRotate;\n iterator = head;\n while(breakAt - 1 > 0) {\n iterator = iterator.next;\n breakAt -= 1;\n }\n\n const newHead = iterator.next;\n iterator.next = null;\n end.next = head;\n\n return newHead;\n};", "solution_java": "class Solution {\n public ListNode rotateRight(ListNode head, int k) {\n if(k<=0 || head==null || head.next==null){\n return head;\n }\n \n int length=1;\n ListNode first=head;\n ListNode curr=head;\n ListNode node=head; \n while(node.next!=null){\n length++;\n node=node.next;\n }\n \n if(k==length){\n return head;\n }\n \n int n=length-(k%length);\n for(int i=0; i1\n head=curr.next;\n curr.next=null;\n \n return head;\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n// like if it is useful to you\n ListNode* rotateRight(ListNode* head, int k) {\n if(head == NULL){\n return head;\n }\n vector nums;\n ListNode *temp = head;\n while(temp != NULL){\n nums.push_back(temp->val);\n temp = temp->next;\n }\n// if k greater than size;\n k = k%nums.size();\n// rotating vector\n reverse(nums.begin(),nums.end());\n reverse(nums.begin(),nums.begin()+k);\n reverse(nums.begin()+k,nums.end());\n// replace value of list \n temp = head;\n for(int i = 0; ival = nums[i];\n temp = temp->next;\n }\n return head;\n }\n};" }, { "title": "Binary Search Tree Iterator", "algo_input": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):\n\n\n\tBSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.\n\tboolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.\n\tint next() Moves the pointer to the right, then returns the number at the pointer.\n\n\nNotice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.\n\nYou may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.\n\n \nExample 1:\n\nInput\n[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\nOutput\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\nExplanation\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 105].\n\t0 <= Node.val <= 106\n\tAt most 105 calls will be made to hasNext, and next.\n\n\n \nFollow up:\n\n\n\tCould you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?\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 BSTIterator:\n\n def __init__(self, root: Optional[TreeNode]):\n self.root=root\n self.tree=[]#list to store the inorder traversal\n def inorder(node):\n if not node:\n return\n inorder(node.left)\n self.tree.append(node.val)\n inorder(node.right)\n return\n inorder(self.root)\n self.i=0\n \n\n def next(self) -> int:\n self.i+=1\n return self.tree[self.i-1]\n\n def hasNext(self) -> bool:\n return self.i-1 0;\n};\n\n/** \n * Your BSTIterator object will be instantiated and called as such:\n * var obj = new BSTIterator(root)\n * var param_1 = obj.next()\n * var param_2 = obj.hasNext()\n */", "solution_java": "class BSTIterator {\n\n TreeNode root;\n TreeNode current;\n Stack st = new Stack<>();\n public BSTIterator(TreeNode root) {\n this.root = root;\n //init(root);\n current = findLeft(root);\n //System.out.println(\"Init: stack is: \"+st);\n }\n\n public int next() {\n \n int val = -1;\n if(current != null)\n val = current.val;\n else\n return -1;\n \n if(current.right != null)\n current = findLeft(current.right);\n else if(!st.isEmpty())\n current = st.pop();\n else \n current = null;\n // System.out.println(\"next: stack is: \"+st);\n return val;\n }\n \n public TreeNode findLeft(TreeNode node) {\n \n if(node == null)\n return null;\n \n if(node.left != null){\n TreeNode next = node.left;\n st.push(node);\n return findLeft(next);\n }\n else\n return node;\n \n }\n \n public boolean hasNext() {\n return current != null;\n }\n}", "solution_c": "//TC O(1) and O(H) Space\n\n//MIMIC inorder\nclass BSTIterator {\npublic:\n stack stk;\n BSTIterator(TreeNode* root) {\n pushAll(root);\n // left is done\n }\n \n int next() {\n //root handled\n TreeNode* node = stk.top();\n int ans = node->val;\n stk.pop();\n \n //right handled\n pushAll(node->right);\n \n return ans;\n \n }\n \n bool hasNext() {\n return stk.size() != 0; // stk is empty then no next to show simple\n }\n \n void pushAll(TreeNode* root){\n //left part - as inorder is like Left left left, once a root is done then check right\n while(root!= NULL){\n stk.push(root);\n root = root->left;\n }\n \n }\n};" }, { "title": "Minimum Adjacent Swaps to Reach the Kth Smallest Number", "algo_input": "You are given a string num, representing a large integer, and an integer k.\n\nWe call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.\n\n\n\tFor example, when num = \"5489355142\":\n\n\t\n\t\tThe 1st smallest wonderful integer is \"5489355214\".\n\t\tThe 2nd smallest wonderful integer is \"5489355241\".\n\t\tThe 3rd smallest wonderful integer is \"5489355412\".\n\t\tThe 4th smallest wonderful integer is \"5489355421\".\n\t\n\t\n\n\nReturn the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.\n\nThe tests are generated in such a way that kth smallest wonderful integer exists.\n\n \nExample 1:\n\nInput: num = \"5489355142\", k = 4\nOutput: 2\nExplanation: The 4th smallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"\n\n\nExample 2:\n\nInput: num = \"11112\", k = 4\nOutput: 4\nExplanation: The 4th smallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"\n\n\nExample 3:\n\nInput: num = \"00123\", k = 1\nOutput: 1\nExplanation: The 1st smallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"\n\n\n \nConstraints:\n\n\n\t2 <= num.length <= 1000\n\t1 <= k <= 1000\n\tnum only consists of digits.\n\n", "solution_py": "class Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n num = list(num)\n orig = num.copy()\n \n for _ in range(k): \n for i in reversed(range(len(num)-1)): \n if num[i] < num[i+1]: \n ii = i+1 \n while ii < len(num) and num[i] < num[ii]: ii += 1\n num[i], num[ii-1] = num[ii-1], num[i]\n lo, hi = i+1, len(num)-1\n while lo < hi: \n num[lo], num[hi] = num[hi], num[lo]\n lo += 1\n hi -= 1\n break \n \n ans = 0\n for i in range(len(num)): \n ii = i\n while orig[i] != num[i]: \n ans += 1\n ii += 1\n num[i], num[ii] = num[ii], num[i]\n return ans ", "solution_js": "var getMinSwaps = function(num, k) {\n \n const digits = [...num]\n const len = digits.length;\n \n // helper function to swap elements in digits in place\n const swap = (i, j) => [digits[i], digits[j]] = [digits[j], digits[i]]\n \n // helper function to reverse elements in digits from i to the end of digits\n const reverse = (i) => {\n for (let j = len - 1; i < j; ++i && --j) {\n swap(i, j);\n }\n }\n \n // helper to get the next smallest permutation for digits\n const nextPermutation = () => {\n // from right to left, find the first decreasing index\n // in digits and store it as i\n let i = len - 2;\n while (digits[i] >= digits[i + 1]) {\n i--;\n }\n \n // from right to left, find the first index in digits\n // that is greater than element at i\n let j = len - 1;\n while (digits[j] <= digits[i]) {\n j--;\n }\n \n // swap the 2 elements at i and j\n swap(i, j);\n // reverse all elements after i because we know that\n // all elements after i are in ascending order\n // from right to left\n reverse(i + 1);\n }\n \n // find the next permutation k times\n for (let i = 0; i < k; i++) {\n nextPermutation();\n }\n\n // find out how many swaps it will take to get to the\n // kth permutation by finding out how many swaps\n // it takes to put digits back to its original state\n let numSwaps = 0;\n for (let i = 0; i < len; i++) {\n let j = i;\n // find the first element in digits to matches\n // num[i] and hold its place at j\n while (num[i] !== digits[j]) {\n j++;\n }\n \n // move the element at j to i while counting the\n // number of swaps\n while (i < j) {\n swap(j, j - 1);\n numSwaps++;\n j--;\n }\n }\n return numSwaps;\n};", "solution_java": "class Solution {\n public int getMinSwaps(String num, int k) {\n int[] nums=new int[num.length()];\n int[] org=new int[num.length()];\n\n for(int i=0;i0 && j!=i){\n swap(org,j,j-1);\n ans++;\n j--;\n }\n\n }\n\n }\n\n return ans;\n\n }\n\npublic void nextPermutation(int[] nums) {\n\n if(nums.length<=1)\n return;\n\n int j=nums.length-2;\n while(j>=0 && nums[j]>=nums[j+1])\n j--;\n\n if(j>=0){\n int k=nums.length-1;\n while(nums[j]>=nums[k])\n k--;\n\n swap(nums,j,k);\n\n }\n\n reverse(nums,j+1,nums.length-1);\n\n }\n\n public void swap(int[] nums,int j,int k){\n int temp=nums[j];\n nums[j]=nums[k];\n nums[k]=temp;\n }\n\n public void reverse(int[] nums,int i,int j){\n while(i<=j){\n swap(nums,i,j);\n i++;\n j--;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n\n // GREEDY APPROACH\n // min steps to make strings equal\n\n int minSteps(string s1, string s2) {\n int size = s1.length();\n int i = 0, j = 0;\n int result = 0;\n\n while (i < size) {\n j = i;\n while (s1[j] != s2[i]) j++;\n\n while (i < j) {\n swap(s1[j], s1[j-1]);\n j--;\n result++;\n }\n i++;\n }\n return result;\n }\n\n int getMinSwaps(string num, int k) {\n string original = num;\n\n while(k--) {\n next_permutation(num.begin(), num.end());\n }\n\n return minSteps(original, num);\n }\n};" }, { "title": "Height Checker", "algo_input": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.\n\nYou are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).\n\nReturn the number of indices where heights[i] != expected[i].\n\n \nExample 1:\n\nInput: heights = [1,1,4,2,1,3]\nOutput: 3\nExplanation: \nheights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.\n\n\nExample 2:\n\nInput: heights = [5,1,2,3,4]\nOutput: 5\nExplanation:\nheights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.\n\n\nExample 3:\n\nInput: heights = [1,2,3,4,5]\nOutput: 0\nExplanation:\nheights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.\n\n\n \nConstraints:\n\n\n\t1 <= heights.length <= 100\n\t1 <= heights[i] <= 100\n\n", "solution_py": "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n heightssort = sorted(heights)\n import numpy as np\n diff = list(np.array(heightssort) - np.array(heights))\n return (len(diff) - diff.count(0))", "solution_js": "var heightChecker = function(heights) {\n let count = 0;\n const orderedHeights = [...heights].sort((a, b) => a-b)\n\n for (let i = 0; i < heights.length; i++) {\n heights[i] !== orderedHeights[i] ? count++ : null\n }\n\n return count\n};", "solution_java": "class Solution {\n public int heightChecker(int[] heights) {\n\n int[] dupheights = Arrays.copyOfRange(heights , 0 ,heights.length);\n\n Arrays.sort(dupheights);\n int count = 0;\n\n for(int i=0 ; i< heights.length ; i++){\n\n if(heights[i] != dupheights[i]){\n count++;\n }\n\n }\n\n return count;\n\n }\n}", "solution_c": "class Solution {\npublic:\n int heightChecker(vector& heights) {\n vector expected=heights;\n int count=0;\n sort(expected.begin(),expected.end());\n for(int i=0;i bool:\n \n def isadditive(num1,num2,st):\n if len(st) == 0:\n return True\n num3 = str(num1+num2)\n l = len(num3)\n return num3 == st[:l] and isadditive(num2,int(num3),st[l:])\n \n for i in range(1,len(num)-1):\n for j in range(i+1,len(num)):\n if num [0] == \"0\" and i != 1:\n break\n if num[i] == \"0\" and i+1 != j:\n break\n \n if isadditive(int(num[:i]),int(num[i:j]),num[j:]):\n \n return True\n return False", "solution_js": "const getNum = (str, i, j) => {\n str = str.slice(i, j);\n if(str[0] == '0' && str.length > 1) return -1000\n return Number(str);\n}\n\nvar isAdditiveNumber = function(num) {\n // i = 3 say and make theory and proof that\n const len = num.length;\n for(let b = 2; b < len; b++) {\n for(let i = 0; i < b - 1; i++) {\n for(let j = i + 1; j < b; j++) {\n let v1 = getNum(num,0, i + 1);\n let v2 = getNum(num,i + 1, j + 1);\n let v3 = getNum(num,j + 1, b + 1);\n if(v1 + v2 == v3) {\n // test hypothesis;\n // from b start checking if string persist behaviour\n let p = num.slice(0, b + 1);\n while(p.length <= len) {\n let sum = v2 + v3;\n p += sum;\n v2 = v3;\n v3 = sum;\n }\n if(p.slice(0, len) == num) {\n return true;\n }\n }\n }\n }\n }\n return false;\n};", "solution_java": "class Solution {\n\n public boolean isAdditiveNumber(String num) {\n return backtrack(num, 0, 0, 0, 0);\n }\n \n public boolean backtrack(String num, int idx, long sum, long prev, int length){\n if(idx == num.length()){\n return length >= 3;\n }\n \n long currLong = 0;\n \n for(int i = idx; i < num.length(); i++){\n //make sure it won't start with 0\n if(i > idx && num.charAt(idx) == '0') break;\n currLong = currLong * 10 + num.charAt(i) - '0';\n \n if(length >= 2){\n if(sum < currLong){\n //currLong is greater than sum of previous 2 numbers\n break;\n }else if(sum > currLong){\n //currLong is smaller than sum of previous 2 numbers\n continue;\n }\n }\n //currLong == sum of previous 2 numbers\n if(backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true){\n return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution\n{\npublic:\n bool isAdditiveNumber(string num)\n {\n vector adds;\n return backtrack(num, 0, adds);\n }\n\nprivate:\n bool backtrack(string num, int start, vector &adds)\n {\n if (start >= num.size() && adds.size() >= 3)\n return true;\n\n int maxSize = num[start] == '0' ? 1 : num.size() - start;\n for (int i = 1; i <= maxSize; i++)\n {\n string current = num.substr(start, i);\n\n if (adds.size() >= 2)\n {\n string num1 = adds[adds.size() - 1], num2 = adds[adds.size() - 2];\n string sum = add(num1, num2);\n if (sum != current)\n continue;\n }\n\n adds.push_back(current);\n if (backtrack(num, start + i, adds))\n return true;\n adds.pop_back();\n }\n return false;\n }\n\n string add(string num1, string num2)\n {\n string sum;\n int i1 = num1.size() - 1, i2 = num2.size() - 1, carry = 0;\n while (i1 >= 0 || i2 >= 0)\n {\n int current = carry + (i1 >= 0 ? (num1[i1--] - '0') : 0) + (i2 >= 0 ? (num2[i2--] - '0') : 0);\n carry = current / 10;\n sum.push_back(current % 10 + '0');\n }\n if (carry)\n sum.push_back(carry + '0');\n reverse(begin(sum), end(sum));\n return sum;\n }\n};" }, { "title": "Generate a String With Characters That Have Odd Counts", "algo_input": "Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.\n\nThe returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.  \n\n \nExample 1:\n\nInput: n = 4\nOutput: \"pppz\"\nExplanation: \"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".\n\n\nExample 2:\n\nInput: n = 2\nOutput: \"xy\"\nExplanation: \"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".\n\n\nExample 3:\n\nInput: n = 7\nOutput: \"holasss\"\n\n\n \nConstraints:\n\n\n\t1 <= n <= 500\n\n", "solution_py": "class Solution:\n def generateTheString(self, n: int) -> str:\n alpha = \"abcdefghijklmnopqrstuvwxyz\"\n res=\"\"\n while n>0:\n curr, alpha = alpha[0], alpha[1:]\n if n%2:\n res += curr*n\n n-=n\n else: \n res += curr*(n-1)\n n-=n-1\n return res", "solution_js": "// C++ Code\nclass Solution {\npublic:\n string generateTheString(int n) {\n string res = \"\";\n if (n%2 == 0)\n {\n res += 'a';\n n -= 1;\n }\n for (int i=0;i < n;i++)\n res += 'k';\n return res;\n }\n};\n\n\n// JavaScript Code\nvar generateTheString = function(n) {\n let ans = [];\n let state = n % 2 === 0 ? true : false;\n \n if(!state){\n for(let i=0;i List[int]:\n idx, i = [], 1\n prev, cur = head, head.next\n while cur and cur.next:\n if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n idx.append(i)\n prev = cur\n cur = cur.next\n i += 1\n\n if len(idx) < 2:\n return [-1, -1]\n \n minDist = min(j - i for i, j in pairwise(idx))\n maxDist = idx[-1] - idx[0]\n\n return [minDist, maxDist]", "solution_js": "var nodesBetweenCriticalPoints = function(head) {\n const MAX = Number.MAX_SAFE_INTEGER;\n const MIN = Number.MIN_SAFE_INTEGER;\n \n let currNode = head.next;\n let prevVal = head.val;\n \n let minIdx = MAX;\n let maxIdx = MIN;\n \n let minDist = MAX;\n let maxDist = MIN;\n \n for (let i = 1; currNode.next != null; ++i) {\n const currVal = currNode.val;\n const nextNode = currNode.next;\n const nextVal = nextNode.val;\n \n // Triggers when we have either a maxima or a minima\n if ((prevVal < currVal && currVal > nextVal) || (prevVal > currVal && currVal < nextVal)) {\n if (maxIdx != MIN) minDist = Math.min(minDist, i - maxIdx);\n if (minIdx != MAX) maxDist = Math.max(maxDist, i - minIdx);\n \n if (minIdx == MAX) minIdx = i;\n maxIdx = i;\n }\n \n prevVal = currVal;\n currNode = nextNode;\n }\n\n const minRes = minDist === MAX ? -1 : minDist;\n const maxRes = maxDist === MIN ? -1 : maxDist;\n \n return [minRes, maxRes];\n};", "solution_java": "class Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int res[]=new int[]{-1,-1};\n if(head==null||head.next==null||head.next.next==null) return res;\n int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1;\n ListNode prev=head,ptr=head.next;\n int idx=1,minD=Integer.MAX_VALUE;\n while(ptr!=null&&ptr.next!=null){\n if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val nodesBetweenCriticalPoints(ListNode* head) {\n if(!head or !head->next or !head->next->next) return {-1,-1};\n int mini = 1e9;\n int prevInd = -1e9;\n int currInd = 0;\n int start = -1e9;\n int prev = head->val;\n head = head->next;\n\n while(head->next){\n if(prevval and head->next->valval){\n mini = min(mini,currInd-prevInd);\n prevInd = currInd;\n if(start==-1e9) start = currInd;\n }\n if(prev>head->val and head->next->val>head->val){\n mini = min(mini,currInd-prevInd);\n prevInd = currInd;\n if(start==-1e9) start = currInd;\n }\n prev = head->val;\n head = head->next;\n currInd++;\n }\n\n if(start!=prevInd) return {mini,prevInd-start};\n return {-1,-1};\n }\n};" }, { "title": "Longest Palindromic Substring", "algo_input": "Given a string s, return the longest palindromic substring in s.\n\n \nExample 1:\n\nInput: s = \"babad\"\nOutput: \"bab\"\nExplanation: \"aba\" is also a valid answer.\n\n\nExample 2:\n\nInput: s = \"cbbd\"\nOutput: \"bb\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts consist of only digits and English letters.\n\n", "solution_py": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n res = \"\"\n for i in range(len(s)):\n left, right = i - 1, i + 1\n\n while (right < len(s) and s[right] == s[i]):\n right += 1\n\n while (0 <= left < right < len(s) and s[left] == s[right]):\n left, right = left - 1, right + 1\n\n res = s[left+1:right] if right - left-1 > len(res) else res\n return res", "solution_js": "I solve the problem distinguishing two different cases.\nFirst I consider the case when the length of the palindrome to be found is odd (there is a center). \n\tI then expand the search to left and right from the possible found center.\nThen I consider the case when the length of the palindrome to be found is pair (there is no center/middle).\n\tI then expand the search to left and right from the possible palindrome having the form \"xx\".\n```/**\n * @param {string} s\n * @return {string}\n */\nvar longestPalindrome = function(s) {\n let longestP = s[0];\n let palindrome = \"\";\n if(s.length === 1 ) return s;\n \n //the length of the palindrome is odd\n for(let index = 1; index < s.length-1; index++){\n if(s[index - 1] === s[index + 1]){\n palindrome = s[index - 1] + s[index] + s[index + 1];\n for(let k = 1; index - 1 - k > -1 && index + 1 + k < s.length; k++){\n if(s[index - 1 - k] === s[index + 1 + k]){\n palindrome = s[index - 1 - k] + palindrome + s[index + 1 + k];\n }\n else{\n break;\n }\n }\n }\n if (palindrome.length > longestP.length){\n longestP = palindrome;\n }\n palindrome = \"\";\n }\n \n //the length of the palindrome is pair\n for(let index = 0; index < s.length-1; index++){\n if(s[index] === s[index + 1]){\n palindrome = s[index] + s[index + 1];\n for(let k = 1; (index - k > -1) && (index + 1 + k < s.length); k++){\n if(s[index - k] === s[index + 1 + k]){\n palindrome = s[index - k] + palindrome + s[index + 1 + k];\n }\n else{\n break;\n }\n }\n }\n if (palindrome.length > longestP.length){\n longestP = palindrome;\n }\n palindrome = \"\";\n }\n return longestP;\n};`", "solution_java": "class Solution {\n String max = \"\";\n \n private void checkPalindrome(String s, int l, int r) {\n while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {\n if (r - l >= max.length()) {\n max = s.substring(l, r + 1);\n } \n\n l--;\n r++;\n }\n }\n \n public String longestPalindrome(String s) {\n for (int i = 0; i < s.length(); i++) {\n checkPalindrome(s, i, i);\n checkPalindrome(s, i, i + 1); \n }\n \n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n string longestPalindrome(string s) {\n if(s.size() <= 1) return s;\n\n string longest = \"\";\n\n for (int i = 0; i < s.size(); i++) {\n string sub1 = expand(s, i, i+1);\n string sub2 = expand(s, i, i);\n\n string sub3 = sub1.size() > sub2.size() ? sub1 : sub2;\n\n if(sub3.size() > longest.size()) {\n longest = sub3;\n }\n }\n return longest;\n }\n\n string expand(string s, int i, int j) {\n while(j < s.size() && i >= 0 && s[i] == s[j]) {\n i--;\n j++;\n }\n // Add 1 to i and subtract 1 from j because the range is expanded by 1 on each side before it ends\n return s.substr(i+1, j-i-1);\n }\n};" }, { "title": "String Matching in an Array", "algo_input": "Given an array of string words. Return all strings in words which is substring of another word in any order. \n\nString words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].\n\n \nExample 1:\n\nInput: words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput: [\"as\",\"hero\"]\nExplanation: \"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.\n\n\nExample 2:\n\nInput: words = [\"leetcode\",\"et\",\"code\"]\nOutput: [\"et\",\"code\"]\nExplanation: \"et\", \"code\" are substring of \"leetcode\".\n\n\nExample 3:\n\nInput: words = [\"blue\",\"green\",\"bu\"]\nOutput: []\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 100\n\t1 <= words[i].length <= 30\n\twords[i] contains only lowercase English letters.\n\tIt's guaranteed that words[i] will be unique.\n\n", "solution_py": "class Solution:\n def stringMatching(self, words: List[str]) -> List[str]:\n ans=set()\n l=len(words)\n for i in range(l):\n for j in range(l):\n if (words[i] in words[j]) & (i!=j):\n ans.add(words[i])\n return ans", "solution_js": "var stringMatching = function(words) {\n let res = [];\n\n for (let i = 0; i < words.length; i++) {\n\n for (let j = 0; j < words.length; j++) {\n if (j === i) continue;\n\n if (words[j].includes(words[i])) {\n res.push(words[i]);\n break;\n }\n\n }\n }\n\n return res;\n};", "solution_java": "class Solution {\n public List stringMatching(String[] words) {\n Listans = new ArrayList<>();\n for(int i=0; i= 0){\n ans.add(s);\n break;\n }\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector stringMatching(vector& words) {\n vector res; //output\n\n for(int i = 0 ; i < words.size(); i++)\n {\n for(int j = 0; j < words.size(); j++)\n {\n if(i != j && words[j].find(words[i]) != -1)\n {\n if(!count(res.begin(),res.end(), words[i])) //if vector result does not include this string, push it to vector\n res.push_back(words[i]);\n else\n continue; //if vector result includes this string, ignore\n }\n }\n }\n \n return res;\n }\n};" }, { "title": "Uncrossed Lines", "algo_input": "You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.\n\nWe may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:\n\n\n\tnums1[i] == nums2[j], and\n\tthe line we draw does not intersect any other connecting (non-horizontal) line.\n\n\nNote that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).\n\nReturn the maximum number of connecting lines we can draw in this way.\n\n \nExample 1:\n\nInput: nums1 = [1,4,2], nums2 = [1,2,4]\nOutput: 2\nExplanation: We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\n\n\nExample 2:\n\nInput: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput: 3\n\n\nExample 3:\n\nInput: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 500\n\t1 <= nums1[i], nums2[j] <= 2000\n\n", "solution_py": "class Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n \n @lru_cache(None)\n def dp(a,b):\n if a>=len(nums1) or b>=len(nums2): return 0\n if nums1[a]==nums2[b]: return 1+dp(a+1,b+1)\n else: return max(dp(a+1,b),dp(a,b+1))\n \n return dp(0,0)", "solution_js": "/** https://leetcode.com/problems/uncrossed-lines/\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @return {number}\n */\nvar maxUncrossedLines = function(nums1, nums2) {\n // Array to hold the combination of connected numbers\n let dp = [];\n \n // We look up the connected numbers with matrix\n for (let i=0;i< nums1.length;i++){\n for (let j=0;j< nums2.length;j++){\n if (nums1[i]===nums2[j]){\n dp.push([i,j]);\n }\n }\n }\n \n // Only 0 or 1 connected numbers found, return\n if(dp.length <=1){\n return dp.length;\n }\n \n // Array to count how many connected numbers in the matrix without crossing\n let count=Array(dp.length).fill(1);\n let out = count[0];\n \n // Count from the last connected numbers, for each connected number, count how many other connected numbers in front of it that will not crossed with current\n for (let i=dp.length-2;i>=0;i--){\n for (let j=i+1;j& nums1, vector& nums2,vector> &dp)\n {\n if(n1<0 || n2<0)\n return 0;\n \n if(dp[n1][n2]!=-1)\n return dp[n1][n2];\n \n if(nums1[n1]==nums2[n2])\n return dp[n1][n2]=1+solve(n1-1,n2-1,nums1,nums2,dp);\n \n return dp[n1][n2]=max(solve(n1-1,n2,nums1,nums2,dp),solve(n1,n2-1,nums1,nums2,dp));\n }\n \n int maxUncrossedLines(vector& nums1, vector& nums2) {\n int n1=nums1.size(),n2=nums2.size();\n vector> dp(n1+1,vector(n2+1,-1));\n \n return solve(n1-1,n2-1,nums1,nums2,dp);\n }\n};" }, { "title": "Minimum Increment to Make Array Unique", "algo_input": "You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.\n\nReturn the minimum number of moves to make every value in nums unique.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [1,2,2]\nOutput: 1\nExplanation: After 1 move, the array could be [1, 2, 3].\n\n\nExample 2:\n\nInput: nums = [3,2,1,2,1,7]\nOutput: 6\nExplanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n c=0\n i=1\n num=[]\n \n while i a - b);\n\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] === arr[i + 1]) {\n arr[i + 1]++;\n ans++;\n }\n else if (arr[i] > arr[i + 1]) {\n if(arr[i] - arr[i - 1] === 1){\n ans += arr[i] - arr[i + 1] + 1\n arr[i + 1] += arr[i] - arr[i + 1] + 1;\n }\n }\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int minIncrementForUnique(int[] nums) {\n \n //Approach - 1 : Using a Count array\n \n // TC : O(N)\n // SC : O(N)\n \n int max = 0;\n for(int i : nums)\n max = Math.max(max, i);\n \n int count[] = new int[nums.length + max];\n\t\t\n for(int c : nums)\n count[c]++;\n\t\t\t\n int answer = 0, choosen = 0;\n\t\tint len = count.length;\n\t\t\n for(int i = 0; i< len; i++)\n {\n if(count[i] >= 2)\n {\n choosen += count[i] - 1;\n answer -= i * (count[i] - 1);\n }\n else if(choosen > 0 && count[i] == 0)\n {\n answer += i;\n choosen--;\n }\n }\n\t\t\n return answer;\n \n \n //Approach - 2:\n \n // TC : O(nlogn)\n // SC : O(1)\n \n Arrays.sort(nums);\n int answer = 0;\n for(int i=1; i= nums[i]){\n answer += nums[i-1]- nums[i] +1;\n nums[i] = nums[i-1] + 1; \n }\n }\n return answer;\n }\n}", "solution_c": "class Solution {\npublic:\n int minIncrementForUnique(vector& nums) {\n int minElePossible=0,ans=0;\n sort(nums.begin(),nums.end());\n for(int i=0;i int:\n beg = 0\n end = len(arr)-1\n \n while beg <= end:\n mid = (beg+end)//2\n if arr[mid] < arr[mid+1]:\n beg = mid +1\n elif arr[mid] > arr[mid+1]:\n end = mid -1\n return beg", "solution_js": "var peakIndexInMountainArray = function(arr) {\n\n //lets assume we have peak it divides array in two parts\n // first part is increasing order , second part is decreasing\n // when we find the middle we'll compare arr[middle] > arr[middle+1], it means\n //we can only find max in first part of arr (increasing part) else second part.\n //there will be point where start === end that is our peak\n let start = 0;\n let end = arr.length -1;\n while(start < end){\n let mid = parseInt(start + (end - start)/2)\n if( arr[mid] > arr[mid + 1]){\n end = mid;\n }else {\n start = mid +1;\n }\n }\n\n return start;\n\n};", "solution_java": "class Solution {\npublic int peakIndexInMountainArray(int[] arr) {\n\n int start = 0;\n int end = arr.length - 1;\n\n while( start < end){\n int mid = start + (end - start)/2;\n // if mid < mid next\n if(arr[mid] < arr[mid + 1]){\n start = mid + 1;\n }\n // otherwise it can either peak element or greater element\n else{\n end = mid;\n }\n }\n return start; // or we can return end also, bcz both will be on same value at the time, that's why loop breaks here.\n }\n}", "solution_c": "class Solution {\npublic:\n int peakIndexInMountainArray(vector& arr) {\n return max_element(arr.begin(), arr.end()) - arr.begin();\n }\n};" }, { "title": "Count Unhappy Friends", "algo_input": "You are given a list of preferences for n friends, where n is always even.\n\nFor each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.\n\nAll the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.\n\nHowever, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:\n\n\n\tx prefers u over y, and\n\tu prefers x over v.\n\n\nReturn the number of unhappy friends.\n\n \nExample 1:\n\nInput: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput: 2\nExplanation:\nFriend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.\n\n\nExample 2:\n\nInput: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput: 0\nExplanation: Both friends 0 and 1 are happy.\n\n\nExample 3:\n\nInput: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t2 <= n <= 500\n\tn is even.\n\tpreferences.length == n\n\tpreferences[i].length == n - 1\n\t0 <= preferences[i][j] <= n - 1\n\tpreferences[i] does not contain i.\n\tAll values in preferences[i] are unique.\n\tpairs.length == n/2\n\tpairs[i].length == 2\n\txi != yi\n\t0 <= xi, yi <= n - 1\n\tEach person is contained in exactly one pair.\n\n", "solution_py": "class Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n dd = {}\n \n for i,x in pairs:\n dd[i] = preferences[i][:preferences[i].index(x)]\n dd[x] = preferences[x][:preferences[x].index(i)]\n \n ans = 0\n \n for i in dd:\n for x in dd[i]:\n if i in dd[x]:\n ans += 1\n break\n \n return ans", "solution_js": "var unhappyFriends = function(n, preferences, pairs) {\n let happyMap = new Array(n);\n for (let [i, j] of pairs) {\n happyMap[i] = preferences[i].indexOf(j);\n happyMap[j] = preferences[j].indexOf(i);\n }\n \n let unhappy = 0;\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < happyMap[i]; j++) {\n let partner = preferences[i][j];\n if (preferences[partner].indexOf(i) < happyMap[partner]) {\n unhappy++;\n break;\n }\n }\n }\n \n return unhappy;\n};", "solution_java": "class Solution {\n public int unhappyFriends(int n, int[][] preferences, int[][] pairs) {\n int[][] rankings = new int[n][n]; // smaller the value, higher the preference\n int[] pairedWith = new int[n];\n for (int i = 0; i < n; i++) {\n for (int rank = 0; rank < n - 1; rank++) {\n int j = preferences[i][rank];\n rankings[i][j] = rank; // person \"i\" views person \"j\" with rank\n }\n }\n int unhappy = 0;\n for (int[] pair : pairs) {\n int a = pair[0], b = pair[1];\n pairedWith[a] = b;\n pairedWith[b] = a;\n }\n for (int a = 0; a < n; a++) {\n // \"a\" prefers someone else\n if (rankings[a][pairedWith[a]] != 0) {\n for (int b = 0; b < n; b++) {\n // \"b\" prefers to be with \"a\" over their current partner\n // \"a\" prefers to be with \"b\" over their current partner\n if (b != a\n && rankings[b][a] < rankings[b][pairedWith[b]]\n && rankings[a][b] < rankings[a][pairedWith[a]]) {\n unhappy++;\n break;\n }\n }\n }\n }\n return unhappy;\n }\n}", "solution_c": "class Solution {\npublic:\n bool check(int x , int y , int u , int v ,int n , vector>& pref){\n int id_x = 0 , id_y = 0 , id_u = 0 , id_v = 0 ;\n //check indices of (y and u) in pref[x] ;\n for(int i = 0 ; i < n - 1; ++i ){\n if(pref[x][i] == y) id_y = i ;\n if(pref[x][i] == u) id_u = i ;\n }\n \n //check indices of (v and x) in pref[u] ;\n for(int i = 0 ; i < n - 1 ; ++i ){\n if(pref[u][i] == v) id_v = i ;\n if(pref[u][i] == x) id_x = i ;\n }\n \n return (id_x < id_v and id_u < id_y) ;\n }\n int unhappyFriends(int n, vector>& preferences, vector>& pairs) {\n unordered_set unhappy ;\n for(int i = 0 ; i < pairs.size() ; ++i ){\n for(int j = i + 1; j < pairs.size() ; ++j){\n int x = pairs[i][0] , y = pairs[i][1] , u = pairs[j][0] , v = pairs[j][1] ;\n // x prefers u over y and u preferes x over v \n if(check(x,y,u,v,n,preferences)) unhappy.insert(x), unhappy.insert(u) ;\n // x prefers v over y and v prefers x over u \n if(check(x,y,v,u,n,preferences)) unhappy.insert(x) , unhappy.insert(v) ;\n // y prefers u over x and u prefers y over v\n if(check(y,x,u,v,n,preferences)) unhappy.insert(y) , unhappy.insert(u) ;\n // y prefers v over x and v prefers y over u \n if(check(y,x,v,u,n,preferences)) unhappy.insert(y) , unhappy.insert(v) ;\n }\n }\n return unhappy.size() ;\n }\n};" }, { "title": "Escape The Ghosts", "algo_input": "You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.\n\nEach turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.\n\nYou escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.\n\nReturn true if it is possible to escape regardless of how the ghosts move, otherwise return false.\n\n \nExample 1:\n\nInput: ghosts = [[1,0],[0,3]], target = [0,1]\nOutput: true\nExplanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\n\n\nExample 2:\n\nInput: ghosts = [[1,0]], target = [2,0]\nOutput: false\nExplanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\n\n\nExample 3:\n\nInput: ghosts = [[2,0]], target = [1,0]\nOutput: false\nExplanation: The ghost can reach the target at the same time as you.\n\n\n \nConstraints:\n\n\n\t1 <= ghosts.length <= 100\n\tghosts[i].length == 2\n\t-104 <= xi, yi <= 104\n\tThere can be multiple ghosts in the same location.\n\ttarget.length == 2\n\t-104 <= xtarget, ytarget <= 104\n\n", "solution_py": "class Solution:\n def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:\n t = float('inf')\n tx, ty = target\n for i, j in ghosts:\n t = min(t, abs(tx - i) + abs(ty - j))\n return t > abs(tx) + abs(ty)", "solution_js": "var escapeGhosts = function(ghosts, target) {\n const getDistance = (target, source = [0, 0]) => {\n return (\n Math.abs(target[0] - source[0])\n +\n Math.abs(target[1] - source[1])\n );\n }\n const timeTakenByMe = getDistance(target);\n let timeTakenByGhosts = Infinity;\n for(let ghost of ghosts) {\n timeTakenByGhosts = Math.min(timeTakenByGhosts, getDistance(target, ghost));\n }\n return timeTakenByGhosts > timeTakenByMe;\n};", "solution_java": "// Escape The Ghosts\n// Leetcode: https://leetcode.com/problems/escape-the-ghosts/\n\nclass Solution {\n public boolean escapeGhosts(int[][] ghosts, int[] target) {\n int dist = Math.abs(target[0]) + Math.abs(target[1]);\n for (int[] ghost : ghosts) {\n if (Math.abs(ghost[0] - target[0]) + Math.abs(ghost[1] - target[1]) <= dist) {\n return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n \n bool escapeGhosts(vector>& ghosts, vector& target) {\n int minimumstepsreqbyplayer = abs(target[0]) + abs(target[1]);\n int minimumstepsreqbyanyghost = INT_MAX;\n \n for(auto x: ghosts){\n minimumstepsreqbyanyghost = min(minimumstepsreqbyanyghost, abs(x[0]-target[0]) + abs(x[1]-target[1]));\n }\n \n return minimumstepsreqbyplayer int:\n even_count = 0\n for elem in nums:\n if(len(str(elem))%2 == 0):\n even_count += 1\n return even_count\n ", "solution_js": "var findNumbers = function(nums) {\n\tlet count = 0;\n\tfor(let num of nums){\n\t\tif(String(num).length % 2 === 0) count++\n\t}\n\treturn count;\n};", "solution_java": "class Solution \n{\n public int findNumbers(int[] nums) \n {\n int count = 0;\n for(int val : nums)\n {\n if((val>9 && val<100) || (val>999 && val<10000) || val==100000 )\n count++;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int findNumbers(vector& nums) {\n int count = 0;\n\n for(auto it:nums)\n {\n int amount = 0;\n while(it>0)\n {\n amount++;\n it /= 10;\n }\n if (amount % 2 == 0)\n {\n count++;\n }\n }\n return count;\n }\n};" }, { "title": "Minimize Maximum Pair Sum in Array", "algo_input": "The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.\n\n\n\tFor example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.\n\n\nGiven an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:\n\n\n\tEach element of nums is in exactly one pair, and\n\tThe maximum pair sum is minimized.\n\n\nReturn the minimized maximum pair sum after optimally pairing up the elements.\n\n \nExample 1:\n\nInput: nums = [3,5,2,3]\nOutput: 7\nExplanation: The elements can be paired up into pairs (3,3) and (5,2).\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\n\n\nExample 2:\n\nInput: nums = [3,5,4,2,4,6]\nOutput: 8\nExplanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t2 <= n <= 105\n\tn is even.\n\t1 <= nums[i] <= 105\n", "solution_py": "class Solution:\n def minPairSum(self, nums: List[int]) -> int:\n pair_sum = []\n nums.sort()\n for i in range(len(nums)//2):\n pair_sum.append(nums[i]+nums[len(nums)-i-1])\n return max(pair_sum)", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minPairSum = function(nums) {\n nums.sort((a,b) => a-b);\n let max = 0;\n for(let i=0; i& nums){\n\t //sort the array\n sort(nums.begin(),nums.end());\n int start=0,end=nums.size()-1,min_max_pair_sum=0;\n\t\t//Observe the pattern of taking the first and last element, second and second last element... and soo onn.. \n\t\t//would help you to minimize the maximum sum.\n while(start int:\n hs, ms = (int(x) for x in startTime.split(\":\"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(\":\"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96", "solution_js": "var numberOfRounds = function(loginTime, logoutTime) {\n const start = toMins(loginTime);\n const end = toMins(logoutTime);\n\n let roundStart = Math.ceil(start / 15);\n let roundEnd = Math.floor(end / 15);\n\n if (start < end) {\n return Math.max(0, roundEnd - roundStart);\n }\n else {\n roundEnd += 96;\n return roundEnd - roundStart;\n }\n\n function toMins(timeStr) {\n const [hh, mm] = timeStr.split(\":\");\n\n let totMins = 0;\n\n totMins += parseInt(hh) * 60;\n totMins += parseInt(mm);\n\n return totMins;\n }\n};", "solution_java": "class Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n String[] arr1 = loginTime.split(\":\");\n String[] arr2 = logoutTime.split(\":\");\n\n int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]);\n int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]);\n\n if(time1 > time2) time2 = time2 + 24*60;\n if(time1%15 != 0) time1 = time1 + 15-time1%15;\n\n return (time2 - time1)/15;\n }\n}", "solution_c": "class Solution {\npublic:\n int solve(string s)\n {\n int hour=stoi(s.substr(0,2));\n int min=stoi(s.substr(3,5));\n return hour*60+min;\n }\n int numberOfRounds(string loginTime, string logoutTime) {\n int st=solve(loginTime);\n int et=solve(logoutTime);\n int ans=0;\n if(st>et) et=et+1440;\n if(st%15!=0) st=st+(15-st%15);\n ans=(et-st)/15;\n return ans;\n }\n};" }, { "title": "Number of Closed Islands", "algo_input": "Given a 2D grid consists of 0s (land) and 1s (water).  An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.\n\nReturn the number of closed islands.\n\n \nExample 1:\n\n\n\nInput: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput: 2\nExplanation: \nIslands in gray are closed because they are completely surrounded by water (group of 1s).\n\nExample 2:\n\n\n\nInput: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput: 1\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1,1,1],\n  [1,0,0,0,0,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,1,0,1,0,1],\n  [1,0,1,1,1,0,1],\n  [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= grid.length, grid[0].length <= 100\n\t0 <= grid[i][j] <=1\n\n", "solution_py": "class Solution:\n '''主函数:计算封闭岛屿的数量'''\n def closedIsland(self, grid: List[List[int]]) -> int:\n result = 0\n m, n = len(grid), len(grid[0])\n self.direction = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n \n # 遍历 grid,处理边缘陆地\n for j in range(n):\n self.dfs(grid, 0, j)\n self.dfs(grid, m - 1, j)\n for i in range(m):\n self.dfs(grid, i, 0)\n self.dfs(grid, i, n - 1)\n \n # 剩下都是封闭岛屿,遍历找结果\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n result += 1\n self.dfs(grid, i, j)\n return result\n \n '''从 (i, j) 开始,将与之相邻的陆地都变成海水'''\n def dfs(self, grid, i, j):\n m, n = len(grid), len(grid[0])\n # 超出索引边界\n if i < 0 or j < 0 or i >= m or j >= n:\n return\n # 已经是海水了\n if grid[i][j] == 1:\n return\n # 变成海水\n grid[i][j] = 1\n for d in self.direction:\n x = i + d[0]\n y = j + d[1]\n self.dfs(grid, x, y)", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar closedIsland = function(grid) {\n let rows = grid.length;\n let cols = grid[0].length;\n let islandCount = 0; // Initial island count\n\n // For Quick Response\n if (rows <= 2 || cols <= 2) return islandCount;\n\n for (let i = 0; i <= rows - 1; i++) {\n for (let j = 0; j <= cols - 1; j++) {\n /*\n If land was found on the border, it can never be enclosed by water.\n So, mark the all the adjacent land across grid as visited.\n */\n if (grid[i][j] === 0 && (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)) {\n dfs(i, j);\n }\n }\n }\n\n // If land is found, increase the count and walk around land(adjacent indexes) to mark them as visited.\n for (let i = 1; i <= rows - 1; i++) {\n for (let j = 1; j <= cols - 1; j++) {\n if (grid[i][j] === 0) {\n islandCount++;\n dfs(i, j);\n }\n }\n }\n\n // To walk around land and mark it as visited\n function dfs(x, y) {\n if (x < 0 || y < 0 || x >= rows || y >= cols) return;\n if (grid[x][y] !== 0) return;\n\n grid[x][y] = 2;\n\n dfs(x + 1, y);\n dfs(x, y + 1);\n dfs(x - 1, y);\n dfs(x, y - 1);\n }\n\n return islandCount;\n};", "solution_java": "class Solution {\n boolean isClosed = true;\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int count = 0;\n\n for(int i=1; i grid.length-1 || j> grid[0].length-1 || grid[i][j] != 0) return;\n\n grid[i][j] = 1; // to mark as visited\n\n if(i == 0 || j == 0 || i == grid.length -1 || j == grid[0].length - 1) isClosed = false;\n\n dfs(grid, i, j+1);\n dfs(grid, i, j-1);\n dfs(grid, i+1, j);\n dfs(grid, i-1, j);\n }\n}", "solution_c": "class Solution {\npublic:\n bool isValid(int i,int j,vector>&grid) {\n if(i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 0) {\n return true;\n }\n return false;\n }\n void DFS(int i,int j,vector>&grid) {\n grid[i][j] = 1;\n if(isValid(i + 1,j,grid)) {\n DFS(i + 1,j,grid);\n }\n if(isValid(i - 1,j,grid)) {\n DFS(i - 1,j,grid);\n }\n if(isValid(i,j + 1,grid)) {\n DFS(i,j + 1,grid);\n }\n if(isValid(i,j - 1,grid)) {\n DFS(i,j - 1,grid);\n }\n }\n int closedIsland(vector>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n for(int i = 0; i < m; i++) {\n int j = 0;\n if(grid[i][j] == 0) {\n DFS(i,j,grid);\n }\n j = n - 1;\n if(grid[i][j] == 0) {\n DFS(i,j,grid);\n }\n }\n for(int j = 0; j < n; j++) {\n int i = 0;\n if(grid[i][j] == 0) {\n DFS(i,j,grid);\n }\n i = m - 1;\n if(grid[i][j] == 0) {\n DFS(i,j,grid);\n }\n }\n int cnt = 0;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if(grid[i][j] == 0) {\n cnt++;\n DFS(i,j,grid);\n }\n }\n }\n return cnt;\n }\n};" }, { "title": "Super Palindromes", "algo_input": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\n\nGiven two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].\n\n \nExample 1:\n\nInput: left = \"4\", right = \"1000\"\nOutput: 4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n\n\nExample 2:\n\nInput: left = \"1\", right = \"2\"\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= left.length, right.length <= 18\n\tleft and right consist of only digits.\n\tleft and right cannot have leading zeros.\n\tleft and right represent integers in the range [1, 1018 - 1].\n\tleft is less than or equal to right.\n\n", "solution_py": "class Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n min_num, max_num = int(left), int(right)\n count, limit = 0, 20001\n \n # odd pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[:-1][::-1]\n num_sqr = int(pal) ** 2\n\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n # even pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[::-1]\n num_sqr = int(pal) ** 2\n\n if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n return count ", "solution_js": "var superpalindromesInRange = function(left, right) {\n let ans = 9 >= left && 9 <= right ? 1 : 0\n\n const isPal = str => {\n for (let i = 0, j = str.length - 1; i < j; i++, j--)\n if (str.charAt(i) !== str.charAt(j)) return false\n return true\n }\n\n for (let dig = 1; dig < 10; dig++) {\n let isOdd = dig % 2 && dig !== 1,\n innerLen = (dig >> 1) - 1, innerLim = Math.max(1, 2 ** innerLen),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1\n for (let edge = 1; edge < 3; edge++) {\n let pal = new Uint8Array(dig)\n pal[0] = edge, pal[dig-1] = edge\n if (edge === 2) innerLim = 1, midLim = Math.min(midLim, 2)\n for (let inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n let innerStr = inner.toString(2).padStart(innerLen, '0')\n for (let i = 0; i < innerLen; i++)\n pal[1+i] = innerStr[i], pal[dig-2-i] = innerStr[i]\n }\n for (let mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = mid\n let palin = ~~pal.join(\"\"),\n square = BigInt(palin) * BigInt(palin)\n if (square > right) return ans\n if (square >= left && isPal(square.toString())) ans++\n }\n }\n }\n }\n return ans\n};", "solution_java": "class Solution {\n public int superpalindromesInRange(String left, String right) {\n int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n\n for (int dig = 1; dig < 10; dig++) {\n boolean isOdd = dig % 2 > 0 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n char[] pal = new char[dig];\n Arrays.fill(pal, '0');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) {\n innerLim = 1;\n midLim = Math.min(midLim, 2);\n }\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n String innerStr = Integer.toString(inner, 2);\n while (innerStr.length() < innerLen)\n innerStr = \"0\" + innerStr;\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr.charAt(i);\n pal[dig-2-i] = innerStr.charAt(i);\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n String palin = new String(pal);\n long square = Long.parseLong(palin) * Long.parseLong(palin);\n if (square > Long.parseLong(right)) return ans;\n if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n\n private boolean isPal(String str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str.charAt(i) != str.charAt(j)) return false;\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n int superpalindromesInRange(string lef, string rig) {\n long L = stol(lef) , R = stol(rig); \n int magic = 100000 , ans = 0;\n string s = \"\";\n\n for(int k = 1 ; k < magic ; k++){\n s = to_string(k);\n for(int i = s.length() - 2 ; i >= 0; i--){\n s += s.at(i);\n }\n long v = stol(s);\n v *= v;\n if(v > R) break;\n if(v >= L && isPalindrome(v)) ans++;\n }\n\n for(int k = 1 ; k < magic ; k++){\n s = to_string(k);\n for(int i = s.length() - 1 ; i >= 0 ; i--){\n s += s.at(i);\n }\n long v = stol(s);\n v *= v;\n if(v > R) break;\n if(v >= L && isPalindrome(v)) ans++;\n }\n return ans;\n }\n\n bool isPalindrome(long x){\n return x == reverse(x);\n }\n\n long reverse(long x ){\n long ans = 0;\n while(x > 0){\n ans = 10 * ans + x % 10;\n x /= 10;\n }\n return ans;\n } \n \n};" }, { "title": "String Compression II", "algo_input": "Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\". Thus the compressed string becomes \"a2bc3\".\n\nNotice that in this problem, we are not adding '1' after single characters.\n\nGiven a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.\n\nFind the minimum length of the run-length encoded version of s after deleting at most k characters.\n\n \nExample 1:\n\nInput: s = \"aaabcccd\", k = 2\nOutput: 4\nExplanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n\nExample 2:\n\nInput: s = \"aabbaa\", k = 2\nOutput: 2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n\n\nExample 3:\n\nInput: s = \"aaaaaaaaaaa\", k = 0\nOutput: 3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\t0 <= k <= s.length\n\ts contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n # Find min lenth of the code starting from group ind, if there are res_k characters to delete and\n # group ind needs to be increased by carry_over additional characters\n def FindMinLen(ind, res_k, carry_over=0):\n\n # If we already found the min length - just retrieve it (-1 means we did not calculate it)\n if carry_over == 0 and dynamic[ind][res_k] != -1:\n return dynamic[ind][res_k]\n\n # Number of character occurences that we need to code. Includes carry-over.\n cur_count = carry_over + frequency[ind]\n\n # Min code length if the group ind stays intact. The code accounts for single-character \"s0\" vs. \"s\" situation.\n min_len = 1 + min(len(str(cur_count)), cur_count - 1) + FindMinLen(ind+1,res_k)\n\n # Min length if we keep only 0, 1, 9, or 99 characters in the group - delete the rest, if feasible\n for leave_count, code_count in [(0,0), (1, 1), (9, 2), (99, 3)]:\n if cur_count > leave_count and res_k >= cur_count - leave_count:\n min_len = min(min_len, code_count + FindMinLen(ind + 1,res_k - (cur_count - leave_count)))\n\n # If we drop characters between this character group and next group, like drop \"a\" in \"bbbabb\"\n next_ind = chars.find(chars[ind], ind + 1)\n delete_count = sum(frequency[ind+1:next_ind])\n if next_ind > 0 and res_k >= delete_count:\n min_len = min(min_len, FindMinLen(next_ind, res_k - delete_count, carry_over = cur_count))\n\n # If there was no carry-over, store the result\n if carry_over == 0: dynamic[ind][res_k] = min_len\n return min_len\n\n # Two auxiliary lists - character groups (drop repeated) and number of characters in the group\n frequency, chars = [], \"\"\n for char in s:\n if len(frequency)==0 or char != chars[-1]:\n frequency.append(0)\n chars = chars + char\n frequency[-1] += 1\n\n # Table with the results. Number of character groups by number of available deletions.\n dynamic = [[-1] * (k + 1) for i in range(len(frequency))] + [[0]*(k + 1)]\n\n return FindMinLen(0, k)", "solution_js": "var getLengthOfOptimalCompression = function(s, k) {\n const memo = new Map()\n \n const backtrack = (i, lastChar, lastCharCount, k) => {\n if (k < 0) return Number.POSITIVE_INFINITY\n if (i >= s.length) return 0\n \n const memoKey = `${i}#${lastChar}#${lastCharCount}#${k}`\n if (memoKey in memo) return memo[memoKey]\n \n if (s[i] === lastChar) {\n const incrementor = [1, 9, 99].includes(lastCharCount) ? 1 : 0\n memo[memoKey] = incrementor + backtrack(i+1, lastChar, lastCharCount+1, k)\n } else {\n memo[memoKey] = Math.min(\n 1 + backtrack(i+1, s[i], 1, k), //keep char\n backtrack(i+1, lastChar, lastCharCount, k-1) //delete char\n )\n }\n return memo[memoKey]\n }\n return backtrack(0, '', 0, k)\n};", "solution_java": "class Solution {\n\t public int getLengthOfOptimalCompression(String s, int k) {\n Map memo = new HashMap<>();\n return recur(s, '\\u0000', 0, k, 0, memo);\n }\n\n private int recur(String s, char prevChar, int prevCharCount, int k, int index, Map memo) {\n\n if (index == s.length()) {\n return 0;\n }\n String key = prevChar + \", \" + prevCharCount + \", \" + k + \", \" + index;\n Integer keyVal = memo.get(key);\n\n if (keyVal != null) {\n return keyVal;\n }\n char ch = s.charAt(index);\n int count = 1;\n int nextIndex = index + 1;\n\n for (int i = index + 1; i < s.length(); i++) {\n\n if (s.charAt(i) == ch) {\n count++;\n nextIndex = i + 1;\n } else {\n nextIndex = i;\n break;\n }\n }\n int totalCount = count;\n int prevCountRepresentation = 0;\n //if prev char is equal to current char that means we have removed middle element\n //So we have to subtract the previous representation length and add the new encoding\n //representation length\n if (ch == prevChar) {\n totalCount += prevCharCount;\n prevCountRepresentation = getLength(prevCharCount);\n }\n\n int representaionLength = getLength(totalCount);\n int ans = representaionLength + recur(s, ch, totalCount, k, nextIndex, memo) - prevCountRepresentation;\n\n if (k > 0) {\n\n for (int i = 1; i <= k && i <= count; i++) {\n int currentCount = totalCount - i;\n int length = getLength(currentCount);\n //checking if we have to send current char and current char count or previous char\n //and previous char count\n int holder = length + recur(s, currentCount == 0 ? prevChar : ch,\n currentCount == 0 ? prevCharCount : currentCount, k - i, nextIndex, memo) -\n prevCountRepresentation;\n ans = Math.min(ans, holder);\n }\n }\n memo.put(key, ans);\n return ans;\n }\n //Since length for aaaaa will be a5(2) aaaaaaaaaa a10(3) etc.\n private int getLength(int n) {\n\n if (n == 0) {\n return 0;\n } else if (n == 1) {\n return 1;\n } else if (n < 10) {\n return 2;\n } else if (n < 100) {\n return 3;\n } else {\n return 4;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int dp[101][101];\n int dfs(string &s, int left, int K) {\n int k = K;\n if(s.size() - left <= k) return 0;\n if(dp[left][k] >= 0) return dp[left][k];\n int res = k ? dfs(s, left + 1, k - 1) : 10000, c = 1;\n for(int i = left + 1; i <= s.size(); ++i) {\n res = min(res, dfs(s, i, k) + 1 + (c >= 100 ? 3 : (c >= 10 ? 2 : (c > 1 ? 1 :0))));\n if(i == s.size()) break;\n if(s[i] == s[left]) ++c;\n else if(--k < 0) break;\n }\n return dp[left][K] = res;\n }\n \n int getLengthOfOptimalCompression(string s, int k) {\n memset(dp, -1, sizeof(dp));\n return dfs(s, 0, k);\n }\n};" }, { "title": "Minimum Number of Removals to Make Mountain Array", "algo_input": "You may recall that an array arr is a mountain array if and only if:\n\n\n\tarr.length >= 3\n\tThere exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:\n\t\n\t\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n\t\tarr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n\t\n\t\n\n\nGiven an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array.\n\n \nExample 1:\n\nInput: nums = [1,3,1]\nOutput: 0\nExplanation: The array itself is a mountain array so we do not need to remove any elements.\n\n\nExample 2:\n\nInput: nums = [2,1,1,5,6,2,3,1]\nOutput: 3\nExplanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 1000\n\t1 <= nums[i] <= 109\n\tIt is guaranteed that you can make a mountain array out of nums.\n\n", "solution_py": "class Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n n = len(nums)\n inc = [0] * n\n dec = [0] * n\n \n# Longest Increasing Subsequence\n for i in range(1,n):\n for j in range(0,i):\n if nums[i] > nums[j]:\n inc[i] = max(inc[i], inc[j] + 1)\n \n# Longest Decreasing Subsequence\n for i in range(n-2,-1,-1):\n for j in range(n-1,i,-1):\n if nums[i] > nums[j]:\n dec[i] = max(dec[i], dec[j] + 1)\n \n# Final calculation\n res = 0\n for i in range(0,n):\n if inc[i] > 0 and dec[i] > 0:\n res = max(res, inc[i] + dec[i])\n \n# Final conclusion \n return n - res - 1", "solution_js": "var minimumMountainRemovals = function(nums) {\n let n=nums.length\n let previous=Array.from({length:n},item=>1)\n let previous2=Array.from({length:n},item=>1)\n //calcultaing left and right side LIS in single iteration\n for (let i=0;inums[j] && previous[i]nums[j2] && previous2[i2]1 && previous2[i]>1){\n //at a specific index highest increasing will come from left LIS\n // and highest decreasing will come from right side LIS\n max=Math.max(max,previous[i]+previous2[i]-1)\n }\n }\n return n-max //we need to remove the rest from total\n};", "solution_java": "class Solution {\n public int minimumMountainRemovals(int[] nums) {\n\n int n = nums.length;\n int[] LIS = new int[n];\n int[] LDS = new int[n];\n\n Arrays.fill(LIS, 1);\n Arrays.fill(LDS, 1);\n // calculate the longest increase subsequence (LIS) for every index i\n for(int i=1 ; i < n ; i++)\n {\n for(int j = 0 ; j < i ; j++)\n {\n if(nums[i] > nums[j] && LIS[j]+1 > LIS[i])\n LIS[i] = LIS[j]+1;\n }\n }\n\n // calculate the longest decreasing subsequence(LDS) for every index i and keep track of the maximum of LIS+LDS\n int max = 0;\n for(int i=n-2 ; i >= 0 ; i--)\n {\n for(int j = n-1 ; j > i ; j--)\n {\n if(nums[i] > nums[j] && LDS[j]+1 > LDS[i])\n LDS[i] = LDS[j]+1;\n }\n\n if(LIS[i] > 1 && LDS[i] > 1)\n max = Math.max(LIS[i]+LDS[i]-1, max);\n }\n return n - max;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumMountainRemovals(vector& nums) {\n int n = nums.size();\n\n vector dp1(n,1), dp2(n,1);\n\n // LIS from front\n for(int i=0; i nums[j] && 1 + dp1[j] > dp1[i])\n {\n dp1[i] = 1 + dp1[j];\n }\n }\n }\n\n //LIS from back\n for(int i=n-1; i>=0; i--)\n {\n for(int j=n-1; j>i; j--)\n {\n if(nums[i] > nums[j] && dp2[j] + 1 > dp2[i]){\n dp2[i] = dp2[j] + 1;\n }\n }\n }\n\n int maxi = 1;\n for(int i=0; i 1 && dp2[i] > 1){\n maxi = max(maxi, dp1[i] + dp2[i] -1);\n }\n }\n return (n-maxi);\n }\n};" }, { "title": "Minimize Malware Spread II", "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.\n\nWe will remove exactly one node from initial, completely removing it and any connections from this node to any other node.\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\n \nExample 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\nExample 2:\nInput: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput: 1\nExample 3:\nInput: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\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": "from collections import defaultdict\nfrom collections import deque\nclass Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n n = len(graph)\n G = defaultdict(list)\n for v in range(n):\n for w in range(n):\n if graph[v][w]:\n G[v].append(w)\n \n affect = defaultdict(list)\n for s in initial:\n visited = set([v for v in initial if v != s])\n que = deque([s])\n while que:\n v = que.popleft()\n if v in visited: continue\n visited.add(v)\n affect[v].append(s)\n for w in G[v]:\n que.append(w)\n res = [0]*n\n for v in affect:\n if len(affect[v]) == 1:\n res[affect[v].pop()] += 1\n if not max(res): return min(initial)\n return res.index(max(res))", "solution_js": "var minMalwareSpread = function(graph, initial) {\nlet n = graph.length\nlet AdjList = new Map();\nlet listFromGraph = (mat) => {// convert adj matrix to adj list\n for(let i=0; i {// dfs helper, visit the graph assuming that node, given as 2nd parameter is deleted\n if(curr===node){\n return;\n }\n if(visitedSet.has(curr)){\n return;\n }\n visitedSet.add(curr);// size of visited shows how many nodes are visited/affected by the malware\n let neighbours = AdjList[curr];\n for(let i in neighbours){// visit all the neighbours\n dfs(neighbours[i],node);\n }\n}\nlet MinSpread = n;// min index of node with max reduction in malware\nlet SpreadDist = n;// number of nodes affected by malware if MinSpread was deleted\nfor(let i=0; i visitedSet.size){// to get max impact\n MinSpread = initial[i];\n SpreadDist = visitedSet.size;\n }\n visitedSet.clear();// clear visited set for next index to be deleted\n}\nreturn MinSpread;\n};", "solution_java": "class Solution {\n int[] parent;\n int[] size;\n \n public int find(int x){\n if(parent[x]==x) return x;\n int f = find(parent[x]);\n parent[x] = f;\n return f;\n }\n \n void merge(int x, int y){\n if(size[x]>size[y]){\n parent[y] = x;\n size[x] += size[y];\n }else{\n parent[x] =y;\n size[y] +=size[x];\n }\n }\n \n public int minMalwareSpread(int[][] graph, int[] initial) {\n int n =graph.length;\n \n parent = new int[n];\n size= new int[n];\n // putting initially infected nodes in hashset to ignore them while making graph\n HashSet hs = new HashSet<>();\n for(int a : initial){\n hs.add(a);\n }\n //initializing Parent for DSU\n for(int i=0;i> map = new HashMap<>();\n //We need to ensure increase the count whenever a parent is influenced by initial Nodes...because if it influenced by more than one infectious node then it would still remain infectious.\n int[] infected = new int[n]; \n for(int e: initial){\n map.put(e,new HashSet<>());\n for(int j=0;j par = map.get(e);\n int total =0;\n for(int p: par){\n if(infected[p]==1){ //add to total only if influenced by only one infectious node.\n total+=size[p];\n }\n }\n if(total>=max){\n if(max==total){\n ans = Math.min(ans,e);\n }else{\n ans =e;\n }\n max =total;\n }\n }\n \n if(ans!=-1) return ans;\n //for returining smallest element.\n Arrays.sort(initial);\n \n return initial[0];\n \n }\n}", "solution_c": "class Solution {\npublic:\n int minMalwareSpread(vector>& graph, vector& initial) {\n \n sort(initial.begin(), initial.end());\n int ans = -1, mn = INT_MAX, n = graph.size();\n \n vector> new_graph(n);\n for(int i = 0; i < n; i++)\n for(int j = 0; j < n; j++)\n if(graph[i][j])\n new_graph[i].push_back(j);\n \n for(auto &k : initial)\n {\n vector dsu(n, -1);\n for(int i = 0; i < n; i++)\n for(auto &j : new_graph[i])\n if(i != k && j != k)\n {\n int a = findParent(dsu, i), b = findParent(dsu, j);\n if(a != b)\n dsu[b] += dsu[a], dsu[a] = b;\n }\n \n vector infected(n, 0);\n for(auto &i : initial)\n if(i != k)\n infected[findParent(dsu, i)]++;\n \n int total_infected = 0;\n for(int i = 0; i < n; i++)\n if(infected[i])\n total_infected += abs(dsu[i]);\n \n if(total_infected < mn)\n mn = total_infected, ans = k;\n }\n \n return ans == -1 ? initial[0] : ans;\n }\n \n int findParent(vector &dsu, int i)\n {\n int a = i;\n while(dsu[i] >= 0)\n i = dsu[i];\n \n if(i != a)\n dsu[a] = i;\n \n return i;\n }\n};" }, { "title": "Surface Area of 3D Shapes", "algo_input": "You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).\n\nAfter placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.\n\nReturn the total surface area of the resulting shapes.\n\nNote: The bottom face of each shape counts toward its surface area.\n\n \nExample 1:\n\nInput: grid = [[1,2],[3,4]]\nOutput: 34\n\n\nExample 2:\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 32\n\n\nExample 3:\n\nInput: grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput: 46\n\n\n \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 <= n <= 50\n\t0 <= grid[i][j] <= 50\n\n", "solution_py": "class Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int: \n m, n = len(grid), len(grid[0])\n \n area = 0\n for r in range(m): \n for c in range(n):\n if grid[r][c] != 0:\n area += 2\n \n if r == 0 or r == m - 1:\n area += grid[r][c] if m != 1 else 2*grid[r][c]\n if r != m - 1: \n area += abs(grid[r][c] - grid[r+1][c])\n \n if c == 0 or c == n - 1:\n area += grid[r][c] if n != 1 else 2*grid[r][c]\n if c != n - 1: \n area += abs(grid[r][c] - grid[r][c+1]) \n \n return area", "solution_js": "var surfaceArea = function(grid) {\n let cube=0, overlap=0;\n for(let i=0; i0){overlap+=Math.min(grid[i][j], grid[i-1][j]);} // x-direction\n if(j>0){overlap+=Math.min(grid[i][j], grid[i][j-1]);} // y-direction\n\t\t\tif(grid[i][j]>1){overlap+=grid[i][j]-1}; // z-direction\n }\n }\n return cube*6-overlap*2;\n};", "solution_java": "class Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n int n = grid.length;\n for(int i=0; i>& grid) {\n int area = 0;\n \n for(int i = 0; i < grid.size(); i++) {\n for(int j = 0; j < grid[0].size(); j++) {\n\t\t\t\t//adding 4 sides\n area += grid[i][j]*4;\n\t\t\t\t\n\t\t\t\t//adding two because of there will only one top and one bottom if cube is placed upon each other\n if(grid[i][j] != 0)\n area+=2;\n\t\t\t\t\n\t\t\t\t//subtracting adjacent side area if any\n if(i-1 >= 0)\n area -= min(grid[i-1][j], grid[i][j]);\n if(i+1 < grid.size())\n area -= min(grid[i+1][j], grid[i][j]);\n if(j-1 >= 0)\n area -= min(grid[i][j-1], grid[i][j]);\n if(j+1 < grid.size())\n area -= min(grid[i][j+1], grid[i][j]);\n }\n }\n \n return area;\n }\n};" }, { "title": "Sum of Digits of String After Convert", "algo_input": "You are given a string s consisting of lowercase English letters, and an integer k.\n\nFirst, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.\n\nFor example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following operations:\n\n\n\tConvert: \"zbax\" ➝ \"(26)(2)(1)(24)\" ➝ \"262124\" ➝ 262124\n\tTransform #1: 262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17\n\tTransform #2: 17 ➝ 1 + 7 ➝ 8\n\n\nReturn the resulting integer after performing the operations described above.\n\n \nExample 1:\n\nInput: s = \"iiii\", k = 1\nOutput: 36\nExplanation: The operations are as follows:\n- Convert: \"iiii\" ➝ \"(9)(9)(9)(9)\" ➝ \"9999\" ➝ 9999\n- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36\nThus the resulting integer is 36.\n\n\nExample 2:\n\nInput: s = \"leetcode\", k = 2\nOutput: 6\nExplanation: The operations are as follows:\n- Convert: \"leetcode\" ➝ \"(12)(5)(5)(20)(3)(15)(4)(5)\" ➝ \"12552031545\" ➝ 12552031545\n- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33\n- Transform #2: 33 ➝ 3 + 3 ➝ 6\nThus the resulting integer is 6.\n\n\nExample 3:\n\nInput: s = \"zbax\", k = 2\nOutput: 8\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\t1 <= k <= 10\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def getLucky(self, s: str, k: int) -> int:\n nums = [str(ord(c) - ord('a') + 1) for c in s]\n for _ in range(k):\n nums = str(sum(int(digit) for num in nums for digit in num))\n return nums", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nvar getLucky = function(s, k) {\n function alphabetPosition(text) {\n var result = [];\n for (var i = 0; i < text.length; i++) {\n var code = text.toUpperCase().charCodeAt(i)\n if (code > 64 && code < 91) result.push(code - 64);\n }\n return result;\n }\n\n let str = alphabetPosition(s).join(\"\");\n let sum = 0;\n let newArr;\n\n while(k>0){\n newArr = str.split(\"\");\n sum = newArr.reduce((acc, e) => parseInt(acc)+parseInt(e));\n str = sum.toString();\n k--;\n }\n return sum\n\n};", "solution_java": "class Solution {\n public int getLucky(String s, int k) {\n \n StringBuilder sb=new StringBuilder();\n\n for(int i=0;i0 && result.length()>1)\n { \n sum=0;\n for(int i=0;i int:\n beg =0\n end =x\n while beg <=end:\n mid = (beg+end)//2\n sqr = mid*mid\n if sqr == x:\n return mid\n elif sqr < x:\n beg = mid+1\n else:\n end = mid-1\n return end\n ", "solution_js": "/**\n * @param {number} x\n * @return {number}\n */\nvar mySqrt = function(x) {\n const numx = x;\n let num = 0;\n\n while (num <= x) {\n const avg = Math.floor((num+x) / 2);\n if (avg * avg > numx) x = avg - 1;\n else num = avg + 1;\n }\n return x;\n};", "solution_java": "class Solution {\n public int mySqrt(int x) {\n long answer = 0;\n while (answer * answer <= x) {\n answer += 1;\n }\n return (int)answer - 1;\n }\n}", "solution_c": "class Solution {\npublic:\n int mySqrt(int x) {\n int s = 0 , e = x , mid;\n \n while(sval == root->val) return func(head->next,root->left) or func(head->next,root->right);\n return false;\n }\n bool isSubPath(ListNode* head, TreeNode* root) {\n if(!root) return false;\n if(func(head,root)) return true;\n return isSubPath(head,root->left) or isSubPath(head,root->right); \n }\n};" }, { "title": "Reverse Substrings Between Each Pair of Parentheses", "algo_input": "You are given a string s that consists of lower case English letters and brackets.\n\nReverse the strings in each pair of matching parentheses, starting from the innermost one.\n\nYour result should not contain any brackets.\n\n \nExample 1:\n\nInput: s = \"(abcd)\"\nOutput: \"dcba\"\n\n\nExample 2:\n\nInput: s = \"(u(love)i)\"\nOutput: \"iloveu\"\nExplanation: The substring \"love\" is reversed first, then the whole string is reversed.\n\n\nExample 3:\n\nInput: s = \"(ed(et(oc))el)\"\nOutput: \"leetcode\"\nExplanation: First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 2000\n\ts only contains lower case English characters and parentheses.\n\tIt is guaranteed that all parentheses are balanced.\n\n", "solution_py": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n stack = []\n ans = \"\"\n res = deque([])\n s = list(s)\n for i in s:\n if i==\")\":\n while stack[-1] != \"(\":\n res.append(stack.pop())\n stack.pop()\n while res:\n stack.append(res.popleft())\n else:\n stack.append(i)\n return \"\".join(stack)", "solution_js": "function reverse(s){\n return s.split(\"\").reverse().join(\"\");\n}\n\nfunction solve(s,index) { \n let ans = \"\"; \n let j = index;\n while(j stack = new Stack<>();\n\n int j = 0;\n while(j < s.length()){\n /*\n We need to keep on adding whatever comes\n as long as it is not a ')'.\n */\n if(s.charAt(j) != ')')\n stack.push(s.charAt(j)+\"\");\n\n /*\n Now that we have encountered an ')', its time\n to start popping from top of stack unless we find an opening\n parenthesis\n\n then we just need to reverse the string formed by popping\n and put it back on stack.\n\n Try dry running and it will all make sense\n */\n else{\n StringBuilder sb = new StringBuilder();\n while(!stack.isEmpty() && !stack.peek().equals(\"(\")){\n sb.append(stack.pop());\n }\n\n stack.pop();\n stack.push(sb.reverse().toString());\n }\n j++;\n }\n\n /*\n We have our result string in the stack now,\n we just need to pop it and return the reverse of it.\n */\n StringBuilder res = new StringBuilder();\n while(!stack.isEmpty())\n res.append(stack.pop());\n\n return res.reverse().toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string reverseParentheses(string s) {\n stack st;\n for(int i=0;i= len(self.arr):\n self.is_has_next = False \n return val \n \n def hasNext(self):\n return self.is_has_next \n \n def peek(self):\n return self.arr[self._next]", "solution_js": "var PeekingIterator = function(iterator) {\n this.iterator = iterator\n this.curr = iterator.next()\n\n};\n\nPeekingIterator.prototype.peek = function() {\n return this.curr\n};\n\nPeekingIterator.prototype.next = function() {\n let temp = this.curr\n this.curr = this.iterator.next()\n return temp\n};\n\nPeekingIterator.prototype.hasNext = function() {\n return this.curr > 0 // the input iterator return -100000000 when next() after it run out of members, instead of return undefined.\n};", "solution_java": "// Java Iterator interface reference:\n// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator {\n Queue q;\n\tpublic PeekingIterator(Iterator iterator) {\n\t // initialize any member here.\n\t q= new LinkedList<>();\n while(iterator.hasNext())\n q.add(iterator.next()); \n\t}\n\t\n // Returns the next element in the iteration without advancing the iterator.\n\tpublic Integer peek() {\n return q.peek();\n\t}\n\t\n\t// hasNext() and next() should behave the same as in the Iterator interface.\n\t// Override them if needed.\n\t@Override\n\tpublic Integer next() {\n\t return q.remove();\n\t}\n\t\n\t@Override\n\tpublic boolean hasNext() {\n\t return q.size()!=0;\n\t}\n}", "solution_c": "/*\n * Below is the interface for Iterator, which is already defined for you.\n * **DO NOT** modify the interface for Iterator.\n *\n * class Iterator {\n * struct Data;\n * Data* data;\n * public:\n * Iterator(const vector& nums);\n * Iterator(const Iterator& iter);\n *\n * // Returns the next element in the iteration.\n * int next();\n *\n * // Returns true if the iteration has more elements.\n * bool hasNext() const;\n * };\n */\n\nclass PeekingIterator : public Iterator {\npublic:\n int _nextVal;\n bool _hasNext;\n PeekingIterator(const vector& nums) : Iterator(nums) {\n // Initialize any member here.\n // **DO NOT** save a copy of nums and manipulate it directly.\n // You should only use the Iterator interface methods.\n _nextVal = 0;\n _hasNext = Iterator::hasNext();\n if (_hasNext)\n _nextVal = Iterator::next();\n }\n\n // Returns the next element in the iteration without advancing the iterator.\n int peek() {\n return (_nextVal);\n }\n\n // hasNext() and next() should behave the same as in the Iterator interface.\n // Override them if needed.\n int next() {\n int tmp = _nextVal;\n\n _hasNext = Iterator::hasNext();\n if (_hasNext)\n _nextVal = Iterator::next();\n return (tmp);\n }\n\n bool hasNext() const {\n return (_hasNext);\n }\n};" }, { "title": "Count Number of Ways to Place Houses", "algo_input": "There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.\n\nReturn the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.\n\nNote that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street.\n\n \nExample 1:\n\nInput: n = 1\nOutput: 4\nExplanation: \nPossible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.\n\n\nExample 2:\n\nInput: n = 2\nOutput: 9\nExplanation: The 9 possible arrangements are shown in the diagram above.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\n", "solution_py": "class Solution:\n def countHousePlacements(self, n: int) -> int:\n \n \n @lru_cache(None)\n def rec(i, k):\n \n # i is the index of the house \n # k is the state of last house, 1 if there was a house on the last index else 0\n \n if i>=n:\n return 1\n \n elif k==0:\n return rec(i+1,1) + rec(i+1,0)\n \n else:\n return rec(i+1,0)\n \n \n \n #l1 are the combinations possible in lane 1, the final answer will be the square \n\t\t#of of l1 as for every combination of l1 there will be \"l1\" combinations in lane2.\n \n l1 = rec(1,0) + rec(1,1)\n \n \n mod = 10**9 +7\n return pow(l1, 2, mod) #use this when there is mod involved along with power \n ", "solution_js": "const mod = (10 ** 9) + 7\nvar countHousePlacements = function(n) {\n let prev2 = 1\n let prev1 = 1\n let ways = 2\n \n for ( let i = 2; i <= n; i++ ) {\n prev2 = prev1\n prev1 = ways\n ways = ( prev1 + prev2 ) % mod\n }\n \n return (ways ** 2) % mod\n}", "solution_java": "class Solution {\n int mod = (int)1e9+7;\n public int countHousePlacements(int n) {\n \n if(n == 1)\n return 4;\n if(n == 2)\n return 9;\n long a = 2;\n long b = 3;\n if(n==1)\n return (int)(a%mod);\n if(n==2)\n return (int)(b%mod);\n long c=0;\n for(int i=3;i<=n;i++)\n {\n c = (a+b)%mod;\n a=b%mod;\n b=c%mod;\n }\n \n return (int)((c*c)%mod);\n }\n}", "solution_c": "class Solution {\npublic:\n typedef long long ll;\n ll mod = 1e9+7;\n int countHousePlacements(int n) {\n ll house=1, space=1;\n ll total = house+space;\n for(int i=2;i<=n;i++){\n\t house = space;\n\t space = total;\n\t total = (house+space)%mod;\n\t }\n\t return (total*total)%mod;\n }\n};" }, { "title": "Escape the Spreading Fire", "algo_input": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:\n\n\n\t0 represents grass,\n\t1 represents fire,\n\t2 represents a wall that you and fire cannot pass through.\n\n\nYou are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.\n\nReturn the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109.\n\nNote that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.\n\nA cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n\n \nExample 1:\n\nInput: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput: 3\nExplanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.\n\nExample 2:\n\nInput: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput: -1\nExplanation: The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.\n\n\nExample 3:\n\nInput: grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput: 1000000000\nExplanation: The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109 is returned.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t2 <= m, n <= 300\n\t4 <= m * n <= 2 * 104\n\tgrid[i][j] is either 0, 1, or 2.\n\tgrid[0][0] == grid[m - 1][n - 1] == 0\n\n", "solution_py": "class Solution(object):\n def maximumMinutes(self, A):\n m, n = len(A), len(A[0])\n inf = 10 ** 10\n d = [[0,1],[1,0],[0,-1],[-1,0]]\n fires = [[i, j, 0] for i in range(m) for j in range(n) if A[i][j] == 1]\n A = [[inf if a < 2 else -1 for a in r] for r in A]\n\n def bfs(queue, seen):\n for i, j, t in queue:\n if seen[i][j] < inf: continue\n seen[i][j] = t\n for di,dj in d:\n x, y = i + di, j + dj\n if 0 <= x < m and 0 <= y < n and seen[x][y] >= inf and t + 1 < A[x][y]:\n queue.append([x, y, t + 1])\n \n def die(t):\n seen = [[inf + 10] * n for i in range(m)]\n bfs([[0, 0, t]], seen)\n return seen[-1][-1] > A[-1][-1]\n\n bfs(fires, A)\n A[-1][-1] += 1\n return bisect_left(range(10**9 + 1), True, key=die) - 1", "solution_js": "var maximumMinutes = function(grid) {\n let fireSpread = getFireSpreadTime(grid);\n let low = 0, high = 10 ** 9;\n while (low < high) {\n let mid = Math.ceil((low + high) / 2);\n if (canReachSafehouse(grid, fireSpread, mid)) low = mid;\n else high = mid - 1;\n }\n return canReachSafehouse(grid, fireSpread, low) ? low : -1;\n};\n\nfunction canReachSafehouse(originalGrid, fireSpread, timeToWait) {\n const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n let grid = originalGrid.map((row) => [...row]);\n let m = grid.length, n = grid[0].length;\n let queue = [[0, 0]], time = timeToWait;\n while (queue.length) {\n for (let i = queue.length; i > 0; i--) {\n let [row, col] = queue.shift();\n if (row === m - 1 && col === n - 1) {\n return true;\n }\n for (let [x, y] of directions) {\n let newX = row + x, newY = col + y;\n if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass\n let isTarget = newX === m - 1 && newY === n - 1;\n if ((isTarget && time + 1 <= fireSpread[newX][newY]) || time + 1 < fireSpread[newX][newY]) { // only visit if fire will not spread to new cell at the next minute\n grid[newX][newY] = 1;\n queue.push([newX, newY]);\n }\n }\n }\n time++;\n }\n return false;\n}\n\nfunction getFireSpreadTime(originalGrid) {\n const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];\n let grid = originalGrid.map((row) => [...row]);\n let m = grid.length, n = grid[0].length;\n let queue = [];\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n queue.push([i, j]);\n }\n }\n }\n \n let time = 0, fireSpread = Array(m).fill(0).map(() => Array(n).fill(Infinity));\n while (queue.length) {\n for (let i = queue.length; i > 0; i--) {\n let [row, col] = queue.shift();\n fireSpread[row][col] = time;\n for (let [x, y] of directions) {\n let newX = row + x, newY = col + y;\n if (newX < 0 || newX >= m || newY < 0 || newY >= n || grid[newX][newY] !== 0) continue; // out of bounds or cell is not grass\n grid[newX][newY] = 1;\n queue.push([newX, newY]);\n }\n }\n time++;\n }\n return fireSpread;\n}", "solution_java": "import java.util.Arrays;\nimport java.util.LinkedList;\nimport java.util.Queue;\n\nclass Solution {\n\n public boolean ok(int[][] grid, int[][] dist, int wait_time) {\n int n = grid.length;\n int m = grid[0].length;\n\n Queue> Q = new LinkedList<>();\n Q.add(new Pair<>(0, 0, wait_time));\n\n int[][] visited = new int[n][m];\n visited[0][0] = 1;\n\n while (!Q.isEmpty()) {\n Pair at = Q.poll();\n int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n\n for (int[] to : moves) {\n int ii = at.first + to[0];\n int jj = at.second + to[1];\n if (!inBounds(ii, jj, n, m) || visited[ii][jj] == 1 || grid[ii][jj] == 2) continue;\n if (ii == n - 1 && jj == m - 1 && dist[ii][jj] >= at.third + 1) return true;\n if (dist[ii][jj] <= at.third + 1) continue;\n Q.add(new Pair<>(ii, jj, 1 + at.third));\n visited[ii][jj] = 1;\n }\n }\n return false;\n }\n\n public boolean inBounds(int i, int j, int n, int m) {\n return (0 <= i && i < n && 0 <= j && j < m);\n }\n\n public int maximumMinutes(int[][] grid) {\n int n = grid.length;\n int m = grid[0].length;\n\n int[][] dist = new int[n][m];\n\n for (int[] r : dist) Arrays.fill(r, Integer.MAX_VALUE);\n\n Queue> Q = new LinkedList<>();\n\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1) {\n Q.add(new Pair<>(i, j, 0));\n dist[i][j] = 0;\n }\n }\n }\n\n while (!Q.isEmpty()) {\n Pair at = Q.poll();\n int[][] moves = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n for (int[] to : moves) {\n int ii = at.first + to[0];\n int jj = at.second + to[1];\n if (!inBounds(ii, jj, n, m) || grid[ii][jj] == 2 || dist[ii][jj] <= at.third + 1) continue;\n dist[ii][jj] = 1 + at.third;\n Q.add(new Pair<>(ii, jj, 1 + at.third));\n }\n }\n\n int left = 0;\n int right = 1_000_000_000;\n\n int ans = -1;\n\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (ok(grid, dist, mid)) {\n ans = mid;\n left = mid + 1;\n } else right = mid - 1;\n }\n\n return ans;\n }\n\n static class Pair {\n T first;\n K second;\n L third;\n\n public Pair(T first, K second, L third) {\n this.first = first;\n this.second = second;\n this.third = third;\n }\n }\n\n}", "solution_c": "class Solution {\npublic:\n int maximumMinutes(vector>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n vector> firetime(m, vector(n, INT_MAX));\n queue> q;\n // push fire positions into queue, and set the time as 0\n for(int i=0; i xy;\n int x,y;\n // use BFS to find fire spread time\n while(!q.empty()){\n int points = q.size();\n time++;\n for(int i=0; i=0 && grid[x-1][y]==0 && firetime[x-1][y]==INT_MAX){\n q.push(make_pair(x-1, y));\n firetime[x-1][y] = time;\n }\n if(x+1=0 && grid[x][y-1]==0 && firetime[x][y-1]==INT_MAX){\n q.push(make_pair(x, y-1));\n firetime[x][y-1] = time;\n }\n if(y+1> peopletime(m, vector(n, INT_MAX));\n time = 0;\n // push the initial position of the top left cell into the queue\n // and set the time as 0\n q.push(make_pair(0, 0));\n peopletime[0][0] = 0;\n // use BFS to find the traversal time\n while(!q.empty()){\n int points = q.size();\n time++;\n for(int i=0; i=0 && grid[x-1][y]==0 && peopletime[x-1][y]==INT_MAX && firetime[x-1][y]>time){\n q.push(make_pair(x-1, y));\n peopletime[x-1][y] = time;\n }\n if(x+1time){\n q.push(make_pair(x+1, y));\n peopletime[x+1][y] = time;\n }\n if(y-1>=0 && grid[x][y-1]==0 && peopletime[x][y-1]==INT_MAX && firetime[x][y-1]>time){\n q.push(make_pair(x, y-1));\n peopletime[x][y-1] = time;\n }\n if(y+1time){\n q.push(make_pair(x, y+1));\n peopletime[x][y+1] = time;\n }\n if(((x==m-2 && y==n-1) || (x==m-1 && y==n-2))&&(firetime[m-1][n-1]<=time)){\n q.push(make_pair(m-1, n-1));\n peopletime[m-1][n-1] = time;\n }\n }\n }\n // if you cannot reach the safehouse or fire reaches the safehouse first,\n // return -1\n if(peopletime[m-1][n-1]==INT_MAX || firetime[m-1][n-1]1 && n>1){\n if(peopletime[m-2][n-1]!=INT_MAX && peopletime[m-1][n-2]!=INT_MAX && ((firetime[m-2][n-1]-peopletime[m-2][n-1])>diff || (firetime[m-1][n-2]-peopletime[m-1][n-2]>diff))){\n return diff;\n }\n }\n return diff-1;\n }\n};" }, { "title": "Pyramid Transition Matrix", "algo_input": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.\n\nTo make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.\n\n\n\tFor example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom.\n\n\nYou start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.\n\nGiven bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.\n\n \nExample 1:\n\nInput: bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput: true\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.\n\n\nExample 2:\n\nInput: bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput: false\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.\n\n\n \nConstraints:\n\n\n\t2 <= bottom.length <= 6\n\t0 <= allowed.length <= 216\n\tallowed[i].length == 3\n\tThe letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.\n\tAll the values of allowed are unique.\n\n", "solution_py": "class Solution(object):\n def pyramidTransition(self, bottom, allowed):\n \"\"\"\n :type bottom: str\n :type allowed: List[str]\n :rtype: bool \n \"\"\"\n dic = defaultdict(list)\n for i in allowed:\n dic[(i[0], i[1])].append(i[2])\n \n res = []\n \n def dfs(arr, nxt):\n #base case second floor and check top exists\n if len(arr) == 2 and dic[(arr[0], arr[1])]:\n return True\n \n #go to the next row now\n if len(arr) == len(nxt) + 1:\n return dfs(nxt, [])\n\n #keep iterating the same row\n if dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n for val in dic[(arr[len(nxt)], arr[len(nxt) + 1])]:\n if dfs(arr, nxt + [val]):\n return True\n return False\n \n return dfs(bottom, [])", "solution_js": "var pyramidTransition = function(bottom, allowed) {\n const set = new Set(allowed);\n const memo = new Map();\n const chars = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"];\n \n return topDown(bottom, bottom.length - 1);\n \n function topDown(prev, row) {\n const key = `${prev}#${row}`;\n \n if (row === 0) return true;\n if (memo.has(key)) return memo.get(key);\n\n let pats = new Set();\n pats.add(\"\");\n\n for (let i = 0; i < row; i++) {\n const tmp = new Set();\n\n const leftBot = prev.charAt(i);\n const rightBot = prev.charAt(i + 1);\n\n for (const char of chars) {\n const triadStr = leftBot + rightBot + char;\n\n if (set.has(triadStr)) {\n for (const pat of pats) {\n tmp.add(pat + char);\n } \n }\n }\n \n pats = tmp;\n }\n \n for (const pat of pats) {\n if (topDown(pat, row - 1)) return true;\n }\n \n memo.set(key, false);\n return false;\n }\n};", "solution_java": "class Solution {\n HashMap> map = new HashMap<>();\n HashMap dp = new HashMap<>();\n \n public boolean pyramidTransition(String bottom, List allowed) {\n for(String s:allowed){\n String sub = s.substring(0,2);\n \n char c = s.charAt(2);\n \n if(!map.containsKey(sub))\n map.put(sub, new ArrayList<>());\n \n map.get(sub).add(c);\n }\n \n return dfs(bottom, \"\", 0);\n }\n \n boolean dfs(String currBottom, String newBottom, int index){\n \n if(currBottom.length()==1)\n return true;\n if(index+1>=currBottom.length())\n return false;\n \n String sub = currBottom.substring(index,index+2);\n \n String state = currBottom+\" \"+newBottom+\" \"+index;\n \n if(dp.containsKey(state))\n return dp.get(state);\n \n if(map.containsKey(sub)){\n List letters = map.get(sub);\n \n for(char c:letters){\n if(index==currBottom.length()-2){\n if(dfs(newBottom+c, \"\", 0))\n {\n dp.put(state, true);\n return true;\n }\n }\n else if(dfs(currBottom, newBottom+c, index+1))\n {\n dp.put(state, true);\n return true;\n }\n }\n }\n \n dp.put(state, false);\n return false;\n }\n}", "solution_c": "class Solution {\n unordered_map > m;\npublic:\n bool dfs(string bot,int i,string tem){\n if(bot.size()==1) return true;\n if(i==bot.size()-1) {\n string st;\n return dfs(tem,0,st);\n }\n for(auto v:m[bot.substr(i,2)]){\n tem.push_back(v);\n if(dfs(bot,i+1,tem)){\n return true;\n }\n tem.pop_back();\n }\n return false;\n }\n bool pyramidTransition(string bottom, vector& allowed) {\n for(auto a:allowed){\n m[a.substr(0,2)].push_back(a[2]);\n }\n string te;\n return dfs(bottom,0,te);\n }\n};" }, { "title": "Elimination Game", "algo_input": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:\n\n\n\tStarting from left to right, remove the first number and every other number afterward until you reach the end of the list.\n\tRepeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.\n\tKeep repeating the steps again, alternating left to right and right to left, until a single number remains.\n\n\nGiven the integer n, return the last number that remains in arr.\n\n \nExample 1:\n\nInput: n = 9\nOutput: 6\nExplanation:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr = [2, 4, 6, 8]\narr = [2, 6]\narr = [6]\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\n", "solution_py": "class Solution:\n def lastRemaining(self, n: int) -> int:\n beg = 1\n len = n\n d = 1\n fromleft = True\n\n while len > 1:\n if(fromleft or len%2 == 1):\n beg += d\n d <<= 1\n len >>= 1\n fromleft = not fromleft\n \n return beg", "solution_js": "var lastRemaining = function(n) {\n let sum=1; let num=1; let bool=true;\n while(n>1){ \n if(bool){sum+=num; bool=false;}\n else{if(n%2){sum+=num;} bool=true;}\n num*=2; n=Math.floor(n/2);\n }\n return sum;\n}; ", "solution_java": "class Solution {\n public int lastRemaining(int n) {\n int head = 1;\n int remain = n;\n boolean left = true;\n int step =1;\n \n while(remain > 1){\n if(left || remain%2==1){\n head = head + step;\n }\n remain /= 2;\n step *= 2;\n left = !left;\n }\n return head;\n }\n}", "solution_c": "class Solution {\npublic:\n int lastRemaining(int n) {\n bool left=true;\n int head=1,step=1;//step is the difference between adjacent elements.\n while(n>1){\n if(left || (n&1)){//(n&1)->odd\n head=head+step;\n }\n step=step*2;\n n=n/2;\n left=!left;\n }\n return head;\n }\n};" }, { "title": "Middle of the Linked List", "algo_input": "Given the head of a singly linked list, return the middle node of the linked list.\n\nIf there are two middle nodes, return the second middle node.\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5]\nOutput: [3,4,5]\nExplanation: The middle node of the list is node 3.\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5,6]\nOutput: [4,5,6]\nExplanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [1, 100].\n\t1 <= Node.val <= 100\n\n", "solution_py": "class Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # basically we create two pointers\n # move one pointer extra fast\n # another pointer would be slow\n # when fast reaches end slow would be in mid\n slow = fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow", "solution_js": "var middleNode = function(head) {\n var runner1 = head\n var runner2 = head?.next\n while(runner1 && runner2) {\n runner1 = runner1?.next\n runner2 = (runner2?.next)?.next\n }\n return runner1\n};", "solution_java": "class Solution {\n public ListNode middleNode(ListNode head) {\n \n ListNode temp = head;\n int size = 0;\n while(temp!=null){\n size++;\n temp = temp.next;\n }\n int mid = size/2;\n temp = head;\n for(int i=0;inext!=NULL){\n slow=slow->next;\n fast=fast->next->next;\n }\n return slow;\n }\n};" }, { "title": "Design a Food Rating System", "algo_input": "Design a food rating system that can do the following:\n\n\n\tModify the rating of a food item listed in the system.\n\tReturn the highest-rated food item for a type of cuisine in the system.\n\n\nImplement the FoodRatings class:\n\n\n\tFoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.\n\n\t\n\t\tfoods[i] is the name of the ith food,\n\t\tcuisines[i] is the type of cuisine of the ith food, and\n\t\tratings[i] is the initial rating of the ith food.\n\t\n\t\n\tvoid changeRating(String food, int newRating) Changes the rating of the food item with the name food.\n\tString highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.\n\n\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n\n \nExample 1:\n\nInput\n[\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n[[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]\nOutput\n[null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]\n\nExplanation\nFoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated(\"korean\"); // return \"kimchi\"\n // \"kimchi\" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // \"ramen\" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"sushi\"\n // \"sushi\" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\nfoodRatings.highestRated(\"japanese\"); // return \"ramen\"\n // Both \"sushi\" and \"ramen\" have a rating of 16.\n // However, \"ramen\" is lexicographically smaller than \"sushi\".\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 104\n\tn == foods.length == cuisines.length == ratings.length\n\t1 <= foods[i].length, cuisines[i].length <= 10\n\tfoods[i], cuisines[i] consist of lowercase English letters.\n\t1 <= ratings[i] <= 108\n\tAll the strings in foods are distinct.\n\tfood will be the name of a food item in the system across all calls to changeRating.\n\tcuisine will be a type of cuisine of at least one food item in the system across all calls to highestRated.\n\tAt most 2 * 104 calls in total will be made to changeRating and highestRated.\n\n", "solution_py": "from heapq import heapify, heappop, heappush\n\nclass RatedFood:\n def __init__(self, rating, food):\n self.rating = rating\n self.food = food\n \n def __lt__(self, other):\n if other.rating == self.rating:\n return self.food < other.food\n return self.rating < other.rating\n\nclass FoodRatings:\n def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n self.cuis_to_score_heap = defaultdict(list)\n self.food_to_latest_ratings = defaultdict(int)\n self.food_to_cuis = defaultdict(str)\n \n for food, cuis, rating in zip(foods, cuisines, ratings):\n self.food_to_cuis[food] = cuis\n self.food_to_latest_ratings[food] = rating\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food))\n \n \n\n def changeRating(self, food: str, newRating: int) -> None:\n self.food_to_latest_ratings[food] = newRating\n cuis = self.food_to_cuis[food]\n heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food))\n \n\n def highestRated(self, cuisine: str) -> str:\n while True:\n ratedFood = heappop(self.cuis_to_score_heap[cuisine])\n if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating):\n\t\t\t\n\t\t\t\t# because the food item is still valid, we put it back into the heap\n heappush(self.cuis_to_score_heap[cuisine], ratedFood)\n\t\t\t\t\n return ratedFood.food", "solution_js": "var FoodRatings = function(foods, cuisines, ratings) {\n this.heaps = {}, this.foods = {};\n let n = foods.length;\n for (let i = 0; i < n; i++) {\n let food = foods[i], cuisine = cuisines[i], rating = ratings[i];\n if (!this.heaps[cuisine]) this.heaps[cuisine] = new PriorityQueue((a, b) => { // [food, rating]\n return a[1] === b[1] ? a[0].localeCompare(b[0]) : b[1] - a[1];\n })\n this.heaps[cuisine].add([food, rating]);\n this.foods[food] = { cuisine, rating };\n }\n};\n\nFoodRatings.prototype.changeRating = function(food, newRating) {\n this.foods[food].rating = newRating;\n let { cuisine } = this.foods[food];\n this.heaps[cuisine].add([food, newRating]);\n};\n\nFoodRatings.prototype.highestRated = function(cuisine) {\n let heap = this.heaps[cuisine];\n while (this.foods[heap.top()[0]].rating !== heap.top()[1]) {\n heap.remove();\n }\n return heap.top()[0];\n};\n\nclass PriorityQueue {\n constructor(comparator = ((a, b) => a - b)) {\n this.values = [];\n this.comparator = comparator;\n this.size = 0;\n }\n add(val) {\n this.size++;\n this.values.push(val);\n let idx = this.size - 1, parentIdx = Math.floor((idx - 1) / 2);\n while (parentIdx >= 0 && this.comparator(this.values[parentIdx], this.values[idx]) > 0) {\n [this.values[parentIdx], this.values[idx]] = [this.values[idx], this.values[parentIdx]];\n idx = parentIdx;\n parentIdx = Math.floor((idx - 1) / 2);\n }\n }\n remove() {\n if (this.size === 0) return -1;\n this.size--;\n if (this.size === 0) return this.values.pop();\n let removedVal = this.values[0];\n this.values[0] = this.values.pop();\n let idx = 0;\n while (idx < this.size && idx < Math.floor(this.size / 2)) {\n let leftIdx = idx * 2 + 1, rightIdx = idx * 2 + 2;\n if (rightIdx === this.size) {\n if (this.comparator(this.values[leftIdx], this.values[idx]) > 0) break;\n [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]];\n idx = leftIdx;\n } else if (this.comparator(this.values[leftIdx], this.values[idx]) < 0 || this.comparator(this.values[rightIdx], this.values[idx]) < 0) {\n if (this.comparator(this.values[leftIdx], this.values[rightIdx]) <= 0) {\n [this.values[leftIdx], this.values[idx]] = [this.values[idx], this.values[leftIdx]];\n idx = leftIdx;\n } else {\n [this.values[rightIdx], this.values[idx]] = [this.values[idx], this.values[rightIdx]];\n idx = rightIdx;\n }\n } else {\n break;\n }\n }\n return removedVal;\n }\n top() {\n return this.values[0];\n }\n isEmpty() {\n return this.size === 0;\n }\n}", "solution_java": "class FoodRatings {\n HashMap> cuiToFood = new HashMap();\n HashMap foodToRat = new HashMap();\n HashMap foodToCui = new HashMap();\n public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {\n for(int i = 0; i < foods.length; i++){\n TreeSet foodOfThisCuisine = cuiToFood.getOrDefault(cuisines[i], new TreeSet ((a,b)->\n foodToRat.get(a).equals(foodToRat.get(b)) ? a.compareTo(b) : foodToRat.get(b)-foodToRat.get(a)));\n\t\t\t\n\t\t\t// Both comparators are equal\n\t\t\t/* new Comparator(){\n @Override\n public int compare(String a, String b){\n int aRat = foodToRat.get(a);\n int bRat = foodToRat.get(b);\n \n if(aRat != bRat) return bRat - aRat; // largest rating first\n for(int i = 0; i < Math.min(a.length(), b.length()); i++){\n if(a.charAt(i) != b.charAt(i)) return a.charAt(i) - b.charAt(i);\n }\n return a.length() - b.length();\n }\n })\n\t\t\t*/\n \n foodToRat.put(foods[i], ratings[i]);\n foodOfThisCuisine.add(foods[i]);\n foodToCui.put(foods[i], cuisines[i]); \n \n cuiToFood.put(cuisines[i], foodOfThisCuisine);\n }\n }\n \n // CompareTo() is used to compare whether 2 strings are equal in hashSet! So remove, change value of key in HashMap, then insert again\n public void changeRating(String food, int newRating) {\n String cui = foodToCui.get(food);\n TreeSet foodOfThisCui = cuiToFood.get(cui);\n foodOfThisCui.remove(food);\n foodToRat.put(food, newRating);\n \n foodOfThisCui.add(food);\n cuiToFood.put(cui, foodOfThisCui);\n }\n \n public String highestRated(String cuisine) {\n return cuiToFood.get(cuisine).first();\n }\n}", "solution_c": "class FoodRatings {\npublic:\n unordered_map>> cuisine_ratings;\n unordered_map food_cuisine;\n unordered_map food_rating;\n FoodRatings(vector& foods, vector& cuisines, vector& ratings) {\n for (int i = 0; i < foods.size(); ++i) {\n cuisine_ratings[cuisines[i]].insert({ -ratings[i], foods[i] });\n food_cuisine[foods[i]] = cuisines[i];\n food_rating[foods[i]] = ratings[i];\n }\n }\n void changeRating(string food, int newRating) {\n auto &cuisine = food_cuisine.find(food)->second;\n cuisine_ratings[cuisine].erase({ -food_rating[food], food });\n cuisine_ratings[cuisine].insert({ -newRating, food });\n food_rating[food] = newRating;\n }\n string highestRated(string cuisine) {\n return begin(cuisine_ratings[cuisine])->second;\n }\n};" }, { "title": "Champagne Tower", "algo_input": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.  Each glass holds one cup of champagne.\n\nThen, some champagne is poured into the first glass at the top.  When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.  When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.  (A glass at the bottom row has its excess champagne fall on the floor.)\n\nFor example, after one cup of champagne is poured, the top most glass is full.  After two cups of champagne are poured, the two glasses on the second row are half full.  After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.  After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\n\n\n\nNow after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)\n\n \nExample 1:\n\nInput: poured = 1, query_row = 1, query_glass = 1\nOutput: 0.00000\nExplanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\n\n\nExample 2:\n\nInput: poured = 2, query_row = 1, query_glass = 1\nOutput: 0.50000\nExplanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\n\n\nExample 3:\n\nInput: poured = 100000009, query_row = 33, query_glass = 17\nOutput: 1.00000\n\n\n \nConstraints:\n\n\n\t0 <= poured <= 109\n\t0 <= query_glass <= query_row < 100\n", "solution_py": "class Solution:\n def champagneTower(self, poured: int, r: int, c: int) -> float:\n quantity=defaultdict(int)\n quantity[(0,0)]=poured\n for i in range(r+1):\n flag=False\n for j in range(i+1):\n prev_flow=quantity[(i,j)]-1\n if prev_flow<=0:\n continue\n flag=True\n quantity[(i,j)]=1\n quantity[(i+1,j)]+=prev_flow/2\n quantity[(i+1,j+1)]+=prev_flow/2\n if not flag: break\n return quantity[(r,c)]", "solution_js": "var champagneTower = function(poured, query_row, query_glass) {\n \n let water = [poured];\n let hasOverflow = true;\n let row = 0;\n\n while(true){\n \n if (! hasOverflow) return 0 // We haven't reached query_row yet, and water ran out\n hasOverflow = false;\n \n let rowGlass = Array(water.length).fill(0); // List of glasses at current row\n for (let i = 0; i < rowGlass.length; i++){\n let input = water[i];\n if (input <= 1){\n rowGlass[i] = input;\n water[i] = 0\n }else{\n rowGlass[i] = 1;\n water[i]--\n }\n if (row == query_row && i == query_glass){ // Return if we reach goal before water run out\n return rowGlass[i]\n }\n }\n // console.log('row,rowGlass',row,rowGlass); // to debug\n \n let nextWater = Array(water.length + 1).fill(0); // water poured towards next row, \n for (let i = 0; i < rowGlass.length; i++){\n let overflow = water[i];\n \n if (overflow > 0) hasOverflow = true;\n \n nextWater[i] += overflow / 2;\n nextWater[i+1] += overflow / 2;\n }\n water = nextWater;\n row ++;\n }\n};", "solution_java": "// Champagne Tower\n// Leetcode: https://leetcode.com/problems/champagne-tower/\n\nclass Solution {\n public double champagneTower(int poured, int query_row, int query_glass) {\n if (poured == 0) return 0;\n double[] memo = new double[101];\n memo[0] = poured;\n for (int i=0; i<100; i++) {\n for (int j=i; j>=0; j--) {\n if (memo[j] > 1) {\n if (i == query_row && j == query_glass) return 1;\n double val = (memo[j] - 1) / 2;\n memo[j+1] += val;\n memo[j] = val;\n } else {\n if (i == query_row && j == query_glass) return memo[query_glass];\n memo[j+1] += 0;\n memo[j] = 0;\n }\n }\n }\n return memo[query_glass];\n }\n}", "solution_c": "class Solution {\npublic:\n double champagneTower(int poured, int query_row, int query_glass) {\n vector currRow(1, poured);\n\t\t\n for(int i=0; i<=query_row; i++){ //we need to make the dp matrix only till query row. No need to do after that\n vector nextRow(i+2, 0); //If we are at row 0, row 1 will have 2 glasses. So next row will have currRow number + 2 number of glasses.\n for(int j=0; j<=i; j++){ //each row will have currRow number + 1 number of glasses.\n if(currRow[j]>=1){ //if the champagne from the current glass is being overflowed.\n nextRow[j] += (currRow[j]-1)/2.0; //fill the left glass with the overflowing champagne\n nextRow[j+1] += (currRow[j]-1)/2.0; //fill the right glass with the overflowing champagne\n currRow[j] = 1; //current glass will store only 1 cup of champagne\n }\n }\n if(i!=query_row) currRow = nextRow; //change the currRow for the next iteration. But if we have already reached the query_row, then the next iteration will not even take place, so the currRow is the query_row itself. So don't change as we need the currRow only.\n }\n return currRow[query_glass];\n }\n};" }, { "title": "Percentage of Letter in String", "algo_input": "Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.\n\n \nExample 1:\n\nInput: s = \"foobar\", letter = \"o\"\nOutput: 33\nExplanation:\nThe percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.\n\n\nExample 2:\n\nInput: s = \"jjjj\", letter = \"k\"\nOutput: 0\nExplanation:\nThe percentage of characters in s that equal the letter 'k' is 0%, so we return 0.\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists of lowercase English letters.\n\tletter is a lowercase English letter.\n\n", "solution_py": "class Solution:\n def percentageLetter(self, s: str, letter: str) -> int:\n return (s.count(letter)*100)//len(s)", "solution_js": "var percentageLetter = function(s, letter) {\n let count = 0;\n for (let i of s) { // count how many letters are in s\n if (i == letter) count++;\n }\n return (Math.floor((count*1.0) / (s.length*1.0) * 100)) // get percentage\n};", "solution_java": "class Solution {\n public int percentageLetter(String str, char letter) {\n int count=0;\n int n=str.length();\n for(int i=0;i List[float]:\n colis_times = [-1] * len(cars)\n cars = [Car(pos, sp, i) for i, (pos, sp) in enumerate(cars)]\n for i in range(len(cars)-1): cars[i].next = cars[i+1]\n for i in range(1, len(cars)): cars[i].prev = cars[i-1]\n \n catchup_order = [((b.pos-a.pos)/(a.speed-b.speed), a.idx, a)\n for i, (a, b) \n in enumerate(zip(cars, cars[1:])) if a.speed > b.speed]\n heapify(catchup_order)\n \n while catchup_order:\n catchup_time, idx, car = heappop(catchup_order)\n if colis_times[idx] > -1: continue # ith car has already caught up\n colis_times[idx] = catchup_time\n if not car.prev: continue # no car is following us\n car.prev.next, car.next.prev = car.next, car.prev\n if car.next.speed >= car.prev.speed: continue # the follower is too slow to catch up\n new_catchup_time = (car.next.pos-car.prev.pos)/(car.prev.speed-car.next.speed)\n heappush(catchup_order, (new_catchup_time, car.prev.idx, car.prev))\n \n return colis_times", "solution_js": "var getCollisionTimes = function(cars) {\n // create a stack to hold all the indicies of the cars that can be hit\n const possibleCarsToHit = [];\n const result = new Array(cars.length).fill(-1);\n\t\n for (let i = cars.length - 1; i >= 0; i--) {\n\t\n\t // if there are cars to hit, check if the current car will hit the car before or after hitting\n\t\t// the car in front of them\n\t\t// you can also think of this as if the current car will hit the car before or after being absorbed by\n\t\t// the slower car in front.\n while (possibleCarsToHit.length && result[possibleCarsToHit[possibleCarsToHit.length - 1]] >= 0) {\n const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];\n const timeToCatchNextCar = \n getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);\n const timeToCatchNextNextCar = result[nextCarIndex];\n if (timeToCatchNextCar > 0 && \n timeToCatchNextCar <= timeToCatchNextNextCar) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\t// pop off the stack because the car was absorbed by the next car\n\t\t\t// before getting hit by the current car\n possibleCarsToHit.pop();\n }\n if (possibleCarsToHit.length) {\n const nextCarIndex = possibleCarsToHit[possibleCarsToHit.length - 1];\n result[i] = getTimeToCatchNextCar(cars[i], cars[nextCarIndex]);\n }\n possibleCarsToHit.push(i);\n }\n return result;\n};\n \n \nfunction getTimeToCatchNextCar(leftCar, rightCar) {\n const [leftCarPosition, leftCarSpeed] = leftCar\n const [rightCarPosition, rightCarSpeed] = rightCar;\n const distanceToCatchCar = rightCarPosition - leftCarPosition;\n const differenceInSpeed = leftCarSpeed - rightCarSpeed;\n return differenceInSpeed > 0 ? distanceToCatchCar / differenceInSpeed : -1;\n}", "solution_java": "class Solution {\n public double[] getCollisionTimes(int[][] cars) {\n int n = cars.length;\n double[] res = new double[n];\n Arrays.fill(res, -1.0);\n\n // as soon as a car c1 catches another car c2, we can say c1 vanishes into c2; meaning that\n // after catching c2, we may view c1 as non-existing (cars before c1 may not catches c1);\n\n /** Define a stack storing the index of cars as follows:\n\n Assuming cars c_0, c_1, c_2, ... , c_k are in the stack, they satisfy:\n 1. v0 > v1 > v2 ... > vk where v_i is the velocity of car c_i\n 2. c_(i+1) is the car that c_i vanishes into\n\n Namely, if only these cars exist, then what will happened is that c_0 vanishes into c_1,\n then c_1 vanishes into c_2, ..., c_(k-1) vanishes into c_k;\n */\n Deque stack = new LinkedList<>();\n for (int i = n-1; i >= 0; i--) {\n int[] c1 = cars[i];\n while (!stack.isEmpty()) {\n int j = stack.peekLast();\n int[] c2 = cars[j];\n\n /** If both conditions are satisfied:\n 1. c1 is faster than c2\n 2. c1 catches c2 before c2 vanishes into other car\n\n Then we know that c2 is the car that c1 catches first (i.e., c1 vanishes into c2)\n ==> get the result for c1\n\n Note neither c1 nor c2 is polled out from the stack considering the rule of stack.\n */\n\n if (c1[1] > c2[1] && (res[j] == -1.0 || catchTime(cars, i, j) <= res[j])) {\n res[i] = catchTime(cars, i, j);\n break;\n }\n\n /** Now we have either one of situations\n 1. c1 is slower than c2\n 2. c1 potentially catches c2 AFTER c2 vanishes\n\n Claim: no car before c1 will vanish into c2\n\n 1. ==> cars before c1 will vanish into c1 first before catching c2\n 2. <==> c2 \"vanishes\" into another car even before c1 catches it\n\n Either way, c2 can not be catched by c1 or cars beofre c1 ==> poll it out from stack\n\n */\n stack.pollLast();\n }\n stack.offerLast(i);\n }\n return res;\n }\n\n // time for cars[i] to catch cars[j]\n private double catchTime(int[][] cars, int i, int j) {\n int dist = cars[j][0] - cars[i][0];\n int v = cars[i][1] - cars[j][1];\n\n return (double)dist / v;\n }\n}", "solution_c": "class Solution {\npublic:\n vector getCollisionTimes(vector>& cars)\n {\n int n = cars.size();\n vector res(n,-1.0);\n stack st;// for storing indices\n for(int i=n-1;i>=0;i--)\n {\n //traversing from back if someone has greater speed and ahead of lesser speed car it will always be ahead \n while(!st.empty() && cars[st.top()][1]>= cars[i][1])\n st.pop();\n while(!st.empty()) // for lesser speed car ahead of greater spped car\n {\n double collision_time = (double)(cars[st.top()][0]-cars[i][0])/(cars[i][1]-cars[st.top()][1]);\n if(collision_time <=res[st.top()] || res[st.top()] == -1)\n {\n res[i] = collision_time;\n break;\n }\n st.pop();\n }\n \n st.push(i);\n }\n return res;\n }\n};" }, { "title": "Longest Turbulent Subarray", "algo_input": "Given an integer array arr, return the length of a maximum size turbulent subarray of arr.\n\nA subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.\n\nMore formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:\n\n\n\tFor i <= k < j:\n\n\t\n\t\tarr[k] > arr[k + 1] when k is odd, and\n\t\tarr[k] < arr[k + 1] when k is even.\n\t\n\t\n\tOr, for i <= k < j:\n\t\n\t\tarr[k] > arr[k + 1] when k is even, and\n\t\tarr[k] < arr[k + 1] when k is odd.\n\t\n\t\n\n\n \nExample 1:\n\nInput: arr = [9,4,2,10,7,8,8,1,9]\nOutput: 5\nExplanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]\n\n\nExample 2:\n\nInput: arr = [4,8,12,16]\nOutput: 2\n\n\nExample 3:\n\nInput: arr = [100]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 4 * 104\n\t0 <= arr[i] <= 109\n\n", "solution_py": "class Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n def cmp(a,b):\n if a == b: return 0\n if a > b : return 1\n return -1\n\n n = len(arr)\n ans = 1\n prev = 0\n for i in range(1,n):\n c = cmp(arr[i-1],arr[i])\n if c == 0:\n # we shift prev to i\n prev = i\n elif i == n-1 or c * cmp(arr[i],arr[i+1]) != -1:\n ans = ans if ans > i - prev + 1 else i - prev + 1\n prev = i\n return ans", "solution_js": "var maxTurbulenceSize = function(arr) {\n const len = arr.length;\n const dp = Array.from({ length: len + 1 }, () => {\n return new Array(2).fill(0);\n });\n let ans = 0;\n for(let i = 1; i < len; i++) {\n if(arr[i-1] > arr[i]) {\n dp[i][0] = dp[i-1][1] + 1;\n } else if(arr[i-1] < arr[i]) {\n dp[i][1] = dp[i-1][0] + 1;\n }\n ans = Math.max(ans, ...dp[i]);\n }\n\n // console.log(dp);\n return ans + 1;\n};", "solution_java": "class Solution {\n public int maxTurbulenceSize(int[] arr) {\n if(arr.length == 1) {\n return 1;\n } \n int l = 0, r = 1;\n int diff = arr[l] - arr[r];\n int max;\n if(diff == 0) {\n l = 1;\n r = 1;\n max = 1;\n } else {\n l = 0;\n r = 1;\n max = 2;\n }\n for(int i = 1; r < arr.length-1; i++) {\n int nextdiff = arr[i] - arr[i+1];\n if(diff < 0) {\n if(nextdiff > 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n } else {\n if(nextdiff < 0) {\n r++;\n } else if(nextdiff == 0) {\n l = i+1;\n r = i+1;\n } else {\n l = i;\n r = i+1;\n }\n }\n diff = nextdiff;\n max = Math.max(max, r-l+1);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxTurbulenceSize(vector& arr) {\n vector table1(arr.size(), 0);\n vector table2(arr.size(), 0);\n table1[0] = 1;\n table2[0] = 1;\n int max_len = 1;\n for (int i=1; i arr[i - 1] && (i & 1) == 1) {\n table1[i] = table1[i - 1] + 1;\n }\n if (arr[i] > arr[i - 1] && (i & 1) == 0) {\n table2[i] = table2[i - 1] + 1;\n } else if (arr[i] < arr[i - 1] && (i & 1) == 1) {\n table2[i] = table2[i - 1] + 1;\n }\n max_len = max(max_len, table1[i]);\n max_len = max(max_len, table2[i]);\n }\n return max_len;\n }\n};" }, { "title": "Pascal's Triangle II", "algo_input": "Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.\n\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n\n \nExample 1:\nInput: rowIndex = 3\nOutput: [1,3,3,1]\nExample 2:\nInput: rowIndex = 0\nOutput: [1]\nExample 3:\nInput: rowIndex = 1\nOutput: [1,1]\n\n \nConstraints:\n\n\n\t0 <= rowIndex <= 33\n\n\n \nFollow up: Could you optimize your algorithm to use only O(rowIndex) extra space?\n", "solution_py": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n # base case\n # we know that there exist two base case one which is for zero input\n # One when we have to exit our recursive loop \n if rowIndex == 0:\n return [1]\n if rowIndex == 1:\n return [1,1]\n #recurance relation or prev call\n prev_prob = self.getRow(rowIndex-1)\n # post processing on data \n # if someone has given us prev_Row what operation we can perform to get current_Row\n return [1]+[prev_prob[i]+prev_prob[i-1] for i in range(1,len(prev_prob))]+[1]", "solution_js": "var getRow = function(rowIndex) {\n const triangle = [];\n\n for (let i = 0; i <= rowIndex; i++) {\n const rowValue = [];\n\n for (let j = 0; j < i + 1; j++) {\n if (j === 0 || j === i) {\n rowValue[j] = 1;\n } else {\n rowValue[j] = triangle[i - 1][j - 1] + triangle[i - 1][j];\n }\n }\n triangle.push(rowValue)\n }\n\n return triangle[rowIndex];\n};", "solution_java": "class Solution {\n public List getRow(int rowIndex) {\n List> out = new ArrayList<>();\n for(int i = 0; i<=rowIndex; i++){\n Listin = new ArrayList<>(i+1);\n for(int j = 0 ; j<= i; j++){\n if(j == 0 || j == i){\n in.add(1);\n }\n else{\n in.add(out.get(i-1).get(j-1) + out.get(i-1).get(j));\n }\n \n }\n out.add(in);\n }\n return out.get(rowIndex);\n }\n}", "solution_c": "class Solution {\npublic:\n vector getRow(int rowIndex) {\n vector ans(rowIndex+1,0);\n ans[0]=1;\n for(int i=1;i=1;j--){\n ans[j]=ans[j]+ans[j-1];\n }\n }\n return ans;\n }\n};" }, { "title": "Longest Increasing Path in a Matrix", "algo_input": "Given an m x n integers matrix, return the length of the longest increasing path in matrix.\n\nFrom each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).\n\n \nExample 1:\n\nInput: matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput: 4\nExplanation: The longest increasing path is [1, 2, 6, 9].\n\n\nExample 2:\n\nInput: matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput: 4\nExplanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.\n\n\nExample 3:\n\nInput: matrix = [[1]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 200\n\t0 <= matrix[i][j] <= 231 - 1\n\n", "solution_py": "class Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n ROWS, COLS = len(matrix), len(matrix[0])\n dp = {}\n \n def dfs(r, c, prevVal):\n if (r < 0 or r == ROWS or\n c < 0 or c == COLS or\n matrix[r][c] <= prevVal):\n return 0\n if (r, c) in dp:\n return dp[(r, c)]\n res = 1\n res = max(res, 1 + dfs(r + 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r - 1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r, c + 1, matrix[r][c]))\n res = max(res, 1 + dfs(r, c - 1, matrix[r][c]))\n dp[(r, c)] = res\n return res\n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, -1)\n return max(dp.values())", "solution_js": "var longestIncreasingPath = function(matrix) {\n const m = matrix.length, n = matrix[0].length;\n const dp = new Array(m).fill(0).map(() => {\n return new Array(n).fill(-1);\n });\n\n let ans = 0;\n const dir = [0, -1, 0, 1, 0];\n\n const dfs = (x, y) => {\n if(dp[x][y] != -1) return dp[x][y];\n\n for(let i = 1; i <= 4; i++) {\n const [nx, ny] = [x + dir[i], y + dir[i - 1]];\n if(\n nx >= 0 && ny >= 0 &&\n nx < m && ny < n &&\n matrix[nx][ny] > matrix[x][y]\n ) {\n dp[x][y] = Math.max(dp[x][y], 1 + dfs(nx, ny));\n }\n }\n\n if(dp[x][y] == -1) dp[x][y] = 1;\n ans = Math.max(ans, dp[x][y]);\n return dp[x][y];\n }\n\n for(let i = 0; i < m; i++) {\n for(let j = 0; j < n; j++) {\n if(dp[i][j] == -1) dfs(i, j);\n }\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int longestIncreasingPath(int[][] matrix) {\n int[][] memo = new int[matrix.length][matrix[0].length];\n int longestPath = 0;\n for (int i = 0; i < matrix.length; i++) {\n for (int j = 0; j < matrix[0].length; j++) {\n dfs(matrix, i, j, memo);\n longestPath = Math.max(longestPath, memo[i][j]);\n }\n }\n return longestPath;\n }\n\n private void dfs(int[][] matrix, int i, int j, int[][] memo) {\n if (memo[i][j] != 0)\n return;\n int[][] dirs = {{-1,0}, {0,1}, {1,0}, {0,-1}};\n int max = 0;\n for (int k = 0; k < dirs.length; k++) {\n int x = dirs[k][0] + i;\n int y = dirs[k][1] + j;\n if (isValid(matrix, x, y) && matrix[x][y] > matrix[i][j]) {\n // Get/compute the largest path for that index\n if (memo[x][y] == 0) { // If longest path doesn't exist for that path then compute it\n dfs(matrix, x, y, memo);\n }\n max = Math.max(max, memo[x][y]);\n }\n }\n memo[i][j] = 1 + max;\n }\n\n private boolean isValid(int[][] matrix, int i, int j) {\n if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)\n return false;\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n \n // declare a dp\n \n int dp[205][205];\n \n // direction coordinates of left, right, up, down\n \n vector dx = {-1, 0, 1, 0};\n \n vector dy = {0, 1, 0, -1};\n \n // dfs function\n \n int dfs(vector>& matrix, int i, int j, int n, int m)\n {\n // if value is already calculated for (i, j)th cell\n \n if(dp[i][j] != -1)\n return dp[i][j];\n \n // take the maximum of longest increasing path from all four directions\n \n int maxi = 0;\n \n for(int k = 0; k < 4; k++)\n {\n int new_i = i + dx[k];\n \n int new_j = j + dy[k];\n \n if(new_i >= 0 && new_i < n && new_j >= 0 && new_j < m && matrix[new_i][new_j] > matrix[i][j])\n {\n maxi = max(maxi, dfs(matrix, new_i, new_j, n, m));\n }\n }\n \n // store the res and return it\n \n return dp[i][j] = 1 + maxi;\n }\n \n int longestIncreasingPath(vector>& matrix) {\n \n int n = matrix.size();\n \n int m = matrix[0].size();\n \n // initialize dp with -1\n \n memset(dp, -1, sizeof(dp));\n \n // find the longest increasing path for each cell and take maximum of it\n \n int maxi = INT_MIN;\n \n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < m; j++)\n {\n int ans = dfs(matrix, i, j, n, m);\n \n maxi = max(maxi, ans);\n }\n }\n \n return maxi;\n }\n};" }, { "title": "Jump Game VII", "algo_input": "You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:\n\n\n\ti + minJump <= j <= min(i + maxJump, s.length - 1), and\n\ts[j] == '0'.\n\n\nReturn true if you can reach index s.length - 1 in s, or false otherwise.\n\n \nExample 1:\n\nInput: s = \"011010\", minJump = 2, maxJump = 3\nOutput: true\nExplanation:\nIn the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.\n\n\nExample 2:\n\nInput: s = \"01101110\", minJump = 2, maxJump = 3\nOutput: false\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 105\n\ts[i] is either '0' or '1'.\n\ts[0] == '0'\n\t1 <= minJump <= maxJump < s.length\n\n", "solution_py": "class Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n\t\t# dp[i] represents whether i is reachable\n dp = [False for _ in s]\n dp[0] = True\n\n for i in range(1, len(s)):\n if s[i] == \"1\":\n continue\n\n\t\t\t# iterate through the solutions in range [i - maxJump, i - minJump]\n\t\t\t# and if any previous spot in range is reachable, then i is also reachable\n window_start = max(0, i - maxJump)\n window_end = i - minJump\n for j in range(window_start, window_end + 1):\n if dp[j]:\n dp[i] = True\n break\n \n return dp[-1] ", "solution_js": "var canReach = function(s, minJump, maxJump) {\n const validIdxs = [0];\n for (let i = 0; i < s.length; i++) {\n // skip if character is a 1 or if all the \n // valid indicies are too close\n if (s[i] === '1' || i - validIdxs[0] < minJump) {\n continue;\n }\n \n // remove all the indexes that are too far\n while (validIdxs.length && i - validIdxs[0] > maxJump) {\n validIdxs.shift();\n }\n if (validIdxs.length === 0) {\n return false;\n }\n \n validIdxs.push(i);\n \n // if we are at the last index\n // return if we have an index within range\n if (i === s.length - 1) {\n return i - validIdxs[0] >= minJump;\n }\n }\n // if the last character is a 1 we must return False\n return false;\n};", "solution_java": "class Solution {\n public boolean canReach(String s, int minJump, int maxJump) {\n if(s.charAt(s.length() - 1) != '0')\n return false;\n \n Queue queue = new LinkedList<>();\n queue.add(0);\n \n // This variable tells us till which index we have processed\n int maxReach = 0;\n \n while(!queue.isEmpty()){\n int idx = queue.remove();\n // If we reached the last index\n if(idx == s.length() - 1)\n return true;\n \n // start the loop from max of [current maximum (idx + minJump), maximum processed index (maxReach)]\n for(int j = Math.max(idx + minJump, maxReach); j <= Math.min(idx + maxJump, s.length() - 1); j++){\n if(s.charAt(j) == '0')\n queue.add(j);\n }\n \n // since we have processed till idx + maxJump so update maxReach to next index\n maxReach = Math.min(idx + maxJump + 1, s.length() - 1);\n }\n \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canReach(string s, int minJump, int maxJump) {\n int n = s.length();\n if(s[n-1]!='0')\n return false;\n \n int i = 0;\n queue q;\n q.push(0);\n int curr_max = 0;\n \n while(!q.empty()){\n i = q.front();\n q.pop();\n if(i == n-1)\n return true;\n \n for(int j = max(i + minJump, curr_max); j <= min(i + maxJump, n - 1); j++){\n if(s[j] == '0') q.push(j);\n } \n curr_max = min(i+maxJump+1, n);\n }\n return false;\n }\n};" }, { "title": "Online Election", "algo_input": "You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].\n\nFor each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.\n\nImplement the TopVotedCandidate class:\n\n\n\tTopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.\n\tint q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.\n\n\n \nExample 1:\n\nInput\n[\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]\nOutput\n[null, 0, 1, 1, 0, 0, 1]\n\nExplanation\nTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1\n\n\n\n \nConstraints:\n\n\n\t1 <= persons.length <= 5000\n\ttimes.length == persons.length\n\t0 <= persons[i] < persons.length\n\t0 <= times[i] <= 109\n\ttimes is sorted in a strictly increasing order.\n\ttimes[0] <= t <= 109\n\tAt most 104 calls will be made to q.\n\n", "solution_py": "class TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n counter = defaultdict(int)\n\n mostVotePersons = [0] * len(persons) # mostVotePersons[i] is the most vote person at times[i]\n largestVote = -1 # keep largest vote person index\n for i in range(len(persons)):\n counter[persons[i]] += 1\n if largestVote == -1 or counter[persons[i]] >= counter[largestVote]:\n largestVote = persons[i]\n mostVotePersons[i] = largestVote\n \n self.times = times\n self.mostVotePersons = mostVotePersons\n\n def q(self, t: int) -> int:\n idx = bisect_right(self.times, t) - 1 # binary search on times to find the most recent time before t\n return self.mostVotePersons[idx]", "solution_js": "var TopVotedCandidate = function(persons, times) {\n this.times = times;\n this.len = times.length;\n this.votes = new Array(this.len).fill(0);\n \n let max = 0; // max votes received by any single candidate so far.\n let leader = -1l;\n \n this.leaders = persons.map((person, i) => {\n this.votes[person]++;\n \n if (this.votes[person] >= max) {\n max = this.votes[person];\n leader = person;\n }\n \n return leader;\n });\n \n};\n\nTopVotedCandidate.prototype.q = function(t) {\n let left = 0;\n let right = this.len - 1;\n \n while (left <= right) {\n const mid = left + Math.floor((right - left) / 2);\n \n if (this.times[mid] === t) return this.leaders[mid];\n else if (this.times[mid] < t) left = mid + 1;\n else right = mid - 1;\n }\n\t\n return this.leaders[right];\n};", "solution_java": "class TopVotedCandidate {\n int[] persons;\n int[] times;\n int length;\n Map voteCount;\n Map voteLead;\n\n public TopVotedCandidate(int[] persons, int[] times) {\n this.persons = persons;\n this.times = times;\n length = times.length-1;\n int leadCount = 0;\n int leadPerson = -1;\n voteCount = new HashMap<>();\n voteLead = new HashMap<>();\n for(int i=0; i<=length; i++){\n int newCount = voteCount.getOrDefault(persons[i], 0) + 1;\n voteCount.put(persons[i], newCount);\n if(newCount >= leadCount){\n leadCount = newCount;\n leadPerson = persons[i];\n }\n voteLead.put(times[i], leadPerson);\n }\n }\n\n public int q(int t) {\n int leadPerson = -1;\n if(voteLead.containsKey(t)) {\n leadPerson = voteLead.get(t);\n }\n else if(t < times[0]){\n leadPerson = voteLead.get(times[0]);\n }\n else if(t > times[length]){\n leadPerson = voteLead.get(times[length]);\n }\n else {\n int low = 0;\n int high = length;\n while(low <= high){\n int mid = low + (high-low)/2;\n if(times[mid] > t) high = mid - 1;\n else low = mid + 1;\n }\n leadPerson = voteLead.get(times[high]);\n }\n return leadPerson;\n }\n}", "solution_c": "class TopVotedCandidate {\npublic:\n vector pref;\n vector glob_times;\n TopVotedCandidate(vector& persons, vector& times) {\n int n = times.size();\n glob_times = times;\n pref.resize(n);\n vector cnt;\n int sz = persons.size();\n cnt.resize(sz+1, 0);\n cnt[persons[0]]++;\n pref[0] = persons[0];\n int maxi = 1;\n int maxi_person = persons[0];\n for(int i = 1; i < n; i++){ \n cnt[persons[i]]++;\n if(cnt[persons[i]] > maxi){\n maxi = cnt[persons[i]];\n maxi_person = persons[i];\n }\n else if(cnt[persons[i]] == maxi){\n maxi_person = persons[i];\n }\n \n pref[i] = maxi_person;\n }\n } \n \n int q(int t) {\n \n int it = upper_bound(glob_times.begin(), glob_times.end(), t) - glob_times.begin();\n if(it == 0) it++;\n return pref[it-1];\n }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj->q(t);\n */" }, { "title": "Four Divisors", "algo_input": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.\n\n \nExample 1:\n\nInput: nums = [21,4,7]\nOutput: 32\nExplanation: \n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\n\nExample 2:\n\nInput: nums = [21,21]\nOutput: 64\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t1 <= nums[i] <= 105\n\n", "solution_py": "import math \nclass Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n s=0\n for i in nums:\n r=i+1\n c=2\n for j in range(2, int(math.sqrt(i))+1):\n if i%j==0:\n if (i / j == j) :\n c+=1\n r+=j\n else :\n c+=2\n r+=j+int(i/j)\n print(c, r)\n if c==4:\n s+=r\n return s", "solution_js": "var sumFourDivisors = function(nums) {\n let check = (num) => {\n let divs = [num]; // init the array with the number itself\n let orig = num;\n num = num >> 1; // divide in half to avoid checking too many numbers\n while (num > 0) {\n if (orig % num === 0) divs.push(num);\n num--;\n if (divs.length > 4) return 0;\n }\n if (divs.length === 4) {\n return divs.reduce((a, b) => a + b, 0);\n }\n return 0;\n }\n \n let total = 0;\n \n for (let num of nums) {\n total += check(num);\n }\n \n return total;\n};", "solution_java": "class Solution {\n public int sumFourDivisors(int[] nums) {\n int res = 0;\n for(int val : nums){\n int sum = 0;\n int count = 0;\n for(int i=1;i*i <= val;i++){\n if(val % i == 0){\n sum += i;\n count++;\n if(i != val/i){\n sum += val/i;\n count++;\n }\n }\n }\n if(count == 4){\n res += sum;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int sumFourDivisors(vector& nums) {\n int n = nums.size();\n int sum = 0,cnt=0,temp=0;\n for(int i=0;i4)\n break;\n }\n }\n if(cnt==4){\n sum += temp;\n }\n temp=0; cnt=0;\n }\n return sum;\n }\n};" }, { "title": "Smallest Value of the Rearranged Number", "algo_input": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.\n\nReturn the rearranged number with minimal value.\n\nNote that the sign of the number does not change after rearranging the digits.\n\n \nExample 1:\n\nInput: num = 310\nOutput: 103\nExplanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.\n\n\nExample 2:\n\nInput: num = -7605\nOutput: -7650\nExplanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.\n\n\n \nConstraints:\n\n\n\t-1015 <= num <= 1015\n\n", "solution_py": "class Solution:\n def smallestNumber(self, num: int) -> int:\n lst=[i for i in str(num)]\n if num<0:\n return ''.join(['-'] + sorted(lst[1:],reverse=True))\n lst=sorted(lst)\n if '0' in lst:\n itr=0\n while itr0){\n arr.sort((a,b)=>{\n return a-b;\n })\n }\n else{\n arr.sort((a,b)=>{\n return b-a;\n })\n }\n for(let i=0;i List[int]:\n l = len(str(low))\n h = len(str(high))\n ans = []\n for i in range(l,h+1):\n for j in range(1,11-i):\n t = str(j)\n for k in range(i-1):\n t+=str(int(t[-1])+1)\n if int(t)<=high and int(t)>=low:\n ans.append(int(t))\n ans.sort()\n return ans", "solution_js": "var sequentialDigits = function(low, high) {\n const digits = '123456789';\n const ans = [];\n \n const minLen = low.toString().length;\n const maxLen = high.toString().length;\n \n for (let windowSize = minLen; windowSize <= maxLen; ++windowSize) {\n for (let i = 0; i + windowSize <= digits.length; ++i) {\n const num = parseInt(digits.substring(i, i + windowSize));\n \n if (num >= low && num <= high) {\n ans.push(num);\n }\n }\n }\n \n \n return ans;\n};", "solution_java": "class Solution {\n public List sequentialDigits(int low, int high) {\n int lowSize = String.valueOf(low).length(), highSize = String.valueOf(high).length();\n List output = new ArrayList<>();\n\n for(int size=lowSize; size<=highSize; size++) {\n int seedNumber = getSeedNumber(size);\n int increment = getIncrement(size);\n int limit = (int)Math.pow(10,size);\n // System.out.println(seedNumber+\":\"+increment+\":\"+limit);\n while(true){\n if(seedNumber>=low && seedNumber<=high)\n output.add(seedNumber);\n if(seedNumber%10==9 || seedNumber>high) break;\n seedNumber+=increment;\n }\n }\n return output;\n }\n\n private int getSeedNumber(int size) {\n int seed = 1;\n for(int i=2;i<=size;i++)\n seed=10*seed + i;\n return seed;\n }\n\n private int getIncrement(int size) {\n int increment = 1;\n for(int i=2;i<=size;i++)\n increment=10*increment + 1;\n return increment;\n }\n}", "solution_c": "class Solution {\npublic:\n vector sequentialDigits(int low, int high) {\n string lf = to_string(low);\n string rt = to_string(high);\n \n vector ans;\n for(int i = lf.size(); i <= rt.size(); i++){ // 字符串长度\n for(int st = 1; st <= 9; st++){\n string base(i, '0'); // \"000000\" i个0\n for(int j = 0; j < i; j++){\n base[j] += st + j;\n }\n \n if(base.back() <= '9'){\n int num = stoi(base);\n if(low <= num && num <= high){\n ans.push_back(num);\n }\n }\n }\n }\n \n return ans;\n }\n \n};" }, { "title": "Sender With Largest Word Count", "algo_input": "You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].\n\nA message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.\n\nReturn the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.\n\nNote:\n\n\n\tUppercase letters come before lowercase letters in lexicographical order.\n\t\"Alice\" and \"alice\" are distinct.\n\n\n \nExample 1:\n\nInput: messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]\nOutput: \"Alice\"\nExplanation: Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return \"Alice\".\n\n\nExample 2:\n\nInput: messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]\nOutput: \"Charlie\"\nExplanation: Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.\n\n \nConstraints:\n\n\n\tn == messages.length == senders.length\n\t1 <= n <= 104\n\t1 <= messages[i].length <= 100\n\t1 <= senders[i].length <= 10\n\tmessages[i] consists of uppercase and lowercase English letters and ' '.\n\tAll the words in messages[i] are separated by a single space.\n\tmessages[i] does not have leading or trailing spaces.\n\tsenders[i] consists of uppercase and lowercase English letters only.\n\n", "solution_py": "class Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d={}\n l=[]\n for i in range(len(messages)):\n if senders[i] not in d:\n d[senders[i]]=len(messages[i].split())\n else:\n d[senders[i]]+=len(messages[i].split())\n x=max(d.values())\n for k,v in d.items():\n if v==x :\n l.append(k)\n if len(l)==1:\n return l[0]\n else:\n l=sorted(l)[::-1] #Lexigograhical sorting of list\n return l[0]", "solution_js": "/**\n * @param {string[]} messages\n * @param {string[]} senders\n * @return {string}\n */\nvar largestWordCount = function(messages, senders) {\n let wordCount = {}\n let result = ''\n let maxCount = -Infinity\n for (let i = 0; i < messages.length;i++) {\n let count=messages[i].split(' ').length\n wordCount[senders[i]] = wordCount[senders[i]] == undefined ? count : wordCount[senders[i]] + count;\n if (wordCount[senders[i]] > maxCount || (wordCount[senders[i]] == maxCount && senders[i] > result)) {\n maxCount = wordCount[senders[i]];\n result = senders[i];\n }\n }\n return result;\n\n};", "solution_java": "class Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n HashMap hm=new HashMap<>();\n\t\t\n int max=0;\n String name=\"\";\n for(int i=0;imax){\n max=hm.get(senders[i]);\n name=senders[i];\n }\n else if(hm.get(senders[i])==max && name.compareTo(senders[i])<0){\n name=senders[i];\n } \n }\n \n return name;\n }\n}", "solution_c": "class Solution {\npublic:\n string largestWordCount(vector& messages, vector& senders) {\n\n int n(size(messages));\n map m;\n for (auto i=0; i> word) count++;\n m[senders[i]] += count;\n }\n\n int count(0);\n string res;\n for (auto& p : m) {\n if (p.second >= count) {\n count = p.second;\n if (!res.empty() or res < p.first) res = p.first;\n }\n }\n return res;\n }\n};" }, { "title": "Arithmetic Slices II - Subsequence", "algo_input": "Given an integer array nums, return the number of all the arithmetic subsequences of nums.\n\nA sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n\n\n\tFor example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.\n\tFor example, [1, 1, 2, 5, 7] is not an arithmetic sequence.\n\n\nA subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n\n\n\tFor example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\n\n\nThe test cases are generated so that the answer fits in 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [2,4,6,8,10]\nOutput: 7\nExplanation: All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]\n\n\nExample 2:\n\nInput: nums = [7,7,7,7,7]\nOutput: 16\nExplanation: Any subsequence of this array is arithmetic.\n\n\n \nConstraints:\n\n\n\t1  <= nums.length <= 1000\n\t-231 <= nums[i] <= 231 - 1\n\n", "solution_py": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n sz, dp, ans = len(nums), [defaultdict(int) for _ in range(len(nums))], 0\n for i in range(1, sz):\n for j in range(i):\n difference = nums[i] - nums[j]\n dp[i][difference] += 1\n if difference in dp[j]:\n dp[i][difference] += dp[j][difference]\n ans += dp[j][difference]\n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numberOfArithmeticSlices = function(nums) {\n let dp = new Array(nums.length);\n for(let i = 0; i < nums.length; i++) {\n dp[i] = new Map();\n }\n let ans = 0;\n for(let j = 1; j < nums.length; j++) {\n for(let i = 0; i < j; i++) {\n let commonDifference = nums[j] - nums[i];\n if ((commonDifference > (Math.pow(2, 31) - 1)) || commonDifference < (-Math.pow(2, 31))) {\n continue;\n }\n let apsEndingAtI = dp[i].get(commonDifference) || 0\n let apsEndingAtJ = dp[j].get(commonDifference) || 0\n\n dp[j].set(commonDifference, (apsEndingAtI + apsEndingAtJ + 1));\n ans += apsEndingAtI;\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int numberOfArithmeticSlices(int[] nums) {\n int n=nums.length;\n \n HashMap []dp=new HashMap[n];\n \n for(int i=0;i();\n }\n \n int ans=0;\n \n for(int i=1;i=Integer.MAX_VALUE){\n continue;\n }\n \n int endingAtj=dp[j].getOrDefault((int)cd,0);\n int endingAti=dp[i].getOrDefault((int)cd,0);\n \n ans+=endingAtj;\n \n dp[i].put((int)cd,endingAtj+endingAti+1);\n }\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfArithmeticSlices(vector& nums) {\n int n=nums.size(),ans=0;\n unordered_map> ma; // [diff, [index, count]]\n unordered_map k;\n for(int i=1;ival < x){\n leftTail->next = head;\n leftTail = leftTail->next;\n }\n else{\n rightTail->next = head;\n rightTail = rightTail->next;\n }\n head = head->next;\n }\n \n leftTail->next = right->next;\n rightTail->next = NULL;\n \n return left->next;\n }\n};" }, { "title": "Toeplitz Matrix", "algo_input": "Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.\n\nA matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\n\n \nExample 1:\n\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: true\nExplanation:\nIn the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.\n\n\nExample 2:\n\nInput: matrix = [[1,2],[2,2]]\nOutput: false\nExplanation:\nThe diagonal \"[1, 2]\" has different elements.\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 20\n\t0 <= matrix[i][j] <= 99\n\n\n \nFollow up:\n\n\n\tWhat if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?\n\tWhat if the matrix is so large that you can only load up a partial row into the memory at once?\n\n", "solution_py": "###########################################################################################\n# Number of rows(M) x expected numbers(N)\n# Space: O(N)\n# We need to store the expected numbers in list\n############################################################################################\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n # Validate Input\n if not matrix or not matrix[0]:\n return False \n \n # Create a deque tracking the expected values for the next row\n expected = matrix[0]\n # We only care about the elements before last element\n expected.pop()\n \n # From the second row, pop out the last element of the expected numbers and compare it with the target row[1:]\n for row in matrix[1:]:\n # Compare row with expected numbers, invalidate it as soon as we find the numbers are not the same (O(N))\n if row[1:] != expected:\n return False\n else:\n # Pop the last element from row, use it as the expected numbers for the next iteration\n row.pop()\n expected = row\n # If we've reached here, all diagonals aligned\n return True", "solution_js": "var isToeplitzMatrix = function(matrix) {\n for (let i=0; i < matrix.length-1; i++) {\n for (let j=0; j < matrix[i].length-1; j++) {\n if (matrix[i][j] !== matrix[i+1][j+1]) {\n return false\n }\n }\n }\n\n return true\n};", "solution_java": "class Solution {\n public boolean isToeplitzMatrix(int[][] matrix) {\n \n \n int n = matrix.length;\n int m = matrix[0].length;\n \n for(int i = 0; i < m; i++){\n int row = 0;\n int col = i;\n int e = matrix[row++][col++];\n while(row < n && col< m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n } \n }\n \n for(int r = 1; r < n; r++){\n int row = r;\n int col = 0;\n int e =matrix[row++][col++];\n while(row < n && col < m){\n if(e == matrix[row][col]){\n row++;\n col++;\n }else{\n return false;\n }\n }\n }\n \n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isToeplitzMatrix(vector>& matrix) {\n int m = matrix.size(), n = matrix[0].size();\n for (int i = 1; i < m; i++)\n for (int j = 1; j < n; j++)\n if (matrix[i][j] != matrix[i - 1][j - 1])\n return false;\n return true;\n }\n};" }, { "title": "Number of Burgers with No Waste of Ingredients", "algo_input": "Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:\n\n\n\tJumbo Burger: 4 tomato slices and 1 cheese slice.\n\tSmall Burger: 2 Tomato slices and 1 cheese slice.\n\n\nReturn [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].\n\n \nExample 1:\n\nInput: tomatoSlices = 16, cheeseSlices = 7\nOutput: [1,6]\nExplantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.\n\n\nExample 2:\n\nInput: tomatoSlices = 17, cheeseSlices = 4\nOutput: []\nExplantion: There will be no way to use all ingredients to make small and jumbo burgers.\n\n\nExample 3:\n\nInput: tomatoSlices = 4, cheeseSlices = 17\nOutput: []\nExplantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n\n\n \nConstraints:\n\n\n\t0 <= tomatoSlices, cheeseSlices <= 107\n\n", "solution_py": "class Solution(object):\n def numOfBurgers(self, t, c):\n \n if t==c==0:\n return [0,0]\n four=(t-2*c)//2 # no of jumbo burgers by solving 4x+2y=t and x+y=c\n two=c-four #number of small burgers\n if c>=t or (t-2*c)%2==1 or four<0 or two<0: #if cheese is less than tomatoes or if number of jumbo burgers is a decimal or number of burgers are negtive we return empty list\n return []\n \n return [four,two]\n ", "solution_js": "/**\n * @param {number} tomatoSlices\n * @param {number} cheeseSlices\n * @return {number[]}\n */\nvar numOfBurgers = function(tomatoSlices, cheeseSlices) {\n if (tomatoSlices & 1) return []; // return [] if tomatoSlices is odd\n const j = (tomatoSlices >> 1) - cheeseSlices; // jumbo = (tomatoSlices / 2) - cheeseSlices\n return j < 0 || j > cheeseSlices ? [] : [j, cheeseSlices - j]; // small = cheeseSlices - jumbo, if any of jmbo and small < 0 return [] otherwise return [jumbo, small]\n};", "solution_java": "class Solution {\n public List numOfBurgers(int tomatoSlices, int cheeseSlices) {\n Listlist=new ArrayList<>();\n int ts=tomatoSlices;\n int cs=cheeseSlices;\n if (tscs*4 || ts%2!=0 || (ts==0 && cs>0) || (cs==0 && ts>0))\n {\n return list;\n }\n int cnt=0;\n while(ts>0 && cs>0 && ts!=cs*2)\n {\n ts-=4;\n cnt++;\n cs--;\n }\n list.add(cnt);\n list.add(cs);\n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n vector numOfBurgers(int tomatoSlices, int cheeseSlices) {\n // Observation\n // Total Number of Burgers is Equal to Number of cheeseSlices\n // Try to make 1 --> cheeseSlices Amount of Jumbo Burgers and\n // remaining will be Small Burger\n vector ans;\n if(tomatoSlices == 0 and cheeseSlices == 0) {\n ans.push_back(0), ans.push_back(0);\n return ans;\n }\n // Do Binary Search to Get Ideal Division.\n int low = 0, high = cheeseSlices;\n while(low < high) {\n int mid = (low + high) / 2;\n int jumbo = mid, small = cheeseSlices - mid;\n // Jumbo needs 4 tomatoes per burger\n // Small needs 2 tomatoes per burger\n int needJumboTom = jumbo * 4;\n int needSmallTom = small * 2;\n // Should Add Upto tomatoSlices\n if(needJumboTom + needSmallTom == tomatoSlices) {\n ans.push_back(jumbo), ans.push_back(small);\n break;\n } else if(needJumboTom + needSmallTom < tomatoSlices) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return ans;\n }\n};" }, { "title": "N-ary Tree Level Order Traversal", "algo_input": "Given an n-ary tree, return the level order traversal of its nodes' values.\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n\n \nExample 1:\n\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [[1],[3,2,4],[5,6]]\n\n\nExample 2:\n\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n\n\n \nConstraints:\n\n\n\tThe height of the n-ary tree is less than or equal to 1000\n\tThe total number of nodes is between [0, 104]\n\n", "solution_py": "class Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n if not root:\n return []\n \n result = []\n level = [root]\n \n while level:\n current_level = []\n next_level = []\n \n for node in level:\n current_level.append(node.val)\n next_level += node.children\n \n result.append(current_level)\n level = next_level\n \n return result", "solution_js": "var levelOrder = function(root) {\n if(!root) return [];\n \n const Q = [[root, 0]];\n const op = [];\n \n while(Q.length) {\n const [node, level] = Q.shift();\n \n if(op.length <= level) {\n op[level] = [];\n }\n op[level].push(node.val);\n \n for(const child of node.children) {\n Q.push([child, level + 1]);\n }\n }\n return op;\n};", "solution_java": "class Solution {\n public List> result= new ArrayList();\n public List> levelOrder(Node root) {\n if(root==null) return result;\n helper(root,0);\n return result;\n }\n \n private void helper(Node node,int level){\n if(result.size()<=level){\n result.add(new ArrayList());\n }\n result.get(level).add(node.val);\n for(Node child:node.children){\n helper(child,level+1);\n }\n \n }\n}", "solution_c": "class Solution {\npublic:\n \n vector> ans;\n \n vector> levelOrder(Node* root) {\n \n dfs(root, 0);\n return ans;\n }\n \n void dfs(Node* root, int level) {\n \n if(!root) {\n return;\n }\n if(level == ans.size()) {\n ans.push_back({});\n }\n ans[level].push_back(root->val);\n for(auto i : root->children) {\n dfs(i, level+1);\n }\n \n }\n \n};" }, { "title": "Exam Room", "algo_input": "There is an exam room with n seats in a single row labeled from 0 to n - 1.\n\nWhen a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.\n\nDesign a class that simulates the mentioned exam room.\n\nImplement the ExamRoom class:\n\n\n\tExamRoom(int n) Initializes the object of the exam room with the number of the seats n.\n\tint seat() Returns the label of the seat at which the next student will set.\n\tvoid leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.\n\n\n \nExample 1:\n\nInput\n[\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n[[10], [], [], [], [], [4], []]\nOutput\n[null, 0, 9, 4, 2, null, 5]\n\nExplanation\nExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.\n\n\n\n \nConstraints:\n\n\n\t1 <= n <= 109\n\tIt is guaranteed that there is a student sitting at seat p.\n\tAt most 104 calls will be made to seat and leave.\n\n", "solution_py": "class ExamRoom:\n\n def __init__(self, n: int):\n self.N = n\n self.pq = []\n self.dict = {}\n self.addSegment(0, self.N - 1)\n\n def seat(self) -> int:\n start, end, distance = heapq.heappop(self.pq)\n self.dict.pop(start, None) #Remove old segment from dictionary\n self.dict.pop(end, None)\n\n if start == end:\n position = start\n\n elif start == 0:\n position = start\n right = self.addSegment(start + 1, end)\n\n elif end == self.N - 1:\n position = end\n left = self.addSegment(start, end - 1)\n\n elif end - start == 1: #ONLY ONE PLACE TO PUT\n position = start\n left = self.addSegment(start + 1, end)\n\n else:\n position = start + (end - start) // 2\n right = self.addSegment(start, position - 1)\n left = self.addSegment(position + 1, end)\n\n return position\n\n def leave(self, p: int) -> None:\n left = self.dict.get(p - 1, None)\n right = self.dict.get(p + 1, None)\n\n new_start = new_end = p\n\n if left:\n self.removeSegment(left)\n new_start = left.start\n\n if right:\n self.removeSegment(right)\n new_end = right.end\n\n self.addSegment(new_start, new_end)\n\n def addSegment(self, start, end):\n segment = Segment(start, end, self.N)\n self.dict[segment.start] = segment\n self.dict[segment.end] = segment\n heapq.heappush(self.pq, segment)\n\n def removeSegment(self, segment):\n self.dict.pop(segment.start, None)\n self.dict.pop(segment.end, None)\n self.pq.remove(segment)\n\nclass Segment():\n def __init__(self, start, end, N):\n self.start = start\n self.end = end\n self.distance = self.calculateDistance(start, end, N)\n\n def __lt__(self, other_segment):\n return self.distance > other_segment.distance if self.distance != other_segment.distance else self.start < other_segment.start\n\n def calculateDistance(self, start, end, N):\n if start == 0:\n return end\n\n if end == N - 1:\n return end - start\n\n else:\n return (end - start) // 2\n\n def __iter__(self):\n return iter((self.start, self.end, self.distance))", "solution_js": "/**\n * @param {number} n\n */\nvar ExamRoom = function(n) {\n this.n = n\n this.list = []\n};\n\n/**\n * @return {number}\n */\nExamRoom.prototype.seat = function() {\n // if nothing in the list, seat the first student at index 0.\n if(this.list.length === 0){\n this.list.push(0)\n return 0\n }\n\n // find the largest distance between left wall and first student, and right wall and last student\n let distance = Math.max(this.list[0], this.n - 1 - this.list[this.list.length-1])\n // update the largest distance by considering the distance between students\n for(let i=0; i available;\n private final TreeSet taken;\n\n public ExamRoom(int n) {\n this.max = n - 1;\n this.available = new TreeSet<>((a, b) -> {\n var distA = getMinDistance(a);\n var distB = getMinDistance(b);\n return distA == distB ? a.s - b.s : distB - distA;\n });\n this.available.add(new Interval(0, max));\n this.taken = new TreeSet<>();\n }\n\n public int seat() {\n var inter = available.pollFirst();\n var idx = getInsertPosition(inter);\n taken.add(idx);\n if ((idx - 1) - inter.s >= 0)\n available.add(new Interval(inter.s, idx - 1));\n if (inter.e - (idx + 1) >= 0)\n available.add(new Interval(idx + 1, inter.e));\n return idx;\n }\n\n public void leave(int p) {\n taken.remove(p);\n var lo = taken.lower(p);\n if (lo == null)\n lo = -1;\n var hi = taken.higher(p);\n if (hi == null)\n hi = max + 1;\n available.remove(new Interval(lo + 1, p - 1));\n available.remove(new Interval(p + 1, hi - 1));\n available.add(new Interval(lo + 1, hi - 1));\n }\n\n private int getInsertPosition(Interval inter) {\n if (inter.s == 0)\n return 0;\n else if (inter.e == max)\n return max;\n else\n return inter.s + (inter.e - inter.s) / 2;\n }\n\n private int getMinDistance(Interval in) {\n return in.s == 0 || in.e == max ? in.e - in.s : (in.e - in.s) / 2;\n }\n\n private final class Interval {\n private final int s;\n private final int e;\n\n Interval(int s, int e) {\n this.s = s;\n this.e = e;\n }\n\n @Override\n public String toString() {\n return \"[\" + s + \",\" + e + \"]\";\n }\n }\n}", "solution_c": "class ExamRoom {\npublic:\n set s; // ordered set\n int num;\n ExamRoom(int n) {\n num=n; // total seats\n }\n \n int seat() {\n if(s.size()==0) { s.insert(0); return 0;} // if size is zero place at seat 0\n auto itr = s.begin();\n if(s.size()==1) { // if size==1 -> check if its closer to 0 or last seat (num-1) \n if(*itr > num-1-(*itr)){ s.insert(0); return 0; }\n else{ s.insert(num-1); return num-1;}\n }\n int mx=-1; // for max gap\n int l=0; // for left index of the student to max gap.\n \n if(s.find(0)==s.end()){mx = (*itr); l=-mx;} // if 0 is not seated -> check gap with 0 and starting seat.\n\t\t\n\t\t// Iterate the set to calculate gaps \n for(int i=0;i check gap with last filled seat and (num-1)\n if(mx< num-1-(*itr)) {\n mx = (num-1-(*itr));\n l=*itr;\n }\n }\n s.insert(l+mx); // place the student at l+mx\n return l+mx;\n \n \n }\n \n void leave(int p) {\n\t// remove student from set\n s.erase(p);\n }\n};" }, { "title": "Largest Substring Between Two Equal Characters", "algo_input": "Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"aa\"\nOutput: 0\nExplanation: The optimal substring here is an empty substring between the two 'a's.\n\nExample 2:\n\nInput: s = \"abca\"\nOutput: 2\nExplanation: The optimal substring here is \"bc\".\n\n\nExample 3:\n\nInput: s = \"cbzxy\"\nOutput: -1\nExplanation: There are no characters that appear twice in s.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 300\n\ts contains only lowercase English letters.\n\n", "solution_py": "class Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n last, ans = {}, -1 \n for i, c in enumerate(s):\n if c not in last:\n last[c] = i\n else:\n ans = max(ans, i - last[c] - 1)\n return ans ", "solution_js": "var maxLengthBetweenEqualCharacters = function(s) {\n \n const map = new Map();\n let max=-1;\n for(let i=0;i map = new HashMap<>();\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n if (map.containsKey(ch)) {\n ans = Math.max(ans, i - 1 - map.get(ch));\n }\n else {\n map.put(ch, i);\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxLengthBetweenEqualCharacters(string s) {\n vector v(26, -1);\n int maxi = -1;\n \n for (int i = 0; i < s.size(); i++) {\n if (v[s[i] - 'a'] == -1) v[s[i] - 'a'] = i;\n else maxi = max(maxi, abs(v[s[i] - 'a'] - i) - 1); \n }\n \n return maxi;\n }\n};" }, { "title": "Reachable Nodes With Restrictions", "algo_input": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n\nYou are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.\n\nReturn the maximum number of nodes you can reach from node 0 without visiting a restricted node.\n\nNote that node 0 will not be a restricted node.\n\n \nExample 1:\n\nInput: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput: 4\nExplanation: The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\nExample 2:\n\nInput: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput: 3\nExplanation: The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 105\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 <= ai, bi < n\n\tai != bi\n\tedges represents a valid tree.\n\t1 <= restricted.length < n\n\t1 <= restricted[i] < n\n\tAll the values of restricted are unique.\n\n", "solution_py": "class Solution:\n def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n # ignore restricted node\n # bfs from 0\n \n # O(E), EDITED: the time complexity here is wrong, plz see my comment\n adj_dict = collections.defaultdict(list)\n for u, v in edges:\n if u in restricted or v in restricted: # EDITED: not O(1)\n continue\n adj_dict[u].append(v)\n adj_dict[v].append(u)\n \n # O(V + E)\n queue = collections.deque([0])\n visited = {0}\n while queue:\n cur = queue.popleft()\n for neighbor in adj_dict[cur]:\n if neighbor in visited:\n continue\n visited.add(neighbor)\n queue.append(neighbor)\n\n return len(visited)", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number[]} restricted\n * @return {number}\n */\nvar reachableNodes = function(n, edges, restricted) {\n const adj = {};\n \n for (const [u, v] of edges) {\n if (adj[u]) {\n adj[u].add(v);\n } else {\n adj[u] = new Set().add(v);\n }\n if (adj[v]) {\n adj[v].add(u);\n } else {\n adj[v] = new Set().add(u);\n }\n }\n \n const restrictedSet = new Set(restricted);\n const visited = new Set();\n \n let ans = 0;\n \n function dfs(node) {\n if (restrictedSet.has(node) || visited.has(node)) {\n return;\n }\n \n ans++;\n visited.add(node);\n \n for (const adjNode of adj[node]) {\n dfs(adjNode);\n }\n }\n \n dfs(0);\n \n return ans;\n};", "solution_java": "class Solution {\n int count=0;\n ArrayList> adj=new ArrayList<>();\n public int reachableNodes(int n, int[][] edges, int[] restricted) {\n boolean[] vis=new boolean[n];\n for(int i:restricted){\n vis[i]=true;\n }\n for(int i=0;i());\n }\n for(int[] ii:edges){\n adj.get(ii[0]).add(ii[1]);\n adj.get(ii[1]).add(ii[0]);\n }\n dfs(0,vis);\n return count;\n }\n private void dfs(int node,boolean[] vis){\n vis[node]=true;\n count++;\n for(int it:adj.get(node)){\n if(vis[it]==false){\n dfs(it,vis);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int count=1; // node 0 is already reached as it is starting point\n vector> graph;\n unordered_set res; // to store restricted numbers for fast fetch\n vector vis; // visited array for DFS\n \n void dfs(int i){\n for(int y: graph[i]){\n if(!vis[y] && res.count(y)==0){\n vis[y]= true;\n dfs(y);\n count++;\n }\n }\n }\n \n int reachableNodes(int n, vector>& edges, vector& restricted) {\n for(int x:restricted) res.insert(x);\n \n // creating graph\n graph.resize(n);\n vis.resize(n);\n for(auto &x:edges){\n graph[x[0]].push_back(x[1]);\n graph[x[1]].push_back(x[0]);\n }\n \n // mark 0 as visited coz it is starting point and is already reached \n vis[0]= true;\n dfs(0);\n \n return count;\n }\n};" }, { "title": "Find Minimum in Rotated Sorted Array", "algo_input": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:\n\n\n\t[4,5,6,7,0,1,2] if it was rotated 4 times.\n\t[0,1,2,4,5,6,7] if it was rotated 7 times.\n\n\nNotice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n\nGiven the sorted rotated array nums of unique elements, return the minimum element of this array.\n\nYou must write an algorithm that runs in O(log n) time.\n\n \nExample 1:\n\nInput: nums = [3,4,5,1,2]\nOutput: 1\nExplanation: The original array was [1,2,3,4,5] rotated 3 times.\n\n\nExample 2:\n\nInput: nums = [4,5,6,7,0,1,2]\nOutput: 0\nExplanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\n\n\nExample 3:\n\nInput: nums = [11,13,15,17]\nOutput: 11\nExplanation: The original array was [11,13,15,17] and it was rotated 4 times. \n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 5000\n\t-5000 <= nums[i] <= 5000\n\tAll the integers of nums are unique.\n\tnums is sorted and rotated between 1 and n times.\n\n", "solution_py": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n if len(nums) == 1 or nums[0] < nums[-1]:\n return nums[0]\n \n l, r = 0, len(nums) - 1\n \n while l <= r:\n mid = l + (r - l) // 2\n \n if mid > 0 and nums[mid - 1] > nums[mid]:\n return nums[mid]\n \n\t\t\t# We compare the middle number and the right index number\n\t\t\t# but why we cannot compare it with the left index number?\n if nums[mid] > nums[r]:\n l = mid + 1\n else:\n r = mid - 1", "solution_js": "var findMin = function(nums) {\n let min = Math.min(...nums)\n return min;\n};", "solution_java": "class Solution {\n public int findMin(int[] nums)\n {\n int min=nums[0];\n\n for(int i=0;inums[i])\n {\n min=nums[i];\n }\n }\n return min;\n }\n}", "solution_c": "class Solution {\npublic:\n int findMin(vector& nums) {\n int result = -1;\n int first = nums[0];\n\n // check the array for rotated point when it is obtained break the loop and assign result as rotation point\n for(int i = 1; inums[i]){\n result = nums[i];\n break;\n }\n }\n // if the array is not sorted return first element\n if(result == -1) {\n return first;\n }\n return result;\n }\n};" }, { "title": "Reverse Bits", "algo_input": "Reverse bits of a given 32 bits unsigned integer.\n\nNote:\n\n\n\tNote that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\n\tIn Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.\n\n\n \nExample 1:\n\nInput: n = 00000010100101000001111010011100\nOutput: 964176192 (00111001011110000010100101000000)\nExplanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.\n\n\nExample 2:\n\nInput: n = 11111111111111111111111111111101\nOutput: 3221225471 (10111111111111111111111111111111)\nExplanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.\n\n\n \nConstraints:\n\n\n\tThe input must be a binary string of length 32\n\n\n \nFollow up: If this function is called many times, how would you optimize it?\n", "solution_py": "class Solution:\n# @param n, an integer\n# @return an integer\ndef reverseBits(self, n):\n res=0\n for i in range(32):\n bit=(n>>i)&1\n res=res|bit<<(31-i)\n return res", "solution_js": "/**\n * @param {number} n - a positive integer\n * @return {number} - a positive integer\n */\n\n// remember the binary must always be of length 32 ;);\nvar reverseBits = function(n) {\n const reversedBin = n.toString(2).split('').reverse().join('');\n const result = reversedBin.padEnd(32,'0'); \n return parseInt(result, 2);\n};", "solution_java": "public class Solution {\n // you need treat n as an unsigned value\n public int reverseBits(int n) {\n int mask = 0;\n int smask = 0;\n int j = 0;\n int rev = 0;\n \n // basically we are checking that the number is set bit or not \n // if the number is set bit then we are appending that to our main answer i.e, rev\n for(int i=31 ; i>=0 ; i--){\n mask = 1<>1;\n ans = ans<<1;\n i++;\n }\n if (i ==32){\n bit = n&1;\n ans = ans|bit;\n }\n return ans;\n }\n};" }, { "title": "Cat and Mouse", "algo_input": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\n\nThe graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.\n\nThe mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.\n\nDuring each player's turn, they must travel along one edge of the graph that meets where they are.  For example, if the Mouse is at node 1, it must travel to any node in graph[1].\n\nAdditionally, it is not allowed for the Cat to travel to the Hole (node 0.)\n\nThen, the game can end in three ways:\n\n\n\tIf ever the Cat occupies the same node as the Mouse, the Cat wins.\n\tIf ever the Mouse reaches the Hole, the Mouse wins.\n\tIf ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.\n\n\nGiven a graph, and assuming both players play optimally, return\n\n\n\t1 if the mouse wins the game,\n\t2 if the cat wins the game, or\n\t0 if the game is a draw.\n\n\n \nExample 1:\n\nInput: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput: 0\n\n\nExample 2:\n\nInput: graph = [[1,3],[0],[3],[0,2]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t3 <= graph.length <= 50\n\t1 <= graph[i].length < graph.length\n\t0 <= graph[i][j] < graph.length\n\tgraph[i][j] != i\n\tgraph[i] is unique.\n\tThe mouse and the cat can always move. \n\n", "solution_py": "class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n ", "solution_js": "var catMouseGame = function(graph) {\n let n=graph.length,\n memo=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2*n+1)])),\n seen=[...Array(n+1)].map(d=>[...Array(n+1)].map(d=>[...Array(2)]))\n //dfs returns 0 1 2, whether the current player loses,wins, or draws respectively\n let dfs=(M,C,level)=>{\n let turn=level%2,curr=turn?C:M,draw=0,res=0\n //draw when we ve seen the state before or cycles\n if(seen[M][C][turn]!==undefined||level>=2*n) \n return memo[M][C][level]=2 \n if(M==0)// win for mouse if it reaches the hole, loss for cat\n memo[M][C][level]=turn^1\n if(M==C)// win for cat if it reaches the mouse, loss for mouse\n memo[M][C][level]=turn \n if(memo[M][C][level]===undefined){\n seen[M][C][turn]=0 //set this state as visited\n for(let i=0;i2->0 \n }\n seen[M][C][turn]=undefined;// de-set the state for the current game,as it concluded\n return memo[M][C][level]\n }\n return [2,1,0][dfs(1,2,0)] //js eye candy\n};", "solution_java": "class Solution {\n int TIME_MAX = 200;\n int DRAW = 0;\n int MOUSE_WIN = 1;\n int CAT_WIN = 2;\n public int catMouseGame(int[][] graph) {\n return dfs(0, new int[]{1, 2}, graph, new Integer[TIME_MAX+1][graph.length][graph.length]);\n }\n\n private int dfs(int time, int[] p, int[][] graph, Integer[][][] memo){ // p[0] -> mouse position, p[1] -> cat position\n Integer old = memo[time][p[0]][p[1]];\n if (old != null) return old; // all the base cases here\n if (time >= TIME_MAX) return DRAW;\n if (p[0]==0) return MOUSE_WIN;\n if (p[0]==p[1]) return CAT_WIN;\n int state = 0;\n int where = p[time&1];\n int res = DRAW;\n for (int i = 0; i < graph[where].length; i++){\n if ((time&1)==0||graph[where][i]>0){ // if mouse turn or cat turn and the dest is not 0, do ...\n p[time&1]=graph[where][i];\n state |= 1 << dfs(time+1, p, graph, memo);\n if ((time&1)>0&&(state&4)>0 || (time&1)==0&&(state&2)>0) // if mouse's turn & mouse win\n break; // or cat's turn & cat win, then we stop.\n }\n }\n p[time&1]=where; // restore p\n if (((time&1)>0 && (state & 4)>0)||((time&1)==0) && state==4){\n res = CAT_WIN; // cat win when (cat's turn & cat win) or (mouse's turn and state = cat)\n }else if (((time&1)==0 && (state & 2)>0)||(time&1)==1 && state==2){\n res = MOUSE_WIN; // mouse win when (mouse's turn and mouse win) or (cat's turn and state = mouse)\n }\n return memo[time][p[0]][p[1]]=res;\n }\n}", "solution_c": "class Solution {\npublic:\n int catMouseGame(vector>& graph) {\n int N = graph.size();\n vector> dp[2];\n vector> outdegree[2];\n queue> q; // q of {turn, mouse position, cat position} for topological sort\n\n dp[0] = vector>(N, vector(N));\n dp[1] = vector>(N, vector(N));\n outdegree[0] = vector>(N, vector(N));\n outdegree[1] = vector>(N, vector(N));\n\n // init dp and queue\n for (int j = 0; j < N; ++j) {\n dp[0][0][j] = dp[1][0][j] = 1;\n q.push({0, 0, j});\n q.push({1, 0, j});\n }\n for (int j = 1; j < N; ++j) {\n dp[0][j][j] = dp[1][j][j] = 2;\n q.push({0, j, j});\n q.push({1, j, j});\n }\n // init outdegree\n for (int i = 0; i < N; ++i) {\n for (int j = 1; j < N; ++j) {\n outdegree[0][i][j] = graph[i].size();\n outdegree[1][i][j] = graph[j].size();\n }\n }\n for (auto &v : graph[0]) {\n for (int i = 0; i < N; ++i) {\n outdegree[1][i][v]--;\n }\n }\n // run the topological sort from queue\n while (q.size()) {\n auto turn = q.front()[0];\n auto mouse = q.front()[1];\n auto cat = q.front()[2];\n q.pop();\n\n if (turn == 0 && mouse == 1 && cat == 2) {\n // the result has been inferenced\n break;\n }\n\n if (turn == 0) { // mouse's turn\n // v is the prev position of cat\n for (auto &v : graph[cat]) {\n if (v == 0) {\n continue;\n }\n\n if (dp[1][mouse][v] > 0) {\n continue;\n }\n\n if (dp[turn][mouse][cat] == 2) {\n // cat wants to move from v to `cat` position, and thus cat wins\n dp[1][mouse][v] = 2;\n q.push({1, mouse, v});\n continue;\n }\n\n outdegree[1][mouse][v]--;\n if (outdegree[1][mouse][v] == 0) {\n dp[1][mouse][v] = 1;\n q.push({1, mouse, v});\n }\n }\n } else { // cat's turn\n // v is the prev position of mouse\n for (auto &v : graph[mouse]) {\n if (dp[0][v][cat] > 0) {\n continue;\n }\n\n if (dp[turn][mouse][cat] == 1) {\n // mouse wants to move from v to `mouse` position and thus mouse wins\n dp[0][v][cat] = 1;\n q.push({0, v, cat});\n continue;\n }\n\n outdegree[0][v][cat]--;\n if (outdegree[0][v][cat] == 0) {\n dp[0][v][cat] = 2;\n q.push({0, v, cat});\n }\n }\n }\n }\n\n return dp[0][1][2];\n }\n};" }, { "title": "Find Good Days to Rob the Bank", "algo_input": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time.\n\nThe ith day is a good day to rob the bank if:\n\n\n\tThere are at least time days before and after the ith day,\n\tThe number of guards at the bank for the time days before i are non-increasing, and\n\tThe number of guards at the bank for the time days after i are non-decreasing.\n\n\nMore formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time].\n\nReturn a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.\n\n \nExample 1:\n\nInput: security = [5,3,3,3,5,6,2], time = 2\nOutput: [2,3]\nExplanation:\nOn day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.\n\n\nExample 2:\n\nInput: security = [1,1,1,1,1], time = 0\nOutput: [0,1,2,3,4]\nExplanation:\nSince time equals 0, every day is a good day to rob the bank, so return every day.\n\n\nExample 3:\n\nInput: security = [1,2,3,4,5,6], time = 2\nOutput: []\nExplanation:\nNo day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.\n\n\n \nConstraints:\n\n\n\t1 <= security.length <= 105\n\t0 <= security[i], time <= 105\n\n", "solution_py": "class Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n decreasing = [0] * len(security)\n increasing = [0] * len(security)\n for i in range(len(security)):\n if i > 0 and security[i - 1] >= security[i]:\n decreasing[i] = decreasing[i - 1] + 1\n for i in reversed(range(len(security))):\n if i < len(security) - 1 and security[i] <= security[i + 1]:\n increasing[i] = increasing[i + 1] + 1\n return [i for i in range(len(security)) if increasing[i] >= time and decreasing[i] >= time]", "solution_js": "var goodDaysToRobBank = function(security, time) {\n let res = [];\n if(!time){\n let i = 0;\n while(isecurity[i-1]) decreasing = 0;\n else decreasing++;\n if(security[i]=time) set.add(i);\n if(increasing>=time&&set.has(i-time)) res.push(i-time);\n }\n return res;\n};", "solution_java": "class Solution {\n public List goodDaysToRobBank(int[] security, int time) {\n List res = new ArrayList<>();\n if (time == 0) {\n for (int i = 0; i < security.length; i++) res.add(i);\n return res;\n }\n Set set = new HashSet<>();\n int count = 1;\n for (int i = 1; i < security.length; i++) {\n if (security[i] <= security[i - 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time) {\n set.add(i);\n }\n }\n \n count = 1;\n for (int i = security.length - 2; i >= 0; i--) {\n if (security[i] <= security[i + 1]) {\n count++;\n } else {\n count = 1;\n }\n if (count > time && set.contains(i)) res.add(i);\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector goodDaysToRobBank(vector& security, int time) {\n int n = security.size();\n vector prefix(n), suffix(n);\n vector ans;\n \n prefix[0] = 0;\n for(int i=1;i=0;i--) {\n if(security[i] <= security[i+1]) suffix[i] = suffix[i+1]+1;\n else suffix[i] = 0;\n }\n \n for(int i=0;i=time && suffix[i]>=time) ans.push_back(i);\n }\n \n return ans;\n }\n};" }, { "title": "Stone Game VI", "algo_input": "Alice and Bob take turns playing a game, with Alice starting first.\n\nThere are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.\n\nYou are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.\n\nThe winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.\n\nDetermine the result of the game, and:\n\n\n\tIf Alice wins, return 1.\n\tIf Bob wins, return -1.\n\tIf the game results in a draw, return 0.\n\n\n \nExample 1:\n\nInput: aliceValues = [1,3], bobValues = [2,1]\nOutput: 1\nExplanation:\nIf Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.\n\n\nExample 2:\n\nInput: aliceValues = [1,2], bobValues = [3,1]\nOutput: 0\nExplanation:\nIf Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.\n\n\nExample 3:\n\nInput: aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput: -1\nExplanation:\nRegardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.\n\n\n \nConstraints:\n\n\n\tn == aliceValues.length == bobValues.length\n\t1 <= n <= 105\n\t1 <= aliceValues[i], bobValues[i] <= 100\n\n", "solution_py": "class Solution:\n def stoneGameVI(self, A, B):\n G = [a+b for a,b in zip(A,B)]\n G.sort()\n L = len(A)\n d = -sum(B) + sum( G[i] for i in range(L-1,-1,-2) )\n return 1 if d>0 else ( -1 if d<0 else 0 )", "solution_js": "var stoneGameVI = function(aliceValues, bobValues) {\n let aliceVal = 0\n let bobVal = 0\n let turn = true\n const combined = {}\n let n = aliceValues.length\n for (let i = 0; i < n; i++) {\n if (combined[aliceValues[i] + bobValues[i]]) {\n combined[aliceValues[i] + bobValues[i]].push({value: aliceValues[i] + bobValues[i], id: i})\n } else {\n combined[aliceValues[i] + bobValues[i]] = [{value: aliceValues[i] + bobValues[i], id: i}]\n }\n }\n Object.values(combined).reverse().forEach((value) => {\n value.forEach(val => {\n if (turn) {\n aliceVal += aliceValues[val.id]\n } else {\n bobVal += bobValues[val.id]\n }\n turn = !turn\n })\n })\n if (aliceVal === bobVal) return 0\n return aliceVal > bobVal ? 1 : -1\n};", "solution_java": "class Solution \n{\nstatic class Pair\n{\n int sum=0;\n int alice=0;\n int bob=0;\n public Pair(int sum,int alice, int bob)\n{\n this.sum=sum;\n\tthis.alice = alice;\n\tthis.bob = bob;\n}\n}\n\n// class to define user defined conparator\nstatic class Compare {\n\t\n\tstatic void compare(Pair arr[], int n)\n\t{\n\t\t// Comparator to sort the pair according to second element\n\t\tArrays.sort(arr, new Comparator() {\n\t\t\t@Override public int compare(Pair p1, Pair p2)\n\t\t\t{\n\t\t\t\treturn p2.sum - p1.sum;\n\t\t\t}\n\t\t});\n\t\t\n\t\t\n\t}\n}\n public int stoneGameVI(int[] aliceValues, int[] bobValues)\n {\n int n=aliceValues.length;\n Pair[] a=new Pair[n];\n for(int i=0;i alice, bob;\n\nstruct myComp {\n bool operator()(pair& a, pair& b){\n return alice[a.second] + bob[a.second] < alice[b.second] + bob[b.second];\n }\n};\n\nclass Solution {\npublic:\n int stoneGameVI(vector& aliceValues, vector& bobValues) {\n alice = aliceValues;\n bob = bobValues;\n priority_queue, vector>, myComp> a,b;\n\n for(int i=0;i ans2) return 1;\n return -1;\n }\n};" }, { "title": "Find the Student that Will Replace the Chalk", "algo_input": "There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.\n\nYou are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.\n\nReturn the index of the student that will replace the chalk.\n\n \nExample 1:\n\nInput: chalk = [5,1,5], k = 22\nOutput: 0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.\n\nExample 2:\n\nInput: chalk = [3,4,1,2], k = 25\nOutput: 1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.\n\n\n \nConstraints:\n\n\n\tchalk.length == n\n\t1 <= n <= 105\n\t1 <= chalk[i] <= 105\n\t1 <= k <= 109\n\n", "solution_py": "class Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x r + c, 0);\n \n k %= sum;\n \n for (let i = 0; i < chalk.length; i++) {\n if (chalk[i] > k) {\n return i;\n }\n\n k -= chalk[i];\n }\n};", "solution_java": "class Solution {\n\npublic int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for (int c : chalk) {\n sum += c;\n }\n long left = k % sum; \n for (int i = 0; i < chalk.length; i++){\n if(left >= chalk[i]){ \n left -= chalk[i];\n } else { \n return i;\n }\n }\n return -1; //just for return statement, put whatever you want here\n}\n}", "solution_c": "class Solution {\npublic:\n // T(n) = O(n) S(n) = O(1) \n int chalkReplacer(vector& chalk, int k) {\n // Size of the vector\n int n = chalk.size();\n // Store the sum of the elements in the vector\n long sum = 0;\n // Calculate the sum of the elements \n for (int n : chalk) sum += n;\n // Update k as the remainder of the sum \n // to make sure that the while loop\n\t\t// will traverse the vector at most 1 time\n k = k % sum;\n // Start from the initial value in the array\n int idx = 0;\n // While the next student has enough chalk\n while (k >= chalk[idx]) {\n // Decrease the remaining chalk\n k -= chalk[idx];\n // Increase the index\n idx = (idx + 1) % n;\n }\n // Return the index of the student without\n // enough chalk\n return idx;\n }\n};" }, { "title": "Largest Merge Of Two Strings", "algo_input": "You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options:\n\n\n\tIf word1 is non-empty, append the first character in word1 to merge and delete it from word1.\n\n\t\n\t\tFor example, if word1 = \"abc\" and merge = \"dv\", then after choosing this operation, word1 = \"bc\" and merge = \"dva\".\n\t\n\t\n\tIf word2 is non-empty, append the first character in word2 to merge and delete it from word2.\n\t\n\t\tFor example, if word2 = \"abc\" and merge = \"\", then after choosing this operation, word2 = \"bc\" and merge = \"a\".\n\t\n\t\n\n\nReturn the lexicographically largest merge you can construct.\n\nA string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c.\n\n \nExample 1:\n\nInput: word1 = \"cabaa\", word2 = \"bcaaa\"\nOutput: \"cbcabaaaaa\"\nExplanation: One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.\n\n\nExample 2:\n\nInput: word1 = \"abcabc\", word2 = \"abdcaba\"\nOutput: \"abdcabcabcaba\"\n\n\n \nConstraints:\n\n\n\t1 <= word1.length, word2.length <= 3000\n\tword1 and word2 consist only of lowercase English letters.\n\n", "solution_py": "class Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n res = ''\n p1 = 0\n p2 = 0\n while p1 < len(word1) and p2 < len(word2):\n if word1[p1:] > word2[p2:]:\n res += word1[p1]\n p1 += 1\n else:\n res += word2[p2]\n p2 += 1\n \n res += word1[p1:] + word2[p2:]\n\n \n return res", "solution_js": "var largestMerge = function(word1, word2) {\n let ans = '';\n let w1 = 0, w2 = 0;\n\n while(w1 < word1.length && w2 < word2.length) {\n if(word1[w1] > word2[w2]) ans += word1[w1++];\n else if(word2[w2] > word1[w1]) ans += word2[w2++];\n else {\n const rest1 = word1.slice(w1);\n const rest2 = word2.slice(w2);\n\n if(rest1 > rest2) ans += word1[w1++];\n else ans += word2[w2++];\n }\n }\n ans += word1.slice(w1);\n ans += word2.slice(w2);\n return ans;\n};", "solution_java": "class Solution {\n public String largestMerge(String word1, String word2) {\n StringBuilder sb = new StringBuilder();\n int i=0;\n int j=0;\n char[] w1 = word1.toCharArray();\n char[] w2 = word2.toCharArray();\n \n int n1=w1.length;\n int n2=w2.length;\n \n // we loop until we exhaust any one of the 2 words completely\n while(iw2[j]){\n sb.append(w1[i++]);\n }else{\n sb.append(w2[j++]);\n }\n }\n \n // at the end of the loop we append any remaining word\n sb.append(word1.substring(i));\n sb.append(word2.substring(j));\n\t\t\n return sb.toString();\n }\n \n private boolean check(char[] w1, int i, char[] w2, int j){\n // will return true if we need to extract from word1 and false if we need to extract from word2\n \n while(iw2[j]){\n return true;\n }else{\n return false;\n }\n }\n \n // if we are unable to find any exhaustable character till the end of the loop we use the one having larger length\n if(i=word2) {ans+=word1[0];word1=word1.substr(1);}\n \n else {ans+=word2[0];word2=word2.substr(1);}\n }\n \n if(word1.size()!=0)ans=ans+word1;\n if(word2.size()!=0)ans=ans+word2;\n \n return ans;\n }\n};" }, { "title": "Perfect Number", "algo_input": "A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.\n\nGiven an integer n, return true if n is a perfect number, otherwise return false.\n\n \nExample 1:\n\nInput: num = 28\nOutput: true\nExplanation: 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.\n\n\nExample 2:\n\nInput: num = 7\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= num <= 108\n\n", "solution_py": "class Solution:\n def checkPerfectNumber(self, num: int) -> bool:\n sum = 0\n root = num**0.5 \n if num ==1:\n return False\n for i in range(2,int(root)+1):\n if num%i== 0:\n sum +=(num//i)+i\n return sum+1 == num", "solution_js": " /**\n * @param {number} num\n * @return {boolean}\n */\nvar checkPerfectNumber = function(num) {\n let total = 0\n\n for(let i = 1 ; i < num;i++){\n if(num % i == 0){\n total += i\n }\n }\n return total == num ? true : false\n};", "solution_java": "class Solution {\n public boolean checkPerfectNumber(int num) {\n if(num==1)\n return false;\n\n int sum = 1;\n for(int i=2; isqrt(num) so tto include that factor we'll add num/i; for ex if we have 64 as number than 8 is sqrt but 16 and 32 also divides 64 but our loop won't consider that case; so we are adding num/i, which means with 2 we are adding 32 and with 4 we are adding 16.\n sum += i + num/i;\n }\n }\n }\n if(sum==num && num!=1){\n return true;\n }\n return false;\n }\n};" }, { "title": "Making File Names Unique", "algo_input": "Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].\n\nSince two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\n\nReturn an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n\n \nExample 1:\n\nInput: names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput: [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation: Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"\n\n\nExample 2:\n\nInput: names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput: [\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation: Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"\n\n\nExample 3:\n\nInput: names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput: [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation: When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".\n\n\n \nConstraints:\n\n\n\t1 <= names.length <= 5 * 104\n\t1 <= names[i].length <= 20\n\tnames[i] consists of lowercase English letters, digits, and/or round brackets.\n\n", "solution_py": "class Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # Hashmap will store the name as key and the number of times that name has duplicated so fas as value.\n hashmap = {}\n\n for name in names:\n modified = name\n # Check whether the name has already been used\n if name in hashmap:\n # Get the number of times the {name} has been used\n k = hashmap[name]\n # Calculate the next available suffix.\n while modified in hashmap:\n k += 1\n modified = f'{name}({k})'\n # Update the number of times the original {name} is used. This will help to efficiently check for next available suffix if the {name} again comes in future.\n hashmap[name] = k\n # Store the modified {name} with 0 as it is not duplicated yet.\n hashmap[modified] = 0\n\n # Return the keys of hashmap as that would be the unique file names.\n return hashmap.keys()", "solution_js": "/**\n * @param {string[]} names\n * @return {string[]}\n */\nvar getFolderNames = function(names) {\n // save existed folder names\n let hashMap = new Map();\n for(let name of names) {\n let finalName = name;\n // next smallest suffix number\n // if this name is not present in the map, next smallest suffix will be 1\n let number = hashMap.get(name) || 1;\n if(hashMap.has(name)) {\n // append suffix to original name\n finalName += '(' + number +')';\n // find the smallest suffix that hasn't been used before\n while(hashMap.has(finalName)) {\n number++;\n // try to use new suffix to update name\n finalName = name + '(' + number +')';\n }\n // update next smallest suffix number of new name\n hashMap.set(finalName, 1);\n }\n // update next smallest suffix number of original name\n hashMap.set(name, number);\n }\n return Array.from(hashMap.keys());\n};", "solution_java": "class Solution {\n Map map = new HashMap<>();\n \n public String[] getFolderNames(String[] names) {\n String[] op = new String[names.length];\n int i = 0;\n \n for(String cur : names){\n if(map.containsKey(cur)) {\n cur = generateCopyName(cur);\n op[i++] = cur;\n // System.out.println(map.toString());\n continue;\n }\n \n op[i++] = cur;\n map.put(cur, 0);\n // System.out.println(map.toString());\n }\n \n return op;\n }\n \n private String generateCopyName(String s) {\n int count = map.get(s) + 1;\n \n String postfix = \"(\" + count + \")\";\n StringBuilder sb = new StringBuilder(s);\n sb.append(postfix);\n \n boolean isChanged = false;\n while(map.containsKey(sb.toString())) {\n sb = new StringBuilder(s);\n sb.append(\"(\" + count + \")\");\n count++;\n isChanged = true;\n }\n String res = sb.toString();\n //System.out.println(res);\n \n \n if(isChanged)\n count = count -1;\n \n map.put(s, count);\n map.put(res, 0);\n \n return res;\n }\n}", "solution_c": "class Solution {\n \n unordered_map next_index_;\n \n bool contain(const string& fn) {\n return next_index_.find(fn) != next_index_.end();\n }\n \n string get_name(string fn) {\n if (!contain(fn)) {\n next_index_.insert({fn, 1});\n return fn;\n }\n \n int idx = next_index_[fn];\n auto cur = fn;\n while (contain(cur)) {\n next_index_.insert({cur, 1});\n cur = fn + \"(\" + to_string(idx) + \")\";\n ++idx;\n }\n next_index_.insert({cur, 1});\n next_index_[fn] = idx;\n return cur;\n }\n \npublic:\n vector getFolderNames(vector& names) {\n vector res;\n for (auto& n : names) {\n res.push_back(get_name(n));\n }\n \n return res;\n }\n};" }, { "title": "Subdomain Visit Count", "algo_input": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly.\n\nA count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.\n\n\n\tFor example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.\n\n\nGiven an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.\n\n \nExample 1:\n\nInput: cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput: [\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation: We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.\n\n\nExample 2:\n\nInput: cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput: [\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation: We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.\n\n\n \nConstraints:\n\n\n\t1 <= cpdomain.length <= 100\n\t1 <= cpdomain[i].length <= 100\n\tcpdomain[i] follows either the \"repi d1i.d2i.d3i\" format or the \"repi d1i.d2i\" format.\n\trepi is an integer in the range [1, 104].\n\td1i, d2i, and d3i consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n output, ans = {}, []\n for domain in cpdomains : \n number, domain = domain.split(' ')\n sub_domain = domain.split('.')\n pair = ''\n print(sub_domain)\n for i in reversed(range(len(sub_domain))) :\n if i == len(sub_domain)-1 : \n pair += sub_domain[i]\n else : \n pair = sub_domain[i] +'.'+ pair \n print(pair)\n \n # output.append(str(number) + ' '+pair)\n if pair not in output.keys() : \n output[pair] = int(number)\n else : \n output[pair] += int(number)\n \n for key in output.keys() : \n ans.append(str(output[key]) + ' '+key)\n \n return ans", "solution_js": "/**\n * @param {string[]} cpdomains\n * @return {string[]}\n */\nvar subdomainVisits = function(cpdomains) {\n let map = {}\n cpdomains.forEach(d => {\n let data = d.split(\" \");\n let arr = data[1].split(\".\")\n while(arr.length > 0) {\n if(arr.join(\".\") in map) map[arr.join(\".\")]+=+data[0]\n else map[arr.join(\".\")] = +data[0]\n arr.shift()\n }\n })\n let result = []\n for(let key in map) result.push(map[key] + \" \"+ key)\n return result\n};", "solution_java": "class Solution {\n public List subdomainVisits(String[] cpdomains) {\n List result = new LinkedList<>();\n HashMap hmap = new HashMap<>();\n \n for(int i = 0; i < cpdomains.length; i++){\n String[] stringData = cpdomains[i].split(\" \");\n String[] str = stringData[1].split(\"\\\\.\");\n String subDomains = \"\";\n \n for(int j = str.length-1; j >= 0; j--){\n subDomains = str[j] + subDomains;\n \n if(!hmap.containsKey(subDomains))\n hmap.put(subDomains, Integer.parseInt(stringData[0]));\n else\n hmap.put(subDomains, hmap.get(subDomains) + Integer.parseInt(stringData[0]));\n subDomains = \".\" + subDomains;\n }\n \n }\n \n for(Map.Entry entry: hmap.entrySet()){\n result.add(entry.getValue() + \" \" + entry.getKey());\n }\n \n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector subdomainVisits(vector& cpdomains) {\n vector v;\n unordered_map m;\n for(auto it : cpdomains){\n string rep=\"\";\n int i=0;\n while(it[i]!=' '){\n rep+=(it[i]);\n i++;\n }\n int r=stoi(rep);\n m[it.substr(i+1,it.size())]+=r;\n\n while(it[i]!='.'){\n i++;\n }\n m[it.substr(i+1,it.size())]+=r;\n i++;\n while(i int:\n stack = [] \n for i in tokens:\n if i == \"+\":\n stack[-1] = stack[-2] + stack.pop()\n elif i == \"-\":\n stack[-1] = stack[-2] - stack.pop()\n elif i == \"*\":\n stack[-1] = stack[-2] * stack.pop()\n elif i == \"/\":\n stack[-1] = int(stack[-2] / stack.pop())\n else:\n stack.append(int(i))\n \n return stack.pop()\n ", "solution_js": "const ops = new Set(['+', '-', '*', '/']);\n\n/**\n * @param {string[]} tokens\n * @return {number}\n */\nvar evalRPN = function(tokens) {\n const stack = [];\n\n for (const token of tokens) {\n if (!ops.has(token)) {\n stack.push(Number(token));\n continue;\n }\n\n const val1 = stack.pop();\n const val2 = stack.pop();\n let toPush;\n\n if (token === '+') {\n toPush = val1 + val2;\n }\n\n if (token === '-') {\n toPush = val2 - val1;\n }\n\n if (token === '*') {\n toPush = val1 * val2;\n }\n\n if (token === '/') {\n toPush = Math.trunc(val2 / val1);\n }\n\n stack.push(toPush);\n }\n\n return stack[0] || 0;\n};", "solution_java": "class Solution {\n public int evalRPN(String[] tokens) {\n Stack stack = new Stack();\n for(String i: tokens){\n if(i.equals(\"+\") || i.equals(\"-\") || i.equals(\"*\") || i.equals(\"/\")){\n int a = stack.pop();\n int b = stack.pop();\n int temp = 0;\n if(i.equals(\"+\"))\n temp = a+b;\n else if(i.equals(\"-\"))\n temp = b-a;\n else if(i.equals(\"*\"))\n temp = a*b;\n else if(i.equals(\"/\"))\n temp = b/a;\n stack.push(temp);\n }\n else\n stack.push(Integer.parseInt(i));\n }\n return stack.pop();\n }\n}", "solution_c": "class Solution {\npublic:\n int stoi(string s){\n int n = 0;\n int i = 0;\n bool neg = false;\n if(s[0] == '-'){\n i++;\n neg = true;\n }\n for(; i < s.size(); i++){\n n = n*10 + (s[i]-'0');\n }\n if(neg) n = -n;\n return n;\n }\n int evalRPN(vector& tokens) {\n stacks;\n int n = tokens.size();\n for(int i = 0; i < n; i++){\n string str = tokens[i];\n if(str == \"*\"){\n int n1 = s.top();\n s.pop();\n int n2 = s.top();\n s.pop();\n int res = n2*n1;\n s.push(res);\n }\n else if(str == \"+\") {\n int n1 = s.top();\n s.pop();\n int n2 = s.top();\n s.pop();\n int res = n2+n1;\n s.push(res);\n }\n else if(str == \"/\"){\n int n1 = s.top();\n s.pop();\n int n2 = s.top();\n s.pop();\n int res = n2/n1;\n s.push(res);\n }\n else if(str == \"-\"){\n int n1 = s.top();\n s.pop();\n int n2 = s.top();\n s.pop();\n int res = n2-n1;\n s.push(res);\n }\n else{\n int num = stoi(str);\n s.push(num);\n }\n }\n return s.top();\n }\n};" }, { "title": "Find Minimum Time to Finish All Jobs", "algo_input": "You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.\n\nThere are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\n\nReturn the minimum possible maximum working time of any assignment. \n\n \nExample 1:\n\nInput: jobs = [3,2,3], k = 3\nOutput: 3\nExplanation: By assigning each person one job, the maximum time is 3.\n\n\nExample 2:\n\nInput: jobs = [1,2,4,7,8], k = 2\nOutput: 11\nExplanation: Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.\n\n \nConstraints:\n\n\n\t1 <= k <= jobs.length <= 12\n\t1 <= jobs[i] <= 107\n\n", "solution_py": "class Solution:\n \n def dfs(self, pos: int, jobs: List[int], workers: List[int]) -> int:\n if pos >= len(jobs):\n return max(workers)\n \n mn = float(\"inf\")\n # we keep track of visited here to skip workers\n # with the same current value of assigned work\n\t\t# this is an important step in pruning the number\n\t\t# of workers to explore\n visited = set()\n for widx in range(len(workers)):\n \n if workers[widx] in visited:\n continue\n visited.add(workers[widx])\n \n # try this worker\n workers[widx] += jobs[pos]\n \n if max(workers) < mn:\n # if it's better than our previous proceed\n res = self.dfs(pos+1, jobs, workers)\n mn = min(mn, res)\n \n # backtrack\n workers[widx] -= jobs[pos]\n \n return mn\n \n \n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n\t # sorting the jobs means that highest value jobs are assigned first\n\t\t# and more computations can be skipped by pruning\n jobs.sort(reverse=True)\n return self.dfs(0, jobs, [0] * k)", "solution_js": "var minimumTimeRequired = function(jobs, k) {\n let n=jobs.length, maskSum=[...Array(1<0)\n for(let mask=0;mask<(1<[...Array(1<Infinity))\n dp[0][0]=0\n for(let i=1;i<=k;i++) //for each new person\n for(let curmask=0;curmask<(1<= result)\n return;\n for (int i=0; i 0 && workers[i] == workers[i-1])\n continue;\n // make choice\n workers[i] += jobs[current];\n // backtrack\n backtrack(jobs, current-1, workers);\n // undo the choice\n workers[i] -= jobs[current];\n }\n }\n \n \n}", "solution_c": "class Solution {\npublic:\n int minimumTimeRequired(vector& jobs, int k) {\n int sum = 0;\n for(int j:jobs)\n sum += j;\n sort(jobs.begin(),jobs.end(),greater());\n int l = jobs[0], r = sum;\n while(l>1;\n vector worker(k,0);\n if(dfs(jobs,worker,0,mid))\n r = mid;\n else\n l = mid + 1;\n }\n return l;\n }\n bool dfs(vector& jobs, vector& worker, int step, int target){\n if(step>=jobs.size())\n return true;\n int cur = jobs[step];\n // assign cur to worker i\n for(int i=0;i List[int]:\n\t\tinorder = []\n\t\tstack = []\n\n\t\twhile stack or root is not None:\n\t\t\tif root:\n\t\t\t\tstack.append(root)\n\t\t\t\troot = root.left\n\t\t\telse:\n\t\t\t\tnode = stack.pop()\n\t\t\t\tinorder.append(node.val)\n\t\t\t\troot = node.right\n\n\t\treturn inorder\n\n\nclass Solution:\n\t\"\"\"\n\tTime: O(n)\n\t\"\"\"\n\n\tdef inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n\t\treturn list(self.inorder_generator(root))\n\n\t@classmethod\n\tdef inorder_generator(cls, tree: Optional[TreeNode]):\n\t\tif tree is not None:\n\t\t\tyield from cls.inorder_generator(tree.left)\n\t\t\tyield tree.val\n\t\t\tyield from cls.inorder_generator(tree.right)", "solution_js": "var inorderTraversal = function(root) {\n let result = [];\n function traverse(node) {\n if(!node) {\n return;\n }\n traverse(node.left);\n result.push(node.val);\n traverse(node.right);\n }\n traverse(root);\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 List li = new LinkedList();\n public List inorderTraversal(TreeNode root) {\n if(root == null){\n List li = new LinkedList();\n return li ;\n }\n inorderTraversal(root.left); \n li.add(root.val); \n inorderTraversal(root.right);\n return li;\n\n }\n \n}", "solution_c": "class Solution {\npublic:\n vector v;\n vector inorderTraversal(TreeNode* root) {\n if(root!=NULL){\n inorderTraversal(root->left);\n v.push_back(root->val);\n inorderTraversal(root->right); \n }\n return v;\n }\n};" }, { "title": "Implement Trie (Prefix Tree)", "algo_input": "A trie (pronounced as \"try\") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.\n\nImplement the Trie class:\n\n\n\tTrie() Initializes the trie object.\n\tvoid insert(String word) Inserts the string word into the trie.\n\tboolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.\n\tboolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.\n\n\n \nExample 1:\n\nInput\n[\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n[[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]\nOutput\n[null, null, true, false, true, null, true]\n\nExplanation\nTrie trie = new Trie();\ntrie.insert(\"apple\");\ntrie.search(\"apple\"); // return True\ntrie.search(\"app\"); // return False\ntrie.startsWith(\"app\"); // return True\ntrie.insert(\"app\");\ntrie.search(\"app\"); // return True\n\n\n \nConstraints:\n\n\n\t1 <= word.length, prefix.length <= 2000\n\tword and prefix consist only of lowercase English letters.\n\tAt most 3 * 104 calls in total will be made to insert, search, and startsWith.\n\n", "solution_py": "class Node : \n def __init__(self ):\n self.child = {} # to hold the nodes.\n self.end = False # to mark a node if it is the end node or not.\n\nclass Trie:\n \n def __init__(self):\n self.root = Node()\n\n def insert(self, word:str) -> None:\n # time compl len(word)\n \n sz = len(word) \n temp = self.root # to hold the root node.\n \n for ind , i in enumerate( word ) :\n if i in temp.child.keys() : # if this curr char in the current node.\n temp = temp.child[i] #another node.\n \n else:\n temp.child[i] = Node()\n temp = temp.child[i]\n\n \n if ind == sz - 1 :\n temp.end = True \n \n \n\n def search(self, word: str) -> bool:\n \n temp = self.root \n for i in word : \n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n \n return temp.end == True \n \n def startsWith(self, prefix: str) -> bool:\n temp = self.root \n for i in prefix :\n if i in temp.child.keys():\n temp = temp.child[i]\n else:\n return 0\n return 1 ", "solution_js": "var Trie = function() {\n this.children = {};\n this.word = false;\n};\n\n/**\n * @param {string} word\n * @return {void}\n */\nTrie.prototype.insert = function(word) {\n if (!word) {\n this.word = true;\n return null;\n }\n let head = word[0];\n let tail = word.substring(1);\n\n if (!this.children[head]) {\n this.children[head] = new Trie();\n }\n this.children[head].insert(tail);\n};\n\n/**\n * @param {string} word\n * @return {boolean}\n */\nTrie.prototype._search = function(word, method) {\n if (!word) {\n if (method === 'search') {\n return this.word;\n } else {\n return true;\n }\n }\n let head = word[0];\n let tail = word.substring(1);\n\n if (!this.children[head]) {\n return false;\n }\n\n return this.children[head][method](tail);\n};\n\n/**\n * @param {string} word\n * @return {boolean}\n */\nTrie.prototype.search = function(word) {\n return this._search(word, 'search');\n};\n\n/**\n * @param {string} prefix\n * @return {boolean}\n */\nTrie.prototype.startsWith = function(prefix) {\n return this._search(prefix, 'startsWith');\n};\n\n/**\n * Your Trie object will be instantiated and called as such:\n * var obj = new Trie()\n * obj.insert(word)\n * var param_2 = obj.search(word)\n * var param_3 = obj.startsWith(prefix)\n */", "solution_java": "class Trie {\n private class Node{\n char character;\n Node[] sub;\n Node(char c){\n this.character = c;\n sub = new Node[26];\n }\n }\n Node root;\n HashMap map;\n public Trie() {\n root = new Node('\\0');\n map = new HashMap<>();\n }\n\n public void insert(String word) {\n Node temp = root;\n for(char c : word.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n temp.sub[index] = new Node(c);\n\n temp = temp.sub[index];\n }\n map.put(word, true);\n }\n\n public boolean search(String word) {\n return map.containsKey(word);\n }\n\n public boolean startsWith(String prefix) {\n Node temp = root;\n for(char c : prefix.toCharArray()){\n int index = c-'a';\n if(temp.sub[index] == null)\n return false;\n temp = temp.sub[index];\n }\n return true;\n }\n}", "solution_c": "class Trie {\npublic:\n struct tr {\n bool isword;\n vector next;\n tr() {\n next.resize(26, NULL); // one pointer for each character\n isword = false;\n }\n };\n \n tr *root;\n Trie() {\n root = new tr();\n }\n \n void insert(string word) {\n tr *cur = root;\n \n for(auto c: word) {\n\t\t\t// if pointer to char doesn't exist create one\n if(cur->next[c-'a'] == NULL) {\n cur->next[c-'a'] = new tr();\n }\n cur = cur->next[c-'a'];\n }\n \n\t\t// set as end or valid word\n cur->isword = true;\n }\n \n bool search(string word) {\n tr *cur = root;\n \n for(auto c: word) {\n\t\t\t// if pointer to char doesn't exist then word is not present\n if(cur->next[c-'a'] == NULL) {\n return false;\n }\n \n cur = cur->next[c-'a'];\n }\n \n\t\t// check if it is prefix or a word\n if(cur->isword){\n return true;\n }\n return false;\n }\n \n\t// similar to search \n\t// here we don't check if it is end or not\n bool startsWith(string prefix) {\n tr *cur = root;\n \n for(auto c: prefix) {\n if(cur->next[c-'a'] == NULL) {\n return false;\n }\n \n cur = cur->next[c-'a'];\n }\n\n return true;\n }\n};\n\n/**\n * Your Trie object will be instantiated and called as such:\n * Trie* obj = new Trie();\n * obj->insert(word);\n * bool param_2 = obj->search(word);\n * bool param_3 = obj->startsWith(prefix);\n */" }, { "title": "Minimum Degree of a Connected Trio in a Graph", "algo_input": "You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.\n\nA connected trio is a set of three nodes where there is an edge between every pair of them.\n\nThe degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\n\nReturn the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.\n\n \nExample 1:\n\nInput: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput: 3\nExplanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n\n\nExample 2:\n\nInput: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput: 0\nExplanation: There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.\n\n\n \nConstraints:\n\n\n\t2 <= n <= 400\n\tedges[i].length == 2\n\t1 <= edges.length <= n * (n-1) / 2\n\t1 <= ui, vi <= n\n\tui != vi\n\tThere are no repeated edges.\n\n", "solution_py": "class Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n result = n ** 2 # placeholder value\n adj = [set() for _ in range(n + 1)]\n visited = set()\n for edge in edges:\n adj[edge[0]].add(edge[1])\n adj[edge[1]].add(edge[0])\n for first in range(1, n + 1): # iterate through every node\n for second in adj[first]: # iterate through every neighbor of the first node\n e1 = tuple(sorted((first, second)))\n if e1 in visited:\n continue\n visited.add(e1) # mark e1 (first -> second) as visited because we don't want to visit (second -> first) again\n for third in adj[second]:\n if third == first: # skip if the third node is the first node (we need the first node to be its neighbor rather than itself!)\n continue\n e2 = tuple(sorted((first, third)))\n if first in adj[third]: # we don't check if e2 is in visited because the third node is not the current node being explored\n visited.add(e2) # we need to mark e2 as visited because one end of e2 is the first node and if we have checked (third -> first), we don't need to check (first -> third) again\n degree = len(adj[first]) - 2 + len(adj[second]) - 2 + len(adj[third]) - 2\n result = min(result, degree)\n return -1 if result == n ** 2 else result", "solution_js": "var minTrioDegree = function(n, edges) {\n // create an adjacency list of all the edges;\n const adjacencyList = new Array(n + 1).fill(0).map(() => new Set());\n for (const [x, y] of edges) {\n adjacencyList[x].add(y);\n adjacencyList[y].add(x);\n }\n\n let minimumDegree = Infinity;\n\n // Find all the combinations of 3 vertices that connect\n // and if they connect calculate the degree\n for (let i = 1; i <= n; i++) {\n for (let j = i + 1; j <= n; j++) {\n for (let k = j + 1; k <= n; k++) {\n if (adjacencyList[i].has(j) && adjacencyList[i].has(k) && adjacencyList[j].has(k)) {\n // We minus 6 because we have 3 vertices and each vertices has 2 edges\n // going out to the 3 connecting nodes\n const degree = adjacencyList[i].size + adjacencyList[j].size + adjacencyList[k].size - 6;\n minimumDegree =\n Math.min(minimumDegree, degree);\n }\n }\n }\n }\n\n return minimumDegree === Infinity ? -1 : minimumDegree;\n};", "solution_java": "class Solution {\npublic int minTrioDegree(int n, int[][] edges) {\n\t// to store edge information\n boolean[][] graph = new boolean[n+1][n+1];\n\t//to store inDegrees to a node(NOTE: here inDegree and outDegree are same because it is Undirected graph)\n int[] inDegree = new int[n+1];\n \n for(int[] edge : edges) {\n graph[edge[0]][edge[1]] = true;\n graph[edge[1]][edge[0]] = true;\n \n inDegree[edge[0]]++;\n inDegree[edge[1]]++;\n }\n \n int result = Integer.MAX_VALUE;\n for(int i=1; i<=n; i++) {\n for(int j=i+1; j<=n; j++) {\n if(graph[i][j]) {\n for(int k=j+1; k<=n; k++) {\n if(graph[i][k] && graph[j][k]) {\n result = Math.min(result, inDegree[i] + inDegree[j] + inDegree[k] - 6);\n }\n }\n }\n }\n }\n \n \n return result == Integer.MAX_VALUE ? -1 : result;\n}\n}", "solution_c": "class Solution {\npublic:\n int minTrioDegree(int n, vector>& edges) {\n vector> adj(n+1);\n int res = INT_MAX;\n for (vector& edge : edges) {\n adj[edge[0]].insert(edge[1]);\n adj[edge[1]].insert(edge[0]);\n }\n\n for (int i = 1; i < n; ++i) {\n for (auto iter1 = adj[i].begin(); iter1 != adj[i].end(); ++iter1) {\n if (*iter1 <= i) continue;\n for (auto iter2 = adj[i].begin(); iter2 != adj[i].end(); ++iter2) {\n int u = *iter1, v = *iter2;\n if (v <= u) continue;\n if (adj[u].count(v)) {\n int cur = adj[i].size() + adj[u].size() + adj[v].size() - 6;\n res = min(res, cur);\n }\n }\n }\n }\n\n return res == INT_MAX ? -1 : res;\n }\n};" }, { "title": "Remove Stones to Minimize the Total", "algo_input": "You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:\n\n\n\tChoose any piles[i] and remove floor(piles[i] / 2) stones from it.\n\n\nNotice that you can apply the operation on the same pile more than once.\n\nReturn the minimum possible total number of stones remaining after applying the k operations.\n\nfloor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).\n\n \nExample 1:\n\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\n\n\nExample 2:\n\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n\n\n \nConstraints:\n\n\n\t1 <= piles.length <= 105\n\t1 <= piles[i] <= 104\n\t1 <= k <= 105\n\n", "solution_py": "class Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n heap = [-p for p in piles]\n heapq.heapify(heap)\n for _ in range(k):\n cur = -heapq.heappop(heap)\n heapq.heappush(heap, -(cur-cur//2))\n return -sum(heap) ", "solution_js": "/**\n * @param {number[]} piles\n * @param {number} k\n * @return {number}\n */\n\nvar minStoneSum = function(piles, k) {\n var heapArr = [];\n for (let i=0; i heapArr[Math.floor((currIndex-1)/2)]){\n swap(currIndex, Math.floor((currIndex-1)/2));\n currIndex = Math.floor((currIndex-1)/2);\n }\n }\n \n function heapifyDown(){\n let currIndex = 0;\n let bigger = currIndex;\n while (heapArr[currIndex*2+1]){\n if (heapArr[currIndex] < heapArr[currIndex*2+1]){\n bigger = currIndex * 2 + 1;\n }\n \n if (heapArr[bigger] < heapArr[currIndex*2+2]){\n bigger = currIndex * 2 + 2;\n }\n \n if (bigger === currIndex){\n break;\n }\n swap(currIndex, bigger);\n currIndex = bigger;\n }\n }\n \n function swap(currIndex, otherIndex){\n let temp = heapArr[currIndex];\n heapArr[currIndex] = heapArr[otherIndex];\n heapArr[otherIndex] = temp;\n }\n \n while (k > 0){\n heapArr[0] -= Math.floor(heapArr[0]/2);\n heapifyDown();\n k--;\n }\n \n return heapArr.reduce((a,num) => a+num, 0);\n};", "solution_java": "class Solution {\n public int minStoneSum(int[] A, int k) {\n PriorityQueue pq = new PriorityQueue<>((a, b)->b - a);\n int res = 0;\n for (int a : A) {\n pq.add(a);\n res += a;\n }\n while (k-- > 0) {\n int a = pq.poll();\n pq.add(a - a / 2);\n res -= a / 2;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int minStoneSum(vector& piles, int k) {\n priority_queue pq;\n int sum = 0, curr;\n\n for (auto pile : piles) {\n pq.push(pile);\n sum += pile;\n }\n\n while (k--) {\n curr = pq.top();\n pq.pop();\n sum -= curr/2;\n pq.push(curr - curr/2);\n }\n\n return sum;\n }\n};" }, { "title": "Next Greater Element II", "algo_input": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.\n\nThe next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.\n\n \nExample 1:\n\nInput: nums = [1,2,1]\nOutput: [2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,3]\nOutput: [2,3,4,-1,4]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n t=len(nums)\n nums+=nums\n l=[-1]*len(nums)\n d={}\n stack=[0]\n for x in range(1,len(nums)):\n #print(x)\n if nums[x]>nums[stack[-1]]:\n while nums[x]>nums[stack[-1]] :\n l[stack[-1]]=nums[x]\n stack.pop()\n if stack==[]:\n break\n #print(l)\n stack.append(x)\n \n else:\n stack.append(x)\n return l[:t]\n \n ", "solution_js": "var nextGreaterElements = function(nums) {\n const len = nums.length;\n const ans = new Array(len).fill(-1);\n const stack = [];\n for(let i = 0; i < len; i++) {\n if(i == 0) stack.push([i, nums[i]]);\n else {\n while(stack.length && stack.at(-1)[1] < nums[i]) {\n ans[stack.pop()[0]] = nums[i];\n }\n stack.push([i, nums[i]]);\n }\n }\n for(let num of nums) {\n while(stack.length && stack.at(-1)[1] < num) {\n ans[stack.pop()[0]] = num;\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int[] nextGreaterElements(int[] nums) {\n Stacks=new Stack<>();\n for(int i=nums.length-1;i>=0;i--){\n s.push(nums[i]);\n }\n for(int i=nums.length-1;i>=0;i--){\n int num=nums[i];\n while(!s.isEmpty() && s.peek()<=nums[i]){\n s.pop();\n }\n nums[i]=s.empty()?-1:s.peek();\n s.push(num);\n }\n return nums;\n }\n}", "solution_c": "class Solution {\npublic:\n vector nextGreaterElements(vector& nums) {\n int n = nums.size();\n vector res;\n \n for(int i = 0; i < n; i++){\n int j = i + 1;\n if(j == n) j = 0;\n int next = -1;\n \n while(j != i){\n if(nums[j] > nums[i]){\n next = nums[j];\n break;\n }\n j++;\n if(j == n) j = 0;\n }\n res.push_back(next);\n }\n return res;\n }\n};" }, { "title": "Mean of Array After Removing Some Elements", "algo_input": "Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.\n\nAnswers within 10-5 of the actual answer will be considered accepted.\n\n \nExample 1:\n\nInput: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput: 2.00000\nExplanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\n\n\nExample 2:\n\nInput: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput: 4.00000\n\n\nExample 3:\n\nInput: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput: 4.77778\n\n\n \nConstraints:\n\n\n\t20 <= arr.length <= 1000\n\tarr.length is a multiple of 20.\n\t0 <= arr[i] <= 105\n\n", "solution_py": "class Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n\n return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])", "solution_js": "var trimMean = function(arr) {\n arr.sort((a,b) => a - b);\n let toDelete = arr.length / 20;\n let sum = 0;\n for (let i = toDelete; i < arr.length - toDelete; i++) {\n sum += arr[i];\n }\n return sum / (arr.length - (2 * toDelete));\n};", "solution_java": "class Solution {\n public double trimMean(int[] arr) {\n Arrays.sort(arr);\n int length = arr.length;\n int toRemove = length * 5 / 100;\n int total = 0;\n for (int number: arr) {\n total += number;\n }\n for (int i=0; i= length-toRemove; i--)\n total -= arr[i];\n length -= (2 * toRemove);\n return (double) ((double)total / (double)length);\n }\n}", "solution_c": "class Solution {\npublic:\n double trimMean(vector& arr) {\n auto first = arr.begin() + arr.size() / 20;\n auto second = arr.end() - arr.size() / 20;\n nth_element(arr.begin(), first, arr.end());\n nth_element(first, second, arr.end());\n return accumulate(first, second, 0.0) / distance(first, second);\n }\n};" }, { "title": "Maximum Number of Balls in a Box", "algo_input": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.\n\nYour job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.\n\nGiven two integers lowLimit and highLimit, return the number of balls in the box with the most balls.\n\n \nExample 1:\n\nInput: lowLimit = 1, highLimit = 10\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.\n\nExample 2:\n\nInput: lowLimit = 5, highLimit = 15\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.\n\n\nExample 3:\n\nInput: lowLimit = 19, highLimit = 28\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.\n\n\n \nConstraints:\n\n\n\t1 <= lowLimit <= highLimit <= 105\n\n", "solution_py": "class Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n boxes = [0] * 100\n \n for i in range(lowLimit, highLimit + 1):\n\t\t\t\n\t\t\t# For the current number \"i\", convert it into a list of its digits.\n\t\t\t# Compute its sum and increment the count in the frequency table.\n\t\t\t\n boxes[sum([int(j) for j in str(i)])] += 1\n \n return max(boxes)", "solution_js": "var countBalls = function(lowLimit, highLimit) {\n let obj={};\n for(let i=lowLimit; i<=highLimit; i++){\n i+=''; let sum=0;\n for(let j=0; j map = new HashMap<>();\n int count = Integer.MIN_VALUE;\n for(int i = lowLimit;i<=highLimit;i++){\n int value = 0;\n int temp = i;\n while (temp!=0){\n value += temp%10;\n temp/=10;\n }\n map.put(value,map.getOrDefault(value,0)+1);\n count = map.get(value) > count ? map.get(value) : count;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countBalls(int lowLimit, int highLimit) {\n\n vector box (46,0);\n for(int i = lowLimit;i<=highLimit;i++)\n {\n int sum = 0;\n int temp = i;\n while(temp)\n {\n sum = sum + temp%10;\n temp = temp/10;\n }\n box[sum]++;\n }\n\n return *max_element(box.begin(),box.end());\n }\n};" }, { "title": "Check if There is a Valid Partition For The Array", "algo_input": "You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.\n\nWe call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:\n\n\n\tThe subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.\n\tThe subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.\n\tThe subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.\n\n\nReturn true if the array has at least one valid partition. Otherwise, return false.\n\n \nExample 1:\n\nInput: nums = [4,4,4,5,6]\nOutput: true\nExplanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.\n\n\nExample 2:\n\nInput: nums = [1,1,1,2]\nOutput: false\nExplanation: There is no valid partition for this array.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t1 <= nums[i] <= 106\n\n", "solution_py": "class Solution:\n def validPartition(self, nums: List[int]) -> bool:\n n = len(nums)\n \n dp = [False] * 3\n dp[0] = True # An empty partition is always valid\n\n for i in range(2, n + 1):\n ans = False\n\n if nums[i - 1] == nums[i - 2]:\n ans = ans or dp[(i - 2) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] == nums[i - 3]:\n ans = ans or dp[(i - 3) % 3]\n if i >= 3 and nums[i - 1] == nums[i - 2] + 1 == nums[i - 3] + 2:\n ans = ans or dp[(i - 3) % 3]\n\n dp[i % 3] = ans\n\n return dp[n % 3]", "solution_js": "var validPartition = function(nums) {\n let n = nums.length, memo = Array(n).fill(-1);\n return dp(0);\n\n function dp(i) {\n if (i === n) return true;\n if (i === n - 1) return false;\n if (memo[i] !== -1) return memo[i];\n\n if (nums[i] === nums[i + 1] && dp(i + 2)) return memo[i] = true;\n if (i < n - 2) {\n if (!dp(i + 3)) return memo[i] = false;\n let hasThreeEqual = nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2];\n let hasThreeConsecutive = nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2];\n if (hasThreeEqual || hasThreeConsecutive) return memo[i] = true;\n }\n return memo[i] = false;\n }\n};", "solution_java": "// Time O(n)\n// Space O(n)\nclass Solution {\n public boolean validPartition(int[] nums) {\n boolean[] dp = new boolean[nums.length+1];\n dp[0]=true; // base case\n for (int i = 2; i <= nums.length; i++){\n dp[i]|= nums[i-1]==nums[i-2] && dp[i-2]; // cond 1\n dp[i]|= i>2 && nums[i-1] == nums[i-2] && nums[i-2] == nums[i-3] && dp[i-3]; // cond 2\n dp[i]|= i>2 && nums[i-1]-nums[i-2]==1 && nums[i-2]-nums[i-3]==1 && dp[i-3]; // cond 3\n }\n return dp[nums.length];\n }\n}", "solution_c": "class Solution {\n \npublic:\n int solve(int i, vector &nums, vector &dp)\n {\n if (i == nums.size()) return 1;\n if (dp[i] != -1) return dp[i];\n \n int ans = 0;\n if (i+1 < nums.size() and nums[i] == nums[i+1])\n ans = max(ans, solve(i+2, nums, dp));\n if (i+2 < nums.size())\n {\n if (nums[i] == nums[i+1] && nums[i+1] == nums[i+2])\n ans = max(ans, solve(i+3, nums, dp));\n else if (abs(nums[i]-nums[i+1]) == 1 and abs(nums[i+1]-nums[i+2]) == 1)\n ans = max(ans, solve(i+3, nums, dp));\n \n }\n \n return dp[i] = ans;\n }\n bool validPartition(vector& nums) {\n vector dp(nums.size()+1, -1);\n return solve(0, nums, dp);\n }\n};" }, { "title": "Number of Ways to Stay in the Same Place After Some Steps", "algo_input": "You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).\n\nGiven two integers steps and arrLen, return the number of ways such that your pointer still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: steps = 3, arrLen = 2\nOutput: 4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay\n\n\nExample 2:\n\nInput: steps = 2, arrLen = 4\nOutput: 2\nExplanation: There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay\n\n\nExample 3:\n\nInput: steps = 4, arrLen = 2\nOutput: 8\n\n\n \nConstraints:\n\n\n\t1 <= steps <= 500\n\t1 <= arrLen <= 106\n\n", "solution_py": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n \n # obtain maximum index we can reach\n maxLen = min(steps+1, arrLen)\n dp = [0]*maxLen\n dp[0] = 1\n \n for step in range(1, steps+1):\n dp2 = [0]*maxLen\n for pos in range(maxLen):\n # dp[step][pos] = dp[step-1][pos] + dp[step-1][pos-1] + dp[step-1][pos+1] \n temp1 = 0 if pos == 0 else dp[pos-1]\n temp2 = 0 if pos == maxLen-1 else dp[pos+1]\n dp2[pos] = (dp[pos] + temp1 + temp2)%(10**9+7)\n \n dp = dp2\n return dp[0]", "solution_js": "var numWays = function(steps, arrLen) {\n let memo = Array(steps + 1).fill(0).map(() => Array(steps + 1).fill(-1)), mod = 10 ** 9 + 7;\n return dp(0, steps);\n \n function dp(i, steps) {\n if (steps === 0) return i === 0 ? 1 : 0; // found a way\n if (i > steps || i < 0 || i >= arrLen) return 0; // out of bounds\n if (memo[i][steps] !== -1) return memo[i][steps]; // memoized\n \n let moveLeft = dp(i - 1, steps - 1);\n let moveRight = dp(i + 1, steps - 1);\n let stay = dp(i, steps - 1);\n return memo[i][steps] = (moveLeft + moveRight + stay) % mod;\n }\n};", "solution_java": "class Solution {\n \n HashMap map = new HashMap();\n \n public int numWays(int steps, int arrLen) {\n \n return (int) (ways(steps,arrLen,0) % ((Math.pow(10,9)) +7));\n }\n \n public long ways(int steps,int arrLen,int index){\n String curr = index + \"->\" + steps;\n \n if(index == 0 && steps == 0){\n return 1;\n }else if(index < 0 || (index >= arrLen) || steps == 0){\n return 0;\n }\n \n if(map.containsKey(curr)){\n return map.get(curr);\n }\n long stay = ways(steps-1,arrLen,index);\n long right = ways(steps-1,arrLen,index+1);\n long left = ways(steps-1,arrLen,index-1);\n \n map.put(curr , (stay+right+left) % 1000000007);\n \n return (right + left + stay) % 1000000007;\n }\n}", "solution_c": "class Solution {\npublic:\n int n, MOD = 1e9 + 7;\n int numWays(int steps, int arrLen) {\n n = arrLen;\n vector> memo(steps / 2 + 1, vector(steps + 1, -1));\n return dp(memo, 0, steps) % MOD;\n }\n long dp(vector>& memo, int i, int steps){\n if(steps == 0)\n return i == 0;\n if(i < 0 || i == n || i > steps)\n return 0;\n if(memo[i][steps] != -1)\n return memo[i][steps];\n return memo[i][steps] = (dp(memo, i, steps - 1) + dp(memo, i - 1, steps - 1) + dp(memo, i + 1, steps - 1)) % MOD;\n }\n};" }, { "title": "Daily Temperatures", "algo_input": "Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.\n\n \nExample 1:\nInput: temperatures = [73,74,75,71,69,72,76,73]\nOutput: [1,1,4,2,1,1,0,0]\nExample 2:\nInput: temperatures = [30,40,50,60]\nOutput: [1,1,1,0]\nExample 3:\nInput: temperatures = [30,60,90]\nOutput: [1,1,0]\n\n \nConstraints:\n\n\n\t1 <= temperatures.length <= 105\n\t30 <= temperatures[i] <= 100\n\n", "solution_py": "class Solution:\n def dailyTemperatures(self, T):\n ans, s = [0]*len(T), deque()\n for cur, cur_tmp in enumerate(T):\n while s and cur_tmp > T[s[-1]]:\n ans[s[-1]] = cur - s[-1]\n s.pop()\n s.append(cur)\n return ans", "solution_js": "var dailyTemperatures = function(temperatures) {\n const len = temperatures.length;\n const res = new Array(len).fill(0);\n const stack = [];\n \n for (let i = 0; i < len; i++) {\n const temp = temperatures[i];\n \n while (temp > (stack[stack.length - 1] || [Infinity])[0]) {\n const [_, j] = stack.pop();\n res[j] = i - j;\n }\n \n stack.push([temp, i]);\n }\n \n return res;\n};", "solution_java": "class Solution {\n public int[] dailyTemperatures(int[] temperatures) {\n HashMaphm=new HashMap<>();\n Stackst=new Stack<>();\n for(int i=0;i0&&temperatures[i]>temperatures[st.peek()]){\n hm.put(st.pop(),i);\n }\n st.push(i);\n }\n int []ans=new int[temperatures.length];\n for(int i=0;i dailyTemperatures(vector& temperatures) {\n int n = temperatures.size();\n stack st;\n vector result(n, 0);\n for(int i = 0; itemperatures[st.top()]){\n result[st.top()] = i-st.top();\n st.pop();\n }\n st.push(i);\n }\n return result;\n }\n};" }, { "title": "Construct Binary Tree from Preorder and Postorder Traversal", "algo_input": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.\n\nIf there exist multiple answers, you can return any of them.\n\n \nExample 1:\n\nInput: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\n\n\nExample 2:\n\nInput: preorder = [1], postorder = [1]\nOutput: [1]\n\n\n \nConstraints:\n\n\n\t1 <= preorder.length <= 30\n\t1 <= preorder[i] <= preorder.length\n\tAll the values of preorder are unique.\n\tpostorder.length == preorder.length\n\t1 <= postorder[i] <= postorder.length\n\tAll the values of postorder are unique.\n\tIt is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree.\n\n", "solution_py": "class Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n\n def build(preorder, preStart, preEnd, postorder, postStart, postEnd):\n if preStart > preEnd:\n return\n elif preStart == preEnd:\n return TreeNode(preorder[preStart])\n \n rootVal = preorder[preStart]\n leftRootVal = preorder[preStart + 1]\n index = valToIndex[leftRootVal]\n root = TreeNode(rootVal)\n leftSize = index - postStart + 1\n \n root.left = build(preorder, preStart + 1, preStart + leftSize,\npostorder, postStart, index)\n root.right = build(preorder, preStart + leftSize + 1, preEnd,\npostorder, index + 1, postEnd - 1)\n \n return root\n \n valToIndex = {}\n for i in range(len(postorder)):\n valToIndex[postorder[i]] = i\n \n return build(preorder, 0, len(preorder) - 1, postorder, 0, len(postorder) - 1)", "solution_js": "var constructFromPrePost = function(preorder, postorder) {\n let preIndex = 0\n\n const dfs = (postArr) => {\n if (postArr.length === 0) return null\n\n const val = preorder[preIndex]\n const nextVal = preorder[++preIndex]\n const mid = postArr.indexOf(nextVal)\n\n const root = new TreeNode(val)\n root.left = dfs(postArr.slice(0, mid + 1))\n root.right = dfs(postArr.slice(mid + 1, postArr.indexOf(val)))\n\n return root\n }\n\n return dfs(postorder)\n};", "solution_java": "class Solution\n{\n public TreeNode constructFromPrePost(int[] preorder, int[] postorder)\n {\n // O(n) time | O(h) space\n if(preorder == null || postorder == null || preorder.length == 0 || postorder.length == 0) return null;\n\n TreeNode root = new TreeNode(preorder[0]);\n int mid = 0;\n\n if(preorder.length == 1) return root;\n\n // update mid\n for(int i = 0; i < postorder.length; i++)\n {\n if(preorder[1] == postorder[i])\n {\n mid = i;\n break;\n }\n }\n\n root.left = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1, 1 + mid + 1),\n Arrays.copyOfRange(postorder, 0, mid + 1));\n\n root.right = constructFromPrePost(\n Arrays.copyOfRange(preorder, 1 + mid + 1, preorder.length),\n Arrays.copyOfRange(postorder, mid + 1, postorder.length - 1));\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 bool vis[40];\n \n TreeNode* solve(vector& pre,int p, vector& pos,int q){\n TreeNode* root=new TreeNode(pre[p]);\n vis[pre[p]]=true;\n p++;\n q--;\n \n if(p>=pre.size() || q<0){\n return root;\n }\n if(!vis[pre[p]]){\n \n int x=q;\n while(x>0 and pos[x]!=pre[p])x--;\n if(pos[x]==pre[p]){\n root->left=solve(pre,p,pos,x);\n }\n \n }\n if(!vis[pos[q]]){\n int x=p;\n while(xright=solve(pre,x,pos,q);\n }\n }\n return root;\n }\n \n TreeNode* constructFromPrePost(vector& preorder, vector& postorder) {\n int n=postorder.size();\n return solve(preorder,0,postorder,n-1);\n }\n};" }, { "title": "Destination City", "algo_input": "You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.\n\nIt is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.\n\n \nExample 1:\n\nInput: paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput: \"Sao Paulo\" \nExplanation: Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".\n\n\nExample 2:\n\nInput: paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput: \"A\"\nExplanation: All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".\n\n\nExample 3:\n\nInput: paths = [[\"A\",\"Z\"]]\nOutput: \"Z\"\n\n\n \nConstraints:\n\n\n\t1 <= paths.length <= 100\n\tpaths[i].length == 2\n\t1 <= cityAi.length, cityBi.length <= 10\n\tcityAi != cityBi\n\tAll strings consist of lowercase and uppercase English letters and the space character.\n\n", "solution_py": "from collections import defaultdict\nclass Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n deg = defaultdict(int)\n for v, w in paths:\n deg[v] += 1\n deg[w]\n for v in deg:\n if not deg[v]: return v", "solution_js": " * @param {string[][]} paths\n * @return {string}\n */\nvar destCity = function(paths) {\n \n \n let map={}\n \n for(let city of paths){\n map[city[0]]=map[city[0]]?map[city[0]]+1:1\n }\n for(let city of paths){\n if(!map[city[1]]) return city[1]\n }\n};```", "solution_java": "class Solution {\n public String destCity(List> paths) {\n HashSet set1 = new HashSet<>();\n\n for (int i = 0; i < paths.size(); ++i) {\n set1.add(paths.get(i).get(0));\n }\n for (int i = 0; i < paths.size(); ++i) {\n if (!set1.contains(paths.get(i).get(1))) return paths.get(i).get(1);\n }\n return \"placeholder\";\n }\n}", "solution_c": "class Solution {\npublic:\n string destCity(vector>& paths) {\n string ans;\n unordered_map m;\n for(int i=0; i int:\n res=nums[0]\n prev=nums[0]\n for i in range(1,len(nums)):\n res += max(0,nums[i]-prev)\n prev=nums[i]\n return res", "solution_js": "var minNumberOperations = function(target) {\n let res = target[0];\n for(let g=1; g target[g-1]){\n res = res + (target[g] - target[g-1]);\n }\n // for target[g] < target[g-1] we need not worry as its already been taken care by previous iterations\n }\n return res;\n};", "solution_java": "// Imagine 3 cases\n// Case 1. [3,2,1], we need 3 operations.\n// Case 2. [1,2,3], we need 3 operations.\n// Case 3. [3,2,1,2,3], we need 5 operations.\n// What we need to add is actually the diff (cur - prev)\n// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public int minNumberOperations(int[] target) {\n int res = 0;\n int prev = 0;\n for (int cur : target) {\n if (cur > prev) {\n res += cur - prev;\n }\n prev = cur;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int minNumberOperations(vector& target) {\n int n=target.size();\n int pre=0, cnt=0;\n for(int i=0;ipre)\n cnt+=target[i]-pre;\n pre=target[i];\n }\n return cnt;\n }\n};" }, { "title": "Open the Lock", "algo_input": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.\n\nThe lock initially starts at '0000', a string representing the state of the 4 wheels.\n\nYou are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.\n\nGiven a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.\n\n \nExample 1:\n\nInput: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput: 6\nExplanation: \nA sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".\n\n\nExample 2:\n\nInput: deadends = [\"8888\"], target = \"0009\"\nOutput: 1\nExplanation: We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".\n\n\nExample 3:\n\nInput: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput: -1\nExplanation: We cannot reach the target without getting stuck.\n\n\n \nConstraints:\n\n\n\t1 <= deadends.length <= 500\n\tdeadends[i].length == 4\n\ttarget.length == 4\n\ttarget will not be in the list deadends.\n\ttarget and deadends[i] consist of digits only.\n\n", "solution_py": "class Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n def neighbor(s):\n res = []\n for i, c in enumerate(s):\n res.append(s[:i] + chr((ord(c) - ord('0') + 9) % 10 + ord('0')) + s[i + 1:])\n res.append(s[:i] + chr((ord(c) - ord('0') + 1) % 10 + ord('0')) + s[i + 1:])\n return res\n \n deadends = set(deadends)\n if \"0000\" in deadends:\n return -1\n ans = 0\n queue = deque([\"0000\"])\n vis = set()\n while queue:\n l = len(queue)\n for _ in range(l):\n cur = queue.popleft()\n if cur == target:\n return ans\n for nxt in neighbor(cur):\n if nxt not in vis and nxt not in deadends:\n queue.append(nxt)\n vis.add(nxt)\n ans += 1\n return -1", "solution_js": "var openLock = function(deadends, target) {\n if(deadends.includes('0000')) {\n return -1\n }\n // treat deadends like visited\n // if a number is in visited/deadends, simply ignore it\n const visited = new Set(deadends)\n \n \n const queue = [['0000', 0]];\n visited.add('0000')\n\n while(queue.length) {\n const [cur, count] = queue.shift()\n if(cur === target) {\n return count\n }\n \n // each number will create 8 more different paths to check\n \n // e.g. if cur = 0000. 8 next/prev numbers to check are\n // 1000, 9000, 0100, 0900, 0010, 0090, 0001, 0009\n for(let i=0; i<4; i++) {\n const c = cur[i]\n \n let up = Number(c) + 1;\n let down = Number(c) - 1;\n // if up is 9, then up + 1 = 10 -> set it to 0\n if(up === 10) {\n up = '0';\n }\n // if down is 0. then down - 1 = -1 -> set to 9\n if(down === -1) {\n down = '9'\n }\n \n const next = cur.substring(0, i) + up + cur.substring(i+1)\n const prev = cur.substring(0, i) + down + cur.substring(i + 1)\n \n // if not visited, push to queue\n if(!visited.has(next)) {\n visited.add(next)\n queue.push([next, count + 1]) \n }\n\n if(!visited.has(prev)) {\n visited.add(prev)\n queue.push([prev, count + 1]) \n }\n }\n }\n \n return -1;\n};", "solution_java": "class Solution {\n public int openLock(String[] deadends, String target) {\n// Converted target to Integer type.\n int t = Integer.parseInt(target);\n HashSet visited = new HashSet<>();\n\n// Converting deadend strings to Integer type. To prevent from visiting deadend, we already mark them visited.\n for(String str: deadends){\n visited.add(Integer.parseInt(str));\n }\n// BFS\n Queue q = new ArrayDeque<>();\n// We make sure that 0 itself isn't a deadend\n if(visited.contains(0)){\n return -1;\n }\n q.add(0);\n visited.add(0);\n int level = 0;\n while(q.size() > 0){\n int size = q.size();\n while(size-->0){\n int elem = q.remove();\n if(t == elem){\n return level;\n }\n// Will help check 4 digits of the element. From digit with low precendence(ones place) to high precedence(thousands place)\n for(int i = 1; i < 10000; i= i*10){\n// The wheel can be rotated in two directions. Hence two numbers.\n int num1;\n int num2;\n// The wheel at 0 can become 1 or 9 due to wrapping.\n if(elem / i % 10 == 0){\n num1=elem + i;\n num2 = elem+ i * 9;\n }\n// The wheel at 9 can become 0 or 8 due to wrapping.\n else if(elem / i % 10 == 9){\n num1 = elem - i * 9;\n num2 = elem -i;\n }\n else{\n num1 = elem -i;\n num2 = elem + i;\n }\n// Checking if numbers have already been visited.\n if(!(visited.contains(num1))){\n visited.add(num1);\n q.add(num1);\n }\n if(!(visited.contains(num2))){\n visited.add(num2);\n q.add(num2);\n }\n }\n }\n level++;\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n void setPermutations(const string& s, queue>& q, int count) {\n for (int i=0; i<4; i++) {\n int j = s[i]-'0';\n char b = (10+j-1)%10 + '0', n = (10+j+1)%10 + '0';\n auto tmp = s; tmp[i]=b;\n q.push({tmp, count+1});\n tmp = s; tmp[i]=n;\n q.push({tmp, count+1});\n }\n }\n int openLock(vector& deadends, string target) {\n unordered_set deadies(deadends.begin(), deadends.end());\n queue> q({{\"0000\", 0}});\n while (!q.empty()) {\n auto t = q.front();\n q.pop();\n if (deadies.count(t.first))\n continue;\n if (t.first==target)\n return t.second;\n deadies.insert(t.first);\n setPermutations(t.first, q, t.second);\n }\n return -1;\n }\n};" }, { "title": "Three Consecutive Odds", "algo_input": "Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.\n \nExample 1:\n\nInput: arr = [2,6,4,1]\nOutput: false\nExplanation: There are no three consecutive odds.\n\n\nExample 2:\n\nInput: arr = [1,2,34,3,4,5,7,23,12]\nOutput: true\nExplanation: [5,7,23] are three consecutive odds.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 1000\n\t1 <= arr[i] <= 1000\n\n", "solution_py": "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n c=0\n for i in arr:\n if i%2==0:\n c=0\n else:\n c+=1\n if c==3:\n return True\n return False", "solution_js": "var threeConsecutiveOdds = function(arr) {\n let c = 0;\n\n for(let val of arr){\n if(val % 2 === 1){\n c++;\n if(c === 3) {\n return true;\n }\n } else {\n c=0;\n }\n }\n\n return false;\n};", "solution_java": "class Solution {\n public boolean threeConsecutiveOdds(int[] arr) {\n int count = 0,n = arr.length;\n for(int i=0;i 0)\n {\n count++;\n if(count == 3) return true;\n }\n else\n {\n count = 0;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool threeConsecutiveOdds(vector& arr) {\n int k = 0;\n for(int i=0;i int:\n start = locations[start]\n end = locations[finish]\n locations.sort()\n start = bisect_left(locations, start)\n end = bisect_left(locations, end)\n @lru_cache(None)\n def dfs(i, fuel):\n if fuel == 0 and i == end: return 1\n res = 0\n if i == end: res += 1\n j = i-1\n while j>=0 and abs(locations[j]-locations[i]) <= fuel:\n res += dfs(j, fuel-abs(locations[j]-locations[i]))\n j -= 1\n j = i+1\n while jnew Array(201).fill(-1));\n \n const dfs = function(cur, f){\n if(f<0) return 0;\n if(memo[cur][f]!=-1) return memo[cur][f];\n let res = (cur==finish);\n for(let i in locations){\n if(i==cur) continue;\n res = (res + dfs(i, f-Math.abs(locations[i]-locations[cur])))%1000000007;\n }\n return memo[cur][f]=res;\n }\n \n return dfs(start, fuel);\n};", "solution_java": "/*\n\nUsing DFS and Memo :\n\n1. We will start from start pos provided and will dfs travel to each other location .\n2. each time we will see if we reach finish , we will increment the result . but we wont stop there if we have fuel left and continue travelling\n3. if fuel goes negetive , we will return 0 , as there is no valid solution in that path\n4. we will take dp[locations][fuel+1] to cache the result , to avoid recomputing .\n\n*/\n\nclass Solution {\n\n int mod = (int)Math.pow(10,9) + 7 ;\n int[][] dp ;\n\n public int countRoutes(int[] locations, int start, int finish, int fuel) {\n\n dp = new int[locations.length][fuel+1] ;\n\n for(int[] row : dp){\n Arrays.fill(row , -1) ;\n }\n\n return dfs(locations , start , finish , fuel);\n }\n\n public int dfs(int[] locations , int cur_location , int finish , int fuel){\n\n if(fuel < 0){\n return 0 ;\n }\n\n if(dp[cur_location][fuel] != -1){\n return dp[cur_location][fuel] ;\n }\n\n int result = 0 ;\n\n if(cur_location == finish){\n result++ ;\n }\n\n for(int i=0 ; i &arr , int s , int f , int k , vector> &dp){\n if(k<0) return 0 ;\n if(dp[s][k]!=-1) return dp[s][k] ;\n int ans=0 ;\n if(s==f) ans=1 ;\n for(int i=0 ; i& locations, int start, int finish, int fuel) {\n vector> dp(locations.size()+1,vector(fuel+1,-1)) ;\n int ans=fun(locations,start,finish,fuel,dp) ;\n return ans ;\n }\n};" }, { "title": "Minimum Falling Path Sum II", "algo_input": "Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.\n\nA falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.\n\n \nExample 1:\n\nInput: arr = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.\n\n\nExample 2:\n\nInput: grid = [[7]]\nOutput: 7\n\n\n \nConstraints:\n\n\n\tn == grid.length == grid[i].length\n\t1 <= n <= 200\n\t-99 <= grid[i][j] <= 99\n\n", "solution_py": "class Solution:\n def minFallingPathSum(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n if m == 1 and n == 1:\n return grid[0][0]\n min_arr = [0 for _ in range(n)]\n for i in range(m):\n prefix = [float('inf') for _ in range(n)]\n suffix = [float('inf') for _ in range(n)]\n current_row = [elem1+elem2 for elem1, elem2 in zip(grid[i], min_arr)]\n for i in range(1, n):\n prefix[i] = min(prefix[i-1], current_row[i-1])\n for i in range(n-2, -1, -1):\n suffix[i] = min(suffix[i+1], current_row[i+1])\n min_arr = [min(pre, suff) for pre, suff in zip(prefix, suffix)]\n return min(min_arr)", "solution_js": "var minFallingPathSum = function(grid) {\nif(grid.length===1){\n return grid[0][0];\n}\nlet sums = [];//find first, second and third minimum values in the grid as these are only possible values for path\n//store the index for fast lookup in a 3D array\nfor(let i=0; i {//recursive call to decide which path to choose from r=row, li=lastIndex\n if(memo[r+','+li] !== undefined){// memoized\n return memo[r+','+li];\n }\n if(r===grid.length-1){// last and first choice for path can only be from 1st and 2nd minimum, as there is only one other row to occupy these columns\n if(li===sums[r][0][1]){\n memo[r+','+li] = sums[r][1][0];\n }\n else{\n memo[r+','+li] = sums[r][0][0];\n }\n return memo[r+','+li];\n }\n else{\n switch (li) {// pick the minimum value path where index is not equal to last index\n case sums[r][0][1]:\n memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n break;\n case sums[r][1][1]:\n memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n break;\n case sums[r][2][1]:\n memo[r+','+li] = Math.min(sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][0][0]+recur(r+1,sums[r][0][1]));\n break;\n default:\n memo[r+','+li] = Math.min(sums[r][0][0]+recur(r+1,sums[r][0][1]),sums[r][1][0]+recur(r+1,sums[r][1][1]),sums[r][2][0]+recur(r+1,sums[r][2][1]));\n }\n return memo[r+','+li];\n }\n}\nreturn recur(0,sums[0][2][1]);//since first and last can only be picked from 1st and 2nd min values\n};", "solution_java": "class Solution {\n // Recursion\n /* public int minFallingPathSum(int[][] grid) {\n int n=grid.length;\n if(n==1) return grid[0][0];\n int ans = 10000000;\n for(int i=0 ; i> &matrix, vector> &dp){\n\n //to handle edge cases if the j index is less than 0 or greater than size of the array.\n if(j<0 or j>=matrix[0].size()) return 1e8;\n\n //base case\n if(i==0) return dp[0][j] = matrix[0][j];\n\n if(dp[i][j]!=-1) return dp[i][j];\n\n int ans = INT_MAX;\n\n //Here we have to iterate through all the possiblities in the entire upper row for each\n //element except for the element which is directly above the current element in the\n //matrix, and then we have to find the minimum.\n for(int k=0;k>& grid) {\n\n int mini = INT_MAX;\n int n = grid.size();\n\n vector> dp(n, vector(n,-1));\n\n for(int j=0;j str:\n return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else \"\" for i in range(2, len(n)))", "solution_js": "var largestGoodInteger = function(num) {\n let maxGoodInt = '';\n for (let i = 0; i <= num.length - 3; i++) {\n if (num[i] === num[i+1] && num[i+1] === num[i+2]) {\n if (num[i] >= maxGoodInt) {\n maxGoodInt = num[i];\n }\n }\n }\n return maxGoodInt + maxGoodInt + maxGoodInt;\n};", "solution_java": "class Solution\n{\n public String largestGoodInteger(String num)\n {\n String ans = \"\";\n for(int i = 2; i < num.length(); i++)\n if(num.charAt(i) == num.charAt(i-1) && num.charAt(i-1) == num.charAt(i-2))\n if(num.substring(i-2,i+1).compareTo(ans) > 0) // Check if the new one is larger\n ans = num.substring(i-2,i+1);\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n string largestGoodInteger(string num) {\n string ans = \"\";\n for(int i=1; i List[int]:\n longest, res = [], []\n for i in range(len(obstacles)):\n idx = bisect_right(longest, obstacles[i])\n if idx == len(longest):\n longest.append(obstacles[i])\n else:\n longest[idx] = obstacles[i]\n res.append(idx+1)\n return res", "solution_js": "var longestObstacleCourseAtEachPosition = function(obstacles) {\n var n = obstacles.length;\n var lis = [];\n var res = new Array(n).fill(0);\n for(var i = 0; i0 && obstacles[i] >= lis[lis.length-1])\n {\n lis.push(obstacles[i]);\n res[i] = lis.length;\n }\n else\n {\n // find the upper bound\n var l = 0;\n var r = lis.length;\n while(l<=r)\n {\n var mid = Math.floor((l+r)/2);\n if(lis[mid]<=obstacles[i])\n {\n l = mid+1;\n }\n else\n {\n r = mid-1;\n }\n }\n lis[l] = obstacles[i];\n res[i] = l+1;\n }\n }\n return res;\n}", "solution_java": "class Solution {\n public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {\n int i = -1, cur = 0, lisSize = -1;\n int[] lis = new int[obstacles.length];\n int[] ans = new int[obstacles.length];\n \n for (int curHeight: obstacles) {\n if (i == -1 || lis[i] <= curHeight) {\n lis[++i] = curHeight;\n lisSize = i;\n } else {\n lisSize = search(lis, 0, i, curHeight);\n lis[lisSize] = curHeight;\n }\n \n ans[cur++] = lisSize + 1;\n }\n \n return ans; \n }\n \n private int search(int[] nums, int start, int end, int target) {\n int left = start, right = end;\n int boundary = 0;\n while (left <= right) {\n int mid = left + (right - left) / 2;\n if (nums[mid] > target) {\n boundary = mid;\n right = mid - 1;\n } else left = mid + 1;\n }\n return boundary;\n }\n}", "solution_c": "class Solution {\npublic:\n\t// ranking each element to make segment tree of small size\n void compress(vector& a){\n vector b=a;\n sort(b.begin(),b.end());\n map mp;\n int prev=b[0],rnk=0,n=a.size();\n for(int i=0;itr)\n return;\n if(tl==tr){\n st[tind]=val;\n return;\n }\n int m=tl+(tr-tl)/2,left=tind<<1;\n if(ind<=m)\n update(st,left,ind,val,tl,m);\n else\n update(st,left+1,ind,val,m+1,tr);\n st[tind]=max(st[left],st[left+1]);\n }\n \n int query(int st[],int tind,int tl,int tr,int ql,int qr){\n if(tl>tr or ql>tr or qr longestObstacleCourseAtEachPosition(vector& a) {\n compress(a);\n int i,n=a.size();\n int st[4*n+10];\n memset(st,0,sizeof(st));\n update(st,1,a[0],1,0,n-1);\n vector dp(n);\n dp[0]=1;\n \n for(i=1;i int:\n prev = 0\n res = 0\n for i, d in enumerate(bin(n)[3:]):\n if d == \"1\":\n res = max(res, i-prev+1)\n prev = i + 1\n return res", "solution_js": "var binaryGap = function(n) {\n var str = (n >>> 0).toString(2), start = 0, end = 0, diff = 0;\n for(var i=0;i ans = new ArrayList();\n for(int i = 0; i < arr.length ; i++){\n if(arr[i] == '1')\n ans.add(i);\n }\n int res = 0;\n for ( int i = 0 ; i < ans.size() -1 ; i++){\n res =Math.max(res,ans.get(i+1) - ans.get(i));\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int binaryGap(int n) {\n int res=0;\n int s=0,i=0;\n while(n){\n if(n&1){\n s=i;break;\n }\n i++;\n n=n>>1;\n }\n while(n){\n if(n&1){\n res=max(res,(i-s));\n s=i;\n }\n i++;\n n=n>>1;\n }\n return res;\n }\n};" }, { "title": "K Divisible Elements Subarrays", "algo_input": "Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p.\n\nTwo arrays nums1 and nums2 are said to be distinct if:\n\n\n\tThey are of different lengths, or\n\tThere exists at least one index i where nums1[i] != nums2[i].\n\n\nA subarray is defined as a non-empty contiguous sequence of elements in an array.\n\n \nExample 1:\n\nInput: nums = [2,3,3,2,2], k = 2, p = 2\nOutput: 11\nExplanation:\nThe elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4], k = 4, p = 1\nOutput: 10\nExplanation:\nAll element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 200\n\t1 <= nums[i], p <= 200\n\t1 <= k <= nums.length\n\n\n \nFollow up:\n\nCan you solve this problem in O(n2) time complexity?\n", "solution_py": "class Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n n = len(nums) \n sub_arrays = set()\n \n\t\t# generate all combinations of subarray\n for start in range(n):\n cnt = 0\n temp = ''\n for i in range(start, n):\n if nums[i]%p == 0:\n cnt+=1 \n temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format \n if cnt>k: # check for termination \n break\n sub_arrays.add(temp) \n \n return len(sub_arrays)", "solution_js": "var countDistinct = function(nums, k, p) {\n let ans = [];\n\n let rec = (index,k,p,nums,ans,curr) => {\n let val = nums[index];\n let check = val%p;\n let isdiv = false;\n if(check == 0) isdiv=true;\n\n if(index == nums.length) {\n if(curr.length>0){\n ans.push(curr.join(\",\"));\n }\n return;\n }\n\n //take conditions\n if(isdiv && k==0){\n ans.push(curr.join(\",\"));\n } else if(isdiv){\n curr.push(val)\n rec(index+1,k-1,p,nums,ans,curr);\n curr.pop()\n } else {\n curr.push(val)\n rec(index+1,k,p,nums,ans,curr);\n curr.pop()\n }\n\n //non take conditions\n if(curr.length == 0){\n rec(index+1,k,p,nums,ans,curr);\n } else {\n ans.push(curr.join(\",\"));\n }\n\n }\n rec(0,k,p,nums,ans,[]);\n let set = new Set(ans);\n\n return set.size\n};", "solution_java": "class Solution {\n public int countDistinct(int[] nums, int k, int p) {\n int n = nums.length;\n // we are storing hashcode for all the substrings so that we can compare them faster.\n // main goal is to avoid entire sub array comparision using hashcode.\n Set ways = new HashSet<>();\n for(int i = 0; i < n; i++) {\n int cnt = 0;\n long hc = 1; // this is the running hashcode for sub array [i...j]\n for(int j = i; j < n; j++) {\n hc = 199L * hc + nums[j]; // updating running hashcode, since we nums are <=200, we shall consider a prime near 200 to avoid collision\n if(nums[j] % p == 0)\n cnt++;\n if(cnt <= k) { // if current subarray [i...j] is valid, add its hashcode in our storage.\n ways.add(hc);\n }\n }\n }\n return ways.size();\n }\n}", "solution_c": "class Solution {\npublic:\n\n int countDistinct(vector& nums, int k, int p) {\n \n int n=nums.size();\n set>ans;\n \n int i,j;\n for(i=0;itt;\n int ct=0;\n for(j=i;jk)\n break;\n ans.insert(tt);\n \n }\n }\n return ans.size();\n }\n \n};" }, { "title": "Minimum Space Wasted From Packaging", "algo_input": "You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.\n\nThe package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.\n\nYou want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.\n\n\n\tFor example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.\n\n\nReturn the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput: 6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.\n\n\nExample 2:\n\nInput: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput: -1\nExplanation: There is no box that the package of size 5 can fit in.\n\n\nExample 3:\n\nInput: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput: 9\nExplanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n\n\n \nConstraints:\n\n\n\tn == packages.length\n\tm == boxes.length\n\t1 <= n <= 105\n\t1 <= m <= 105\n\t1 <= packages[i] <= 105\n\t1 <= boxes[j].length <= 105\n\t1 <= boxes[j][k] <= 105\n\tsum(boxes[j].length) <= 105\n\tThe elements in boxes[j] are distinct.\n\n", "solution_py": "class Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n # prefix sum to save time\n acc = [0] + [*accumulate(packages)]\n packages.sort()\n\n ans = float('inf')\n for box in boxes:\n tmp = 0\n # deal with smallest box first\n box.sort()\n\n # record number of packages already dealt with\n start = 0\n\n for b in box:\n loc = bisect.bisect(packages, b)\n if loc == 0: continue\n tmp += b * (loc - start) - (acc[loc] - acc[start])\n\n # all are packaged\n if loc == len(packages):\n ans = min(ans, tmp)\n break\n\n start = loc\n\n return ans % (10 **9+7) if ans != float('inf') else -1", "solution_js": "/**\n * @param {number[]} packages\n * @param {number[][]} boxes\n * @return {number}\n */\nvar minWastedSpace = function(packages, boxes) {\n let count=0,b,minWastage,totalPackagesSize=0n,minBoxesAreaForAnySupplier=BigInt(Number.MAX_SAFE_INTEGER),boxesArea=0n,p,coverdPackagesIndex,totalBoxesAreaForSupplier;\n packages.sort(function(a,b){return a-b});\n for(let i=0;i= 0){\n int cnt = pos[b[i]]-k;\n cost += 1L * cnt * b[i];\n k=pos[b[i]];\n }\n }\n ans = k == n-1? Math.min(cost, ans) : ans;\n }\n\n return ans == Long.MAX_VALUE? -1 : (int)(ans % (int)(1e9+7));\n }\n}", "solution_c": "class Solution {\npublic:\n #define MOD 1000000007\n #define ll long long\n int minWastedSpace(vector& packages, vector>& boxes) {\n \n int n = packages.size();\n int m = boxes.size();\n sort(packages.begin(), packages.end());\n vector pack(n + 1);\n pack[0] = 0;\n for(int i = 0;i opt = boxes[i];\n sort(opt.begin(), opt.end());\n int back = 0;\n ll temp = 0;\n bool flag = false;\n ll bag ;\n for(int j = 0; j<(int)opt.size(); j++){\n \n bag = opt[j];\n auto it = upper_bound(packages.begin(), packages.end(), bag);\n auto it1 = it;\n int idx ;\n if(it != packages.begin()){\n it--;\n idx = it - packages.begin();\n ll num_packs = idx + 1 - back;\n \n ll pack_sum = pack[idx + 1] - pack[back];\n back = idx + 1;\n temp += (num_packs*bag - pack_sum);\n }\n if(it1 == packages.end()){\n flag = true;\n break;\n } \n }\n if(flag){\n ans = min(ans, temp);\n mf = true;\n }\n \n }\n if(!mf) return -1;\n \n if(ans == 1e18) return -1;\n ans = ans % MOD;\n return ans;\n }\n};" }, { "title": "Cinema Seat Allocation", "algo_input": "\n\nA cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.\n\nGiven the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.\n\nReturn the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.\n\n \nExample 1:\n\n\n\nInput: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput: 4\nExplanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\n\n\nExample 2:\n\nInput: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput: 2\n\n\nExample 3:\n\nInput: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= n <= 10^9\n\t1 <= reservedSeats.length <= min(10*n, 10^4)\n\treservedSeats[i].length == 2\n\t1 <= reservedSeats[i][0] <= n\n\t1 <= reservedSeats[i][1] <= 10\n\tAll reservedSeats[i] are distinct.\n\n", "solution_py": "class Solution(object):\n def maxNumberOfFamilies(self, n, reservedSeats):\n \"\"\"\n :type n: int\n :type reservedSeats: List[List[int]]\n :rtype: int\n \"\"\"\n d = defaultdict(set)\n for row,seat in reservedSeats:\n d[row].add(seat)\n \n def row(i):\n a1 = not set((2,3,4,5)).intersection(d[i])\n a2 = not set((6,7,8,9)).intersection(d[i])\n if a1 and a2:\n return 2\n if a1 or a2:\n return 1\n return 1 if not set((4,5,6,7)).intersection(d[i]) else 0\n \n return sum((row(i) for i in d.keys())) + (n-len(d)) * 2", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} reservedSeats\n * @return {number}\n */\nvar maxNumberOfFamilies = function(n, reservedSeats) {\n let a,b,c,reservedMap={},ans=n*2,takenB={};\n for(let i=0;i seats = new HashMap<>();\n int availableSlots = 2 * n; // max available slots since each empty row could fit at max 2 slots\n\n for (int[] seat: reservedSeats) {\n int row = seat[0];\n int col = seat[1];\n int[] slots = seats.getOrDefault(row, new int[3]);\n\n if (col >= 2 && col <= 5) { // left slot\n slots[0] = 1;\n }\n if (col >= 4 && col <= 7) { // middle slot\n slots[1] = 1;\n }\n if (col >= 6 && col <= 9) { // right slot\n slots[2] = 1;\n }\n\n seats.put(seat[0], slots);\n }\n\n for (int[] slots: seats.values()) {\n int taken = slots[0] + slots[2];\n\n if (taken == 2) { // both slots at either ends are taken\n if (slots[1] == 0) { // check if middle slot not taken\n availableSlots--; // reduce availableslots by 1 since middle slot is available\n } else {\n availableSlots -= 2; // entire row not available - reduce by 2\n }\n } else if (taken == 1) { // one of the slots at either ends are taken\n availableSlots--; // reduce by 1 since either side of the slots not available\n } else {\n continue; // entire row is available - no need to reduce the available slots\n }\n }\n\n return availableSlots;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxNumberOfFamilies(int n, vector>& reservedSeats) {\n unordered_map> o;\n \n for (auto r : reservedSeats) {\n \n o[r[0]].push_back(r[1]);\n }\n \n int ans = 2 * (n - o.size()); // seats with no occupancy directly adding 2\n \n\t\t// if we iterate from 1 to n (10 ^ 9) we cross time limit\n for (auto p : o) {\n \n // get reserved seats\n vector seats = p.second;\n \n \n int occupied_mask = 0;\n \n // representing occupied seats as bits\n for (int s : seats) {\n if (s > 1 && s < 10) {\n occupied_mask += (int)pow(2, 10 - s);\n }\n }\n \n // checking 3 seating configurations\n int masks[3] = {480, 120, 30};\n \n int row_ans = 0;\n bool res1 = (masks[0] & occupied_mask) == 0;\n bool res2 = (masks[1] & occupied_mask) == 0;\n bool res3 = (masks[2] & occupied_mask) == 0;\n \n\t\t\t// if all 3 configurations are empty, 2 families\n\t\t\t// if either one of them are empty, 1 family\n if (res1 && res2 && res3) row_ans += 2;\n else if (res1 || res2 || res3) row_ans += 1;\n \n \n ans += row_ans;\n \n }\n \n return ans;\n }\n};" }, { "title": "Maximum Compatibility Score Sum", "algo_input": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).\n\nThe survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).\n\nEach student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.\n\n\n\tFor example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same.\n\n\nYou are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.\n\nGiven students and mentors, return the maximum compatibility score sum that can be achieved.\n\n \nExample 1:\n\nInput: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput: 8\nExplanation: We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.\n\n\nExample 2:\n\nInput: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput: 0\nExplanation: The compatibility score of any student-mentor pair is 0.\n\n\n \nConstraints:\n\n\n\tm == students.length == mentors.length\n\tn == students[i].length == mentors[j].length\n\t1 <= m, n <= 8\n\tstudents[i][k] is either 0 or 1.\n\tmentors[j][k] is either 0 or 1.\n\n", "solution_py": "import heapq\nfrom collections import defaultdict\n\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m, n = len(students), len(students[0])\n def hamming(student, mentor):\n return sum([int(student[i] != mentor[i]) for i in range(n)])\n\n pq = [(0, 0, '0'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)\n optimal = defaultdict(lambda:float('inf'))\n\n while pq: # O(V)\n cost, i, mentor_status = heapq.heappop(pq) # O(logV)\n\n # early stopping with termination condition\n if i == m:\n return m * n - cost\n\n # generate successors. The next student to be assigned is at index i\n for j, mentor in enumerate(mentors): # O(m)\n if mentor_status[j] != '1':\n new_cost = cost + hamming(students[i], mentor)\n new_mentor_status = mentor_status[:j] + '1' + mentor_status[j+1:]\n\n # update optimal cost if a new successor appears with lower cost to the same node\n if new_cost < optimal[(i+1, new_mentor_status)]:\n optimal[(i+1, new_mentor_status)] = new_cost\n heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV)\n\n return 0", "solution_js": "var maxCompatibilitySum = function(students, mentors) {\n const m = students.length;\n const n = students[0].length;\n\n let max = 0;\n\n dfs(0, (1 << m) - 1, 0);\n\n return max;\n\n function dfs(studentIdx, bitmask, scoreTally) {\n if (studentIdx === m) {\n max = Math.max(max, scoreTally);\n\n return;\n }\n\n for (let mentorIdx = 0; mentorIdx < m; ++mentorIdx) {\n if (bitmask & (1 << mentorIdx)) {\n const matchScore = hammingDistance(students[studentIdx], mentors[mentorIdx]);\n const setMask = bitmask ^ (1 << mentorIdx);\n\n dfs(studentIdx + 1, setMask, scoreTally + matchScore);\n }\n }\n\n return;\n }\n\n function hammingDistance(studentsAnswers, mentorsAnswers) {\n let matches = 0;\n\n for (let j = 0; j < n; ++j) {\n if (studentsAnswers[j] === mentorsAnswers[j]) ++matches;\n }\n\n return matches;\n }\n};", "solution_java": "class Solution {\n int max;\n public int maxCompatibilitySum(int[][] students, int[][] mentors) {\n boolean[] visited = new boolean[students.length];\n helper(visited, students, mentors, 0, 0);\n return max;\n }\n public void helper(boolean[] visited, int[][] students, int[][] mentors, int pos, int score){\n if(pos >= students.length){\n max = Math.max(max, score);\n return;\n }\n for(int i = 0; i < mentors.length; i++)\n if(!visited[i]){\n visited[i] = true;\n helper(visited, students, mentors, pos + 1, score + score(students[pos], mentors[i]));\n visited[i] = false;\n }\n }\n public int score(int[] a, int[] b){\n int count = 0;\n\n for(int i = 0; i < b.length; i++)\n if(a[i] == b[i]) count += 1;\n return count;\n }\n}", "solution_c": "class Solution {\n // Calculating compatibility scores of ith student and jth mentor\n int cal(int i,int j,vector>& arr1,vector>& arr2){\n int cnt=0;\n for(int k=0;k>& arr1,vector>& arr2,vector& vis){\n if(i==m){\n return 0;\n }\n int ans = 0;\n for(int j=0;j>& students, vector>& mentors) {\n int m = students.size();\n vector vis(m,0); // To keep track of which mentor is already paired up\n return helper(0,m,students,mentors,vis);\n }\n};" }, { "title": "Sum of Unique Elements", "algo_input": "You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.\n\nReturn the sum of all the unique elements of nums.\n\n \nExample 1:\n\nInput: nums = [1,2,3,2]\nOutput: 4\nExplanation: The unique elements are [1,3], and the sum is 4.\n\n\nExample 2:\n\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: There are no unique elements, and the sum is 0.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5]\nOutput: 15\nExplanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n hashmap = {}\n for i in nums:\n if i in hashmap.keys():\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n sum = 0\n for k, v in hashmap.items():\n if v == 1: sum += k\n return sum", "solution_js": "var sumOfUnique = function(nums) {\n let obj = {}\n let sum = 0\n // count frequency of each number\n for(let num of nums){\n if(obj[num] === undefined){\n sum += num\n obj[num] = 1\n }else if(obj[num] === 1){\n sum -= num\n obj[num] = -1\n }\n }\n\n return sum\n};", "solution_java": "class Solution {\n public int sumOfUnique(int[] nums) {\n int res = 0;\n Map map = new HashMap<>();\n for(int i = 0;i& nums)\n {\n int sum=0;\n mapmp;\n\n for(auto x:nums)\n mp[x]++;\n\n for(auto m:mp)\n {\n if(m.second==1)\n sum+=m.first;\n }\n return sum;\n }\n};" }, { "title": "Dinner Plate Stacks", "algo_input": "You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.\n\nImplement the DinnerPlates class:\n\n\n\tDinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity.\n\tvoid push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity.\n\tint pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.\n\tint popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.\n\n\n \nExample 1:\n\nInput\n[\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]\nOutput\n[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\n\nExplanation: \nDinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n ﹈ ﹈ ﹈\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n ﹈ ﹈ ﹈\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n ﹈ ﹈ ﹈ \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n ﹈ ﹈ \nD.pop() // Returns 4. The stacks are now: 1 3 \n ﹈ ﹈ \nD.pop() // Returns 3. The stacks are now: 1 \n ﹈ \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.\n\n\n \nConstraints:\n\n\n\t1 <= capacity <= 2 * 104\n\t1 <= val <= 2 * 104\n\t0 <= index <= 105\n\tAt most 2 * 105 calls will be made to push, pop, and popAtStack.\n\n", "solution_py": "class DinnerPlates:\n\n def __init__(self, capacity: int):\n self.heap = []\n self.stacks = []\n self.capacity = capacity\n\n def push(self, val: int) -> None:\n if self.heap:\n index = heapq.heappop(self.heap)\n if index < len(self.stacks):\n self.stacks[index].append(val)\n else:\n self.push(val)\n elif self.stacks:\n lastStack = self.stacks[-1]\n if len(lastStack) != self.capacity:\n lastStack.append(val)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n else:\n stack = deque()\n stack.append(val)\n self.stacks.append(stack)\n \n def pop(self) -> int:\n while self.stacks:\n lastStack = self.stacks[-1]\n if lastStack:\n val = lastStack.pop()\n if not lastStack:\n self.stacks.pop()\n return val\n else:\n self.stacks.pop()\n return -1\n\n def popAtStack(self, index: int) -> int:\n if index == len(self.stacks) - 1:\n return self.pop()\n if index < len(self.stacks):\n stack = self.stacks[index]\n if stack:\n val = stack.pop()\n heapq.heappush(self.heap, index)\n return val\n return -1\n\n\n# Your DinnerPlates object will be instantiated and called as such:\n# obj = DinnerPlates(capacity)\n# obj.push(val)\n# param_2 = obj.pop()\n# param_3 = obj.popAtStack(index)", "solution_js": "/**\n * @param {number} capacity\n */\nvar DinnerPlates = function(capacity) {\n this.capacity = capacity;\n this.stacks = [];\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nDinnerPlates.prototype.push = function(val) {\n var needNewStack = true\n for (var i = 0; i < this.stacks.length; i++) {\n if (this.stacks[i].length < this.capacity) {\n this.stacks[i].push(val);\n needNewStack = false;\n break;\n }\n }\n \n if (needNewStack) {\n this.stacks.push([val]);\n }\n \n};\n\n/**\n * @return {number}\n */\nDinnerPlates.prototype.pop = function() {\n var val = -1;\n for (var i = this.stacks.length - 1; i >= 0; i--) {\n if (this.stacks[i].length > 0) {\n val = this.stacks[i].pop();\n break;\n }\n }\n return val;\n};\n\n/** \n * @param {number} index\n * @return {number}\n */\nDinnerPlates.prototype.popAtStack = function(index) {\n // console.log(index, this.stacks, ...this.stacks[index])\n var val = -1;\n if (this.stacks[index] && this.stacks[index].length > 0) {\n val = this.stacks[index].pop()\n }\n return val;\n};\n\n/** \n * Your DinnerPlates object will be instantiated and called as such:\n * var obj = new DinnerPlates(capacity)\n * obj.push(val)\n * var param_2 = obj.pop()\n * var param_3 = obj.popAtStack(index)\n */", "solution_java": "class DinnerPlates {\n \n List> stack;\n PriorityQueue leftEmpty;\n PriorityQueue rightNonEmpty;\n int cap;\n public DinnerPlates(int capacity) {\n this.cap = capacity;\n this.stack = new ArrayList<>();\n this.leftEmpty = new PriorityQueue<>();\n this.rightNonEmpty = new PriorityQueue<>(Collections.reverseOrder());\n stack.add(new Stack<>());\n leftEmpty.offer(0);\n }\n \n public void push(int val) {\n while(!leftEmpty.isEmpty() && stack.get(leftEmpty.peek()).size() == cap) leftEmpty.poll();\n if(leftEmpty.isEmpty()) {\n stack.add(new Stack<>());\n leftEmpty.offer(stack.size() - 1);\n }\n Stack s = stack.get(leftEmpty.peek());\n if(s.isEmpty()) rightNonEmpty.offer(leftEmpty.peek());\n s.push(val);\n }\n \n public int pop() {\n while(!rightNonEmpty.isEmpty() && stack.get(rightNonEmpty.peek()).isEmpty()) rightNonEmpty.poll();\n if(rightNonEmpty.isEmpty()) {\n return -1;\n } \n Stack s = stack.get(rightNonEmpty.peek());\n if(s.size() == cap) leftEmpty.offer(rightNonEmpty.peek());\n return s.pop();\n }\n \n public int popAtStack(int index) {\n if(index >= stack.size()) return -1;\n Stack s = stack.get(index);\n if(s.isEmpty()) return -1;\n if(s.size() == cap) leftEmpty.offer(index);\n return s.pop();\n }\n}\n\n/**\n * Your DinnerPlates object will be instantiated and called as such:\n * DinnerPlates obj = new DinnerPlates(capacity);\n * obj.push(val);\n * int param_2 = obj.pop();\n * int param_3 = obj.popAtStack(index);\n */", "solution_c": "class DinnerPlates {\npublic:\n map>mp;\n setempty;\n int cap;\n DinnerPlates(int capacity) \n {\n this->cap=capacity;\n }\n \n void push(int val) \n {\n if(empty.size()==0)\n {\n empty.insert(mp.size());\n }\n mp[*empty.begin()].push(val);\n if(mp[*empty.begin()].size()==cap)\n {\n empty.erase(empty.begin());\n }\n }\n int pop() \n {\n if(mp.size()==0)\n {\n return -1;\n }\n int index=mp.rbegin()->first;\n int val=mp[index].top();\n mp[index].pop();\n empty.insert(index);\n if(mp[index].size()==0)\n {\n mp.erase(index);\n }\n return val;\n }\n \n int popAtStack(int index) \n {\n if(mp.size()==0||mp.find(index)==mp.end())\n {\n return -1;\n }\n int val=mp[index].top();\n mp[index].pop();\n empty.insert(index);\n if(mp[index].size()==0)\n {\n mp.erase(index);\n }\n return val;\n }\n};" }, { "title": "Split Linked List in Parts", "algo_input": "Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.\n\nThe length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.\n\nThe parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.\n\nReturn an array of the k parts.\n\n \nExample 1:\n\nInput: head = [1,2,3], k = 5\nOutput: [[1],[2],[3],[],[]]\nExplanation:\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput: [[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation:\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 1000].\n\t0 <= Node.val <= 1000\n\t1 <= k <= 50\n\n", "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n length = 0\n cur = head\n while cur:\n length += 1\n cur = cur.next\n # DON'T do following since this makes head become null\n # while head:\n # length += 1\n # head = head.next\n\n # calculate the base size and the number of parts contain extra number\n size, extra = length // k, length % k\n\n # create empty list to store split parts\n res = [[] for _ in range(k)]\n\n # use two ptrs to split parts\n prev, cur = None, head\n\n for i in range(k):\n res[i] = cur\n # if this part contains extra number, it has (size+1) number\n for j in range(size + (1 if extra > 0 else 0)):\n prev, cur = cur, cur.next\n if prev: prev.next = None\n extra -= 1\n\n return res", "solution_js": "var splitListToParts = function(head, k) {\n let length = 0, current = head, parts = [];\n\n while (current) {\n length++;\n current = current.next;\n }\n\n let base_size = Math.floor(length / k), extra = length % k;\n current = head;\n\n for (let i = 0; i < k; i++) {\n let part_size = base_size + (extra > 0 ? 1 : 0);\n let part_head = null, part_tail = null;\n\n for (let j = 0; j < part_size; j++) {\n if (!part_head) {\n part_head = part_tail = current;\n } else {\n part_tail.next = current;\n part_tail = part_tail.next;\n }\n\n if (current) {\n current = current.next;\n }\n }\n\n if (part_tail) {\n part_tail.next = null;\n }\n\n parts.push(part_head);\n extra = Math.max(extra - 1, 0);\n }\n\n return parts;\n};", "solution_java": "class Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n ListNode[] arr=new ListNode[k];\n\n if(k<2 || head==null || head.next==null){\n arr[0]=head;\n return arr;\n }\n\n ListNode temp=head;\n int len=1;\n while(temp.next!=null){\n len++;\n temp=temp.next;\n }\n\n int partition= len/k; //no of part 3\n int extra=len%k; //extra node 1 0\n\n ListNode curr=head;\n ListNode prev=null;\n int index=0;\n while(head!=null){\n arr[index++]=curr;\n for(int i=0; i0){\n prev=curr;\n curr=curr.next;\n extra--;\n }\n head=curr;\n prev.next=null;\n\n }\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector splitListToParts(ListNode* head, int k)\n {\n vectorans;\n int len=0;\n ListNode*temp=head;\n while(temp!=NULL)\n len++,temp=temp->next;\n\n int y=len/k , z=len%k;\n\n while(head !=NULL)\n {\n ans.push_back(head);\n int count=1;\n while(head!=NULL && countnext,count++;\n\n if(z && y)\n {\n head=head->next;z--;\n }\n if(head==NULL) continue;\n ListNode*temp=head->next;\n head->next=NULL;\n head=temp;\n }\n while(ans.size() int:\n #dict to store valid substrings and their respective occurences count\n d = defaultdict(int)\n #find longest substrings that has k unique chars\n #counter dict for char count and make sure unique char count is not exceeded\n counter = defaultdict(int)\n #init left and right pointers of sliding window\n r = l = 0\n #iterate right pointer\n while r < len(s):\n counter[s[r]] += 1\n \n #invalid window found, so make it valid again\n #len of window is greater than minSize\n while (r - l + 1) > minSize:\n counter[s[l]] -= 1\n #remove the key from dict for unique char count if it becomes zero\n if counter[s[l]] == 0:\n del counter[s[l]]\n #increment the left pointer to make it a valid window\n l += 1\n\n #valid window size (minSize) and unique char count is lesser than or equal to maxLetters\n if r - l + 1 == minSize and len(counter) <= maxLetters:\n #increment count of the occurence of the substring\n d[s[l:r+1]] += 1\n \n #make sure to update right pointer only after an iteration\n r += 1\n \n #return the count of substring with max occurence\n #edge case with no substring\n return max(d.values()) if d else 0", "solution_js": "var maxFreq = function(s, maxLetters, minSize, maxSize) {\n\n let output = 0;\n\n let left = 0, right = 0;\n\n let map = {};\n\n let map2 = {};\n\n let count = 0;\n\n while(right < s.length){\n\n if(map[s[right]] === undefined){ // adding letters to map to keep track of occurences (count)\n map[s[right]] = 1;\n count++;\n\n } else {\n if(map[s[right]] === 0){\n count++;\n }\n map[s[right]]++;\n }\n\n if(right - left + 1 > minSize) { // once over minSize removing occurence of left most letter from map and adjusting count\n\n map[s[left]]--;\n if(map[s[left]] < 1){\n count--;\n }\n left++;\n }\n\n if(right - left + 1 >= minSize && count <= maxLetters){\n map2[s.substring(left, right + 1)] = (map2[s.substring(left, right + 1)] || 0) + 1; // if subsitrng meets constraints of size and count add to map2;\n }\n\n right++;\n }\n\n Object.entries(map2).map(([key, val]) => output = Math.max(output, val)); // get largest value in map2\n\n return output;\n\n};", "solution_java": "class Solution {\n public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {\n Map count = new HashMap<>();\n int ans = 0;\n int n = s.length();\n \n for(int i=0;i+minSize-1 hs = new HashSet<>();\n for(int j=0;j st;\n unordered_map mp;\n \n i = 0, j = 0;\n while(i <= n - minSize && j < n)\n {\n temp += s[j];\n st[s[j]] += 1;;\n if(temp.length() == minSize)\n {\n if(st.size() <= maxLetters)\n mp[temp] += 1;\n i += 1;\n st[temp[0]] -= 1;\n if(st[temp[0]] == 0)\n st.erase(temp[0]);\n temp.erase(temp.begin());\n }\n j += 1;\n }\n for(auto el : mp)\n ans = max(ans, el.second);\n return ans;\n }\n};" }, { "title": "Text Justification", "algo_input": "Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.\n\nYou should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.\n\nExtra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n\nFor the last line of text, it should be left-justified, and no extra space is inserted between words.\n\nNote:\n\n\n\tA word is defined as a character sequence consisting of non-space characters only.\n\tEach word's length is guaranteed to be greater than 0 and not exceed maxWidth.\n\tThe input array words contains at least one word.\n\n\n \nExample 1:\n\nInput: words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\nOutput:\n[\n   \"This    is    an\",\n   \"example  of text\",\n   \"justification.  \"\n]\n\nExample 2:\n\nInput: words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\nOutput:\n[\n  \"What   must   be\",\n  \"acknowledgment  \",\n  \"shall be        \"\n]\nExplanation: Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.\n\nExample 3:\n\nInput: words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\nOutput:\n[\n  \"Science  is  what we\",\n \"understand      well\",\n  \"enough to explain to\",\n  \"a  computer.  Art is\",\n  \"everything  else  we\",\n  \"do                  \"\n]\n\n \nConstraints:\n\n\n\t1 <= words.length <= 300\n\t1 <= words[i].length <= 20\n\twords[i] consists of only English letters and symbols.\n\t1 <= maxWidth <= 100\n\twords[i].length <= maxWidth\n\n", "solution_py": "class Solution:\n def fullJustify(self, words: List[str], maxwidth: int) -> List[str]:\n curr = 0\n last = []\n res = []\n for i in words:\n if curr + len(i) + len(res) <= maxwidth:\n curr += len(i)\n res.append(i)\n else:\n last.append(res)\n curr = len(i)\n res = [i]\n last.append(res)\n ans = []\n for idx ,row in enumerate(last):\n x = maxwidth-len(\"\".join(row))\n t = len(row)-1\n if t == 0:\n ans.append(row[0] + \" \"*(x))\n elif idx != len(last)-1:\n spaces = x//t\n rem = x%t\n res = row[0]\n for i in row[1:]:\n temp = spaces\n if rem:\n temp += 1\n rem -= 1\n res = res + \" \"*temp + i\n # print(res, temp)\n ans.append(res)\n else:\n res = row[0]\n for i in row[1:]:\n res = res + ' '+i\n res = res + \" \"*(maxwidth-len(res))\n ans.append(res)\n\n return ans", "solution_js": "/**\n * @param {string[]} words\n * @param {number} maxWidth\n * @return {string[]}\n */\nvar fullJustify = function(words, maxWidth) {\n if (!words || !words.length) return;\n \n const wordRows = [];\n let wordCols = [];\n let count = 0;\n words.forEach((word, i) => {\n if ((count + word.length + wordCols.length) > maxWidth) {\n wordRows.push(wordCols);\n wordCols = [];\n count = 0;\n }\n \n wordCols.push(word);\n count += word.length;\n\n if (i === words.length - 1) {\n wordRows.push(wordCols);\n } \n });\n \n return wordRows.map((rowWords, i) => justifyText(rowWords, maxWidth, i === wordRows.length - 1));\n};\n\nconst justifyText = (rowWords, maxWidth, isLastLine) => {\n let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0);\n \n if (rowWords.length === 1) {\n return rowWords[0] + ' '.repeat(spaces); \n }\n \n if (isLastLine) {\n spaces -= rowWords.length - 1\n return rowWords.join(' ') + ' '.repeat(spaces); \n }\n \n let index = rowWords.length - 1;\n let justifiedWord = '';\n while (rowWords.length > 0) {\n const repeater = Math.floor(spaces / (rowWords.length - 1));\n const word = rowWords.pop();\n\n if (index === 0) {\n justifiedWord = word + justifiedWord;\n } else if (index === 1) {\n justifiedWord = ' '.repeat(spaces) + word + justifiedWord;\n } else {\n justifiedWord = ' '.repeat(repeater) + word + justifiedWord;\n }\n \n index--;\n spaces -= repeater;\n }\n\n return justifiedWord;\n}", "solution_java": "class Solution {\n public List fullJustify(String[] words, int maxWidth) {\n List unBalanced = new ArrayList<>();\n List balanced = new ArrayList<>();\n int numSpaces = 0;\n\n StringBuffer sb = new StringBuffer();\n //Following code creates a list of unbalanced lines by appending words and 1 space between them\n for(String word : words){\n\n if(sb.length() == 0){\n sb.append(word);\n }else{\n if(sb.length() + 1 + word.length() <= maxWidth){\n sb.append(\" \"+word);\n }else{\n unBalanced.add(sb.toString());\n sb = new StringBuffer(word);\n }\n }\n\n }\n\n if(sb.length() >0){\n unBalanced.add(sb.toString());\n }\n\n for(int j = 0; j < unBalanced.size(); j++){\n String line = unBalanced.get(j);\n numSpaces = maxWidth - line.length();\n StringBuffer lineB = new StringBuffer(line);\n //This if block handles either last line or the scenario where in there's only one word in any sentence and hence no spaces\n if(j == unBalanced.size()-1 || !line.contains(\" \")){\n int tempSpaces = maxWidth - lineB.length();\n while(tempSpaces > 0){\n lineB.append(\" \");\n tempSpaces --;\n }\n balanced.add(lineB.toString());\n continue;\n };\n // The following block checks for each character and appends 1 space during each loop\n //If there are still spaces left at the end of the String, again start from beggining and append spaces after each word\n while(numSpaces > 0){\n int i = 0;\n while(i < lineB.length() - 1){\n if( lineB.charAt(i) == ' ' && lineB.charAt(i+1) != ' '){\n lineB.insert(i+1, ' ');\n i++;\n numSpaces --;\n if(numSpaces == 0) break;\n }\n i++;\n }\n }\n balanced.add(lineB.toString());\n }\n\n return balanced;\n }\n}", "solution_c": "class Solution {\n string preprocessing(string &f, int space, int limit)\n {\n int noofspace = limit-f.size()+space;\n int k = 0;\n string r = \"\";\n while(space)\n {\n int n = noofspace / space;\n if((noofspace%space) != 0)\n n += 1;\n noofspace -= n;\n while(f[k] != ' ')\n {\n r += f[k];\n k++;\n }\n k++;\n while(n--)\n {\n r += ' ';\n }\n space--;\n }\n while(k < f.size())\n {\n r += f[k];\n k++;\n }\n while(noofspace--)\n r += ' ';\n return r;\n }\npublic:\n vector fullJustify(vector& words, int maxWidth) {\n vector ans;\n string f = \"\";\n int space = 0;\n for(string &str : words)\n {\n if((f.size() + str.size() + 1) <= maxWidth && f.size() > 0)\n {\n f += ' ' + str;\n space++;\n }\n else\n {\n if(f.size() > 0){\n f = preprocessing(f, space, maxWidth);\n ans.push_back(f);\n f = \"\";\n }\n f += str;\n space = 0;\n }\n }\n int sz = f.size();\n while(sz < maxWidth)\n {\n f += ' ';\n sz++;\n }\n ans.push_back(f);\n return ans;\n }\n};" }, { "title": "Range Sum Query - Immutable", "algo_input": "Given an integer array nums, handle multiple queries of the following type:\n\n\n\tCalculate the sum of the elements of nums between indices left and right inclusive where left <= right.\n\n\nImplement the NumArray class:\n\n\n\tNumArray(int[] nums) Initializes the object with the integer array nums.\n\tint sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n\n\n \nExample 1:\n\nInput\n[\"NumArray\", \"sumRange\", \"sumRange\", \"sumRange\"]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\nOutput\n[null, 1, -1, -3]\n\nExplanation\nNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-105 <= nums[i] <= 105\n\t0 <= left <= right < nums.length\n\tAt most 104 calls will be made to sumRange.\n\n", "solution_py": "class NumArray:\n\n def __init__(self, nums: List[int]):\n self.nums, Sum = [], 0\n for num in nums:\n Sum += num\n self.nums.append(Sum)\n\n def sumRange(self, left: int, right: int) -> int:\n return self.nums[right] - self.nums[left - 1] if left - 1 >= 0 else self.nums[right]", "solution_js": "var NumArray = function(nums) {\n this.nums = nums;\n};\n\nNumArray.prototype.sumRange = function(left, right) {\n let sum = 0;\n for(let i = left; i <= right; i++) sum += this.nums[i]\n return sum\n};", "solution_java": "class NumArray {\n int [] prefix;\n public NumArray(int[] nums) {\n int n = nums.length;\n prefix = new int[n];\n prefix[0] = nums[0];\n for(int i = 1; i < n; i++){\n prefix[i] = nums[i] + prefix[i - 1];\n }\n }\n\n public int sumRange(int left, int right) {\n if(left == 0){\n return prefix[right];\n }\n return prefix[right] - prefix[left - 1];\n }\n}", "solution_c": "class NumArray {\npublic:\n\tvectorarr;\n\tNumArray(vector& nums) {\n\t\tarr=nums;\n\t}\n\n\tint sumRange(int left, int right) {\n\t\tint sum=0;\n\t\tfor(int i=left;i<=right;i++) sum+=arr[i];\n\t\treturn sum;\n\t}\n};" }, { "title": "XOR Operation in an Array", "algo_input": "You are given an integer n and an integer start.\n\nDefine an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\n\nReturn the bitwise XOR of all elements of nums.\n\n \nExample 1:\n\nInput: n = 5, start = 0\nOutput: 8\nExplanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.\n\n\nExample 2:\n\nInput: n = 4, start = 3\nOutput: 8\nExplanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\t0 <= start <= 1000\n\tn == nums.length\n\n", "solution_py": "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n nums = [start + 2*i for i in range(n)] #generate list of numbers\n ans = nums[0]\n for i in range(1,n):\n ans = ans^nums[i] # XOR operation\n return ans\n \n ", "solution_js": "var xorOperation = function(n, start) {\n let arr = []\n for(let i=0; i a^c)\n};", "solution_java": "class Solution {\n public int xorOperation(int n, int start) {\n int nums[]=new int[n];\n for(int i=0;i int:\n return sum(A) - max((len(A) - i) * n for i, n in enumerate(sorted(A)))", "solution_js": "/**\n * @param {number[]} beans\n * @return {number}\n */\n // time complexity -> O(NlogN) and Space is O(logN) due to sorting. \n var minimumRemoval = function(beans) {\n beans.sort((a, b) => a - b);\n let frontSum = beans.reduce((sum , a) => sum + a, 0);\n let backSum = 0;\n let done = 0;\n let result = Number.MAX_SAFE_INTEGER;\n for(let j = beans.length - 1; j >= 0; j--){\n frontSum -= beans[j];\n count = frontSum + (backSum - (beans[j] * done));\n result = Math.min(result, count);\n done++;\n backSum += beans[j];\n }\n return result;\n};", "solution_java": "class Solution {\n public long minimumRemoval(int[] beans) {\n Arrays.parallelSort(beans);\n long sum=0,min=Long.MAX_VALUE;\n int n=beans.length;\n for(int i:beans)\n sum+=i;\n for(int i=0;i& beans) {\n long long n = beans.size();\n sort(beans.begin(), beans.end());\n long long sum = 0;\n for(int i=0; i curr)\n ans = curr;\n }\n return ans; \n } \n};" }, { "title": "Maximum Non Negative Product in a Matrix", "algo_input": "You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.\n\nAmong all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.\n\nReturn the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.\n\nNotice that the modulo is performed after getting the maximum product.\n\n \nExample 1:\n\nInput: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput: -1\nExplanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\n\n\nExample 2:\n\nInput: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput: 8\nExplanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\n\n\nExample 3:\n\nInput: grid = [[1,3],[0,-4]]\nOutput: 0\nExplanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 15\n\t-4 <= grid[i][j] <= 4\n\n", "solution_py": "class Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n \"\"\"Return maximum & minimum products ending at (i, j).\"\"\"\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007", "solution_js": "var maxProductPath = function(grid) {\n const R = grid.length, C = grid[0].length;\n if (R === 0 || C === 0)\n return -1;\n \n const mat = [...Array(R)].map(() => [...Array(C)].map(() => new Array(2)));\n \n mat[0][0] = [grid[0][0], grid[0][0]];\n for (let i = 1; i < R; i++)\n mat[i][0] = [mat[i-1][0][0]*grid[i][0], mat[i-1][0][1]*grid[i][0]];\n \n for (let i = 1; i < C; i++)\n mat[0][i] = [mat[0][i-1][0]*grid[0][i], mat[0][i-1][1]*grid[0][i]];\n \n for (let i = 1; i < R; i++) {\n for (let j = 1; j < C; j++) {\n const max = Math.max(mat[i-1][j][0], mat[i][j-1][0]),\n min = Math.min(mat[i-1][j][1], mat[i][j-1][1]);\n if (grid[i][j] >= 0)\n mat[i][j] = [max*grid[i][j], min*grid[i][j]];\n else\n mat[i][j] = [min*grid[i][j], max*grid[i][j]];\n }\n }\n \n return mat[R-1][C-1][0] >= 0 ? mat[R-1][C-1][0] % (10**9+7) : -1;\n};", "solution_java": "class Solution {\n public class Pair{\n long min=Integer.MAX_VALUE,max=Integer.MIN_VALUE;\n Pair(){\n\n }\n Pair(long min,long max){\n this.min=min;\n this.max=max;\n }\n }\n public int maxProductPath(int[][] grid) {\n Pair[][] dp=new Pair[grid.length][grid[0].length];\n for(int r=grid.length-1;r>=0;r--){\n for(int c=grid[0].length-1;c>=0;c--){\n if(r==grid.length-1 && c==grid[0].length-1){\n dp[r][c]=new Pair(grid[r][c],grid[r][c]);\n }else{\n Pair hor=(c==grid[0].length-1)?new Pair():dp[r][c+1];\n Pair ver=(r==grid.length-1)?new Pair():dp[r+1][c];\n long min,max;\n if(grid[r][c]>=0){\n max=Math.max(hor.max,ver.max);\n min=Math.min(hor.min,ver.min);\n }else{\n min=Math.max(hor.max,ver.max);\n max=Math.min(hor.min,ver.min);\n }\n dp[r][c]=new Pair(min*grid[r][c],max*grid[r][c]);\n }\n }\n }\n int mod=(int)1e9 +7;\n return dp[0][0].max<0?-1:(int)(dp[0][0].max%mod);\n }\n}", "solution_c": "const long long MOD = 1e9 + 7;\nclass Solution {\npublic:\n int maxProductPath(vector>& grid) {\n long long mx[20][20] = {0};\n long long mn[20][20] = {0};\n int row = grid.size(), col = grid[0].size();\n \n // Init\n mx[0][0] = mn[0][0] = grid[0][0];\n \n // Init the row0 and col0 to be the continuous multiply of the elements.\n for(int i = 1; i < row; i++){\n mx[i][0] = mn[i][0] = mx[i - 1][0] * grid[i][0];\n }\n for(int j = 1; j < col; j++){\n mx[0][j] = mn[0][j] = mx[0][j - 1] * grid[0][j];\n }\n \n // DP as the explanation picture shows\n for(int i = 1; i < row; i++){\n for(int j = 1; j < col; j++){\n mx[i][j] = max(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]);\n mn[i][j] = min(max(mx[i - 1][j], mx[i][j - 1]) * grid[i][j], min(mn[i - 1][j], mn[i][j - 1]) * grid[i][j]);\n }\n }\n \n return mx[row - 1][col - 1] < 0 ? -1 : mx[row - 1][col - 1] % MOD;\n }\n};" }, { "title": "Expression Add Operators", "algo_input": "Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value.\n\nNote that operands in the returned expressions should not contain leading zeros.\n\n \nExample 1:\n\nInput: num = \"123\", target = 6\nOutput: [\"1*2*3\",\"1+2+3\"]\nExplanation: Both \"1*2*3\" and \"1+2+3\" evaluate to 6.\n\n\nExample 2:\n\nInput: num = \"232\", target = 8\nOutput: [\"2*3+2\",\"2+3*2\"]\nExplanation: Both \"2*3+2\" and \"2+3*2\" evaluate to 8.\n\n\nExample 3:\n\nInput: num = \"3456237490\", target = 9191\nOutput: []\nExplanation: There are no expressions that can be created from \"3456237490\" to evaluate to 9191.\n\n\n \nConstraints:\n\n\n\t1 <= num.length <= 10\n\tnum consists of only digits.\n\t-231 <= target <= 231 - 1\n\n", "solution_py": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n s=num[0]\n q=[\"+\",\"-\",\"*\",\"\"]\n ans=[]\n def cal(w):\n i=1\n while i {\n if(idx >= num.length) {\n if(sum === target) {\n res.push(path);\n }\n return null;\n }\n\n for(let j = idx; j < num.length; j++) {\n\n if(j !== idx && num[idx] === \"0\")\n break;\n\n let n = Number(num.slice(idx, j+1));\n\n if(idx === 0) {\n helper(j + 1, sum + n, sum + n, path + n);\n } else {\n helper(j + 1, sum + n, n, path + \"+\" + n);\n\n helper(j + 1, sum - n, 0 - n, path + \"-\" + n);\n\n helper(j + 1, sum - prev + (prev * n), prev * n, path + \"*\" + n);\n }\n }\n\n }\n\n helper(i, 0, 0, \"\");\n\n return res;\n};", "solution_java": "class Solution {\n String s;\n Listresult;\n int target;\n public void operator(int i,int prev,long prod,long mid,String exp,Listl){\n if(i==l.size()){\n if(mid+prod==target)\n result.add(exp);\n return;\n }\n if(prev==-1){\n operator(i+1,0,-1*l.get(i)*l.get(i-1),mid+l.get(i-1),exp+\"*\"+l.get(i),l);\n }else if(prev==1){\n operator(i+1,0,l.get(i)*l.get(i-1),mid-l.get(i-1),exp+\"*\"+l.get(i),l);\n }else{\n operator(i+1,0,prod*l.get(i),mid,exp+\"*\"+l.get(i),l);\n }\n operator(i+1,-1,0,mid+prod-l.get(i),exp+\"-\"+l.get(i),l);\n operator(i+1,1,0,mid+prod+l.get(i),exp+\"+\"+l.get(i),l);\n }\n public void rec(int in,Listl){\n if(in==s.length()){\n operator(1,1,0,l.get(0),l.get(0)+\"\",l);\n return;\n }\n if(s.charAt(in)=='0'){\n l.add(0L);\n rec(in+1,l);\n l.remove(l.size()-1);\n }else{\n for(int i=in;i addOperators(String num, int target) {\n result=new ArrayList<>();\n this.s=num;\n this.target=target;\n rec(0,new ArrayList<>(30));\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector res;\n string s;\n int target, n;\n void solve(int it, string path, long long resSoFar, long long prev){\n if(it == n){\n if(resSoFar == target) res.push_back(path);\n return;\n }\n long long num = 0;\n string tmp;\n\n for(auto j = it; j < n; j++){\n if(j > it && s[it] == '0') break;\n\n num = num * 10 + (s[j] - '0');\n tmp.push_back(s[j]);\n\n if(it == 0) solve(j + 1, tmp, num, num);\n else{\n solve(j + 1, path + \"+\" + tmp, resSoFar + num, num);\n solve(j + 1, path + '-' + tmp, resSoFar - num, -num);\n solve(j + 1, path + '*' + tmp, resSoFar - prev + prev * num, prev * num);\n }\n }\n\n }\n vector addOperators(string num, int target) {\n this -> target = target;\n s = num, n = num.size();\n\n solve(0, \"\", 0, 0);\n return res;\n }\n};" }, { "title": "Eliminate Maximum Number of Monsters", "algo_input": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.\n\nThe monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.\n\nYou have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start.\n\nYou lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.\n\nReturn the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.\n\n \nExample 1:\n\nInput: dist = [1,3,4], speed = [1,1,1]\nOutput: 3\nExplanation:\nIn the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\nAll 3 monsters can be eliminated.\n\nExample 2:\n\nInput: dist = [1,1,2,3], speed = [1,1,1,1]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.\n\n\nExample 3:\n\nInput: dist = [3,2,4], speed = [5,3,2]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.\n\n\n \nConstraints:\n\n\n\tn == dist.length == speed.length\n\t1 <= n <= 105\n\t1 <= dist[i], speed[i] <= 105\n\n", "solution_py": "class Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n for i, t in enumerate(sorted([(d - 1) // s for d, s in zip(dist, speed)])):\n if i > t:\n return i\n return len(dist) ", "solution_js": "/**\n * @param {number[]} dist\n * @param {number[]} speed\n * @return {number}\n */\nvar eliminateMaximum = function(dist, speed) {\n let res = 0;\n let len = dist.length;\n let map = new Map();\n for(let i=0; i a-b);\n // time to eliminate\n let t = 0;\n for(let i=0; i keys[i]-t){\n res += keys[i]-t;\n break;\n }else{\n res += c;\n t += c;\n }\n }\n\n return res;\n};", "solution_java": "class Solution {\n public int eliminateMaximum(int[] dist, int[] speed) {\n \n int n = dist.length;\n \n int[] time = new int[n];\n \n for(int i = 0; i < n; i++){\n time[i] = (int)Math.ceil(dist[i] * 1.0 / speed[i]);\n }\n \n Arrays.sort(time);\n \n int eliminated = 0;\n\t\t\n\t\t// At i = 0, minute = 0 ( therefore, we can use i in place of minute )\n \n for(int i = 0; i < n; i++){\n\t\t\t \n if(time[i] > i){ // At ith minute, eliminate the first monster arriving after ith minute\n eliminated++;\n }else{\n break; // Monster reached the city\n }\n }\n \n return eliminated;\n }\n}", "solution_c": "class Solution {\npublic:\n int eliminateMaximum(vector& dist, vector& speed) {\n priority_queue, greater> pq;\n \n for(int i = 0; i < dist.size(); ++i)\n pq.push(ceil((double)dist[i] / speed[i] ));\n \n int t = 0;\n while(pq.size() && pq.top() > t++) pq.pop();\n return dist.size() - pq.size();\n }\n};" }, { "title": "Invert Binary Tree", "algo_input": "Given the root of a binary tree, invert the tree, and return its root.\n\n \nExample 1:\n\nInput: root = [4,2,7,1,3,6,9]\nOutput: [4,7,2,9,6,3,1]\n\n\nExample 2:\n\nInput: root = [2,1,3]\nOutput: [2,3,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, 100].\n\t-100 <= Node.val <= 100\n\n", "solution_py": "class Solution(object):\n def invertTree(self, root):\n # Base case...\n if root == None:\n return root\n # swapping process...\n root.left, root.right = root.right, root.left\n # Call the function recursively for the left subtree...\n self.invertTree(root.left)\n # Call the function recursively for the right subtree...\n self.invertTree(root.right)\n return root # Return the root...", "solution_js": "var invertTree = function(root) {\n if (!root) return root;\n [root.left, root.right] = [root.right, root.left];\n invertTree(root.right)\n invertTree(root.left)\n return root\n};", "solution_java": "class Solution {\n public TreeNode invertTree(TreeNode root) {\n\n swap(root);\n return root;\n }\n\n private static void swap(TreeNode current) {\n if (current == null) {\n return;\n }\n\n swap(current.left);\n swap(current.right);\n\n TreeNode temp = current.left;\n current.left = current.right;\n current.right = temp;\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* invertTree(TreeNode* root) {\n if(root == NULL) return root;\n TreeNode* temp = root->left;\n root->left = root->right;\n root->right = temp;\n invertTree(root->left);\n invertTree(root->right);\n return root;\n }\n};" }, { "title": "Number of Dice Rolls With Target Sum", "algo_input": "You have n dice and each die has k faces numbered from 1 to k.\n\nGiven three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 1, k = 6, target = 3\nOutput: 1\nExplanation: You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\n\n\nExample 2:\n\nInput: n = 2, k = 6, target = 7\nOutput: 6\nExplanation: You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\n\n\nExample 3:\n\nInput: n = 30, k = 30, target = 500\nOutput: 222616187\nExplanation: The answer must be returned modulo 109 + 7.\n\n\n \nConstraints:\n\n\n\t1 <= n, k <= 30\n\t1 <= target <= 1000\n\n", "solution_py": "class Solution(object):\n def numRollsToTarget(self, n, k, target):\n \"\"\"\n :type n: int\n :type k: int\n :type target: int\n :rtype: int\n \"\"\"\n\n mem = {}\n\n def dfs(i,currSum):\n\n if currSum > target:\n return 0\n\n if i == n:\n if currSum == target:\n return 1\n return 0\n\n if (i,currSum) in mem:\n return mem[(i,currSum)]\n\n ans = 0\n for dicenumber in range(1,k+1):\n ans += dfs(i+1,currSum+dicenumber)\n\n mem[(i,currSum)] = ans\n\n return mem[(i,currSum)]\n\n return dfs(0,0) % (10**9 + 7)", "solution_js": "var numRollsToTarget = function(n, k, target) {\n if (n > target || n * k < target) return 0 //target is impossible to reach\n let arr = new Array(k).fill(1), depth = n //start the first layer of Pascal's N-ary Triangle.\n while (depth > 1) { //more layers of Triangle to fill out\n tempArr = [] //next layer of triangle. not done in place as previous layer's array values are needed\n for (let i = 0; i < arr.length + k - 1 && i <= target - n; i++) { //looping is bounded by size of next layer AND how much data we actually need\n let val = ((tempArr[i - 1] || 0) + (arr[i] || 0) - (arr[i - k] || 0)) % (1000000007) //current index value is the sum of K number of previous layer's values, once we hit K we add next and subtract last so we don't have to manually add all K values\n tempArr.push(val)\n }\n arr = tempArr\n depth -= 1\n }\n let ans = arr[target - n] //answer will be in target - nth index\n return ans < 0 ? ans + 1000000007 : ans\n};", "solution_java": "class Solution {\n public int numRollsToTarget(int n, int k, int target) {\n if (target < n || target > n*k) return 0;\n if (n == 1) return 1;\n\n int[][] dp = new int[n+1][n*k+1];\n for (int i = 1; i<= k; i++) {\n dp[1][i] = 1;\n }\n int mod = 1000000007;\n for (int i = 2; i <= n; i++) {\n for (int j = i; j <= i*k && j <= target; j++) {\n for (int x = 1; x <= k; x++) {\n if (j-x >= 1) {\n dp[i][j] += dp[i-1][j-x];\n if (dp[i][j] >= mod) {\n dp[i][j] %= mod;\n }\n }\n }\n }\n }\n return dp[n][target]%mod;\n }\n}", "solution_c": "class Solution {\npublic:\n\tint dp[31][1001];\n\tSolution(){\n\t\tmemset(dp,-1,sizeof(dp));\n\t}\n\tint help(int dno,int &tdice,int &tf,int target){\n\t\tif(target<0 or dno>tdice) return 0;\n\t\tif(target==0 and dno==tdice) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(dp[dno][target]!=-1) return dp[dno][target];\n\t\tint ans=0;\n\t\tfor(int i=1;i<=tf;i++){\n\t\t\tans=(ans%1000000007+help(dno+1,tdice,tf,target-i)%1000000007)%1000000007;\n\n\t\t}\n\t\treturn dp[dno][target]=ans;\n\t}\n\tint numRollsToTarget(int n, int k, int target) {\n\t return help(0,n,k,target);\n\n\t}\n};" }, { "title": "Remove Covered Intervals", "algo_input": "Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.\n\nThe interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.\n\nReturn the number of remaining intervals.\n\n \nExample 1:\n\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\n\nExample 2:\n\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= intervals.length <= 1000\n\tintervals[i].length == 2\n\t0 <= li < ri <= 105\n\tAll the given intervals are unique.\n\n", "solution_py": "class Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n\n intervals.sort(key = lambda x: (x[0], -x[1]))\n current, count = intervals[0], 1\n for i in range(1, len(intervals)):\n if current[0] <= intervals[i][0] and intervals[i][1] <= current[1]:\n continue\n current = intervals[i]\n count += 1\n return count\n\n# time and space complexity\n# time: O(nlog(n))\n# space: O(1)", "solution_js": "var removeCoveredIntervals = function(intervals) {\n intervals.sort((a,b)=> a[0]-b[0] || b[1]-a[1]);\n let overlap=0;\n for (i=1,prev=0; i= intervals[i][1]))\n\tif (intervals[prev][1] >= intervals[i][1]) // just look at 2nd index\n overlap++ // add to skipped elements\n else\n prev=i; // didn't overlap, so we can advance our previous element\n return intervals.length-overlap;\n};", "solution_java": "class Solution {\n public int removeCoveredIntervals(int[][] intervals) {\n if(intervals == null || intervals.length == 0) return 0;\n Arrays.sort(intervals, (i1,i2) -> (i1[0]==i2[0]?i2[1]-i1[1]:i1[0]-i2[0]));\n int c = intervals[0][0], d = intervals[0][1];\n int ans = intervals.length;\n for(int i=1;i>& intervals) \n {\n int cnt = 0, last = INT_MIN;\n sort(intervals.begin(), intervals.end(), \n [] (const vector& v1, const vector& v2) { \n if(v1[0] != v2[0]) return v1[0] < v2[0];\n else return v1[1] > v2[1];\n });\n\n for(int i=0; i last) last = intervals[i][1];\n }\n \n return intervals.size()-cnt;\n }\n}; " }, { "title": "Range Module", "algo_input": "A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.\n\nA half-open interval [left, right) denotes all the real numbers x where left <= x < right.\n\nImplement the RangeModule class:\n\n\n\tRangeModule() Initializes the object of the data structure.\n\tvoid addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.\n\tboolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.\n\tvoid removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).\n\n\n \nExample 1:\n\nInput\n[\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\nOutput\n[null, null, null, true, false, true]\n\nExplanation\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n\n\n \nConstraints:\n\n\n\t1 <= left < right <= 109\n\tAt most 104 calls will be made to addRange, queryRange, and removeRange.\n\n", "solution_py": "from bisect import bisect_left as bl, bisect_right as br\nclass RangeModule:\n\n def __init__(self):\n self._X = []\n\n def addRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) or idx(right) is odd, it's in a interval. So don't add it. \n # If idx(left) or idx(right) is even, it's not in any interval. So add it as new interval \n # Slice array[idx(left) : idx(right)]\n # 1) both odd: Nothing is added. Merge all middle intervals. \n # 2) both even: Add new intervals. Merge all middle intervals\n # 3) idx(left) is even: update start point of next interval with left\n # 4) idx(right) is even: update end point of previous interval with right\n # Bisect_left vs. Bisect_right\n # left need to proceed all interval closing at left, so use Bisect_left\n # right need to go after all interval openning at right, so use Bisect_right\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 0) + [right] * (j % 2 == 0)\n \n\n def queryRange(self, left: int, right: int) -> bool:\n # Main logic \n # If idx of left/right is odd, it's in a interval. Else it's not. \n # If idx of left&right is the same, they're in the same interval\n # Bisect_left vs. Bisect_right\n # [start, end). Start is included. End is not. \n # so use bisect_right for left \n # so use bisect_left for right \n i, j = br(self._X, left), bl(self._X, right)\n return i == j and i % 2 == 1\n \n\n def removeRange(self, left: int, right: int) -> None:\n # Main Logic \n # If idx(left) is odd, the interval that contains left need to change end point to left \n # If idx(right) is odd, the interval that contains right need to change start point to right\n # Else, everything from idx(left) to idx(right) is removed. Nothing is changed. \n # Bisect_left vs. Bisect_right\n # Same as addRange\n i, j = bl(self._X, left), br(self._X, right)\n self._X[i : j] = [left] * (i % 2 == 1) + [right] * (j % 2 == 1)", "solution_js": "var RangeModule = function() {\n this.ranges = []\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {void}\n */\n//Time: O(logN)\nRangeModule.prototype.addRange = function(left, right) {\n const lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n if (lIdx === this.ranges.length) {\n this.ranges.push(left)\n this.ranges.push(-right)\n } else if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n this.ranges.splice(lIdx, rIdx - lIdx, -right)\n } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) {\n this.ranges.splice(lIdx, rIdx - lIdx)\n } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n this.ranges.splice(lIdx, rIdx - lIdx, left, -right)\n } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) {\n this.ranges.splice(lIdx, rIdx - lIdx, left) \n }\n return null\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {boolean}\n */\n//Time: O(logN)\nRangeModule.prototype.queryRange = function(left, right) {\n const lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n if (lIdx === this.ranges.length) return false\n if (lIdx + 2 < rIdx) return false\n if (lIdx === rIdx) {\n return this.ranges[lIdx] < 0\n } else if (lIdx + 1 === rIdx) {\n return this.ranges[lIdx] === left || this.ranges[lIdx] === -right\n } {\n return this.ranges[lIdx] === left && Math.abs(this.ranges[lIdx + 1]) === right\n }\n};\n\n/** \n * @param {number} left \n * @param {number} right\n * @return {void}\n */\n//Time: O(logN)\nRangeModule.prototype.removeRange = function(left, right) {\n let lIdx = this.findIndex(left), rIdx = this.findIndex(-right)\n if (lIdx === this.ranges.length) return null\n if (this.ranges[lIdx] < 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n this.ranges.splice(lIdx, rIdx - lIdx, -left)\n } else if (this.ranges[lIdx] < 0 && this.ranges[rIdx] < 0) {\n this.ranges.splice(lIdx, rIdx - lIdx, -left, right)\n } else if (this.ranges[lIdx] > 0 && (this.ranges[rIdx] > 0 || rIdx === this.ranges.length)) {\n this.ranges.splice(lIdx, rIdx - lIdx)\n } else if (this.ranges[lIdx] > 0 && this.ranges[rIdx] < 0) {\n this.ranges.splice(lIdx, rIdx - lIdx, right) \n }\n // console.log(this.ranges)\n return null\n};\n\nRangeModule.prototype.findIndex = function(number) {\n let l = 0, r = this.ranges.length\n while(l < r) {\n const m = l + ((r - l) >> 1)\n if (Math.abs(this.ranges[m]) > Math.abs(number)) {\n r = m\n } else if (Math.abs(this.ranges[m]) < Math.abs(number)) {\n l = m + 1\n } else {\n if (number < 0) {\n l = m + 1\n } else {\n r = m\n }\n }\n }\n return l\n}\n\n/** \n * Your RangeModule object will be instantiated and called as such:\n * var obj = new RangeModule()\n * obj.addRange(left,right)\n * var param_2 = obj.queryRange(left,right)\n * obj.removeRange(left,right)\n */", "solution_java": "class RangeModule {\n TreeMap map;\n\n public RangeModule() {\n map = new TreeMap<>();\n }\n\n public void addRange(int left, int right) {\n // assume the given range [left, right), we want to find [l1, r1) and [l2, r2) such that l1 is the floor key of left, l2 is the floor key of right. Like this:\n // [left, right)\n // [l1, r1) [l2, r2)\n // Note: l2 could be the same as l1, so they are either both null or both non-null\n Integer l1 = map.floorKey(left);\n Integer l2 = map.floorKey(right);\n\n // try to visualize each case, and what to do based on r1\n if (l1 == null && l2 == null) {\n map.put(left, right);\n }\n else if (l1 != null && map.get(l1) >= left) {\n map.put(l1, Math.max(right, map.get(l2))); // r2 will always be greater than r1, so no need to check r1\n }\n else {\n map.put(left, Math.max(right, map.get(l2)));\n }\n\n // we don't want to remove the range starts at left, so left should be exclusive.\n // but we want to remove the one starts at right, so right should be inclusive.\n map.subMap(left, false, right, true).clear();\n }\n\n public boolean queryRange(int left, int right) {\n Integer l = map.floorKey(left);\n if (l != null && map.get(l) >= right) {\n return true;\n }\n return false;\n }\n\n public void removeRange(int left, int right) {\n Integer l1 = map.lowerKey(left); // I used lowerKey here, since we don't care about the range starting at left, as it should be removed\n Integer l2 = map.lowerKey(right); // same, we don't care about the range starting at right\n\n // do this first, in case l1 == l2, the later one will change r1(or r2 in this case)\n if (l2 != null && map.get(l2) > right) {\n map.put(right, map.get(l2));\n }\n\n if (l1 != null && map.get(l1) > left) {\n map.put(l1, left);\n }\n\n // range that starts at left should be removed, so left is inclusive\n // range that starts at right should be kept, so right is exclusive\n map.subMap(left, true, right, false).clear();\n }\n}", "solution_c": "/*\n https://leetcode.com/problems/range-module/\n\n Idea is to use a height balanced tree to save the intervals. Intervals are kept\n according to the start point.\n We search for the position where the given range can lie, then check the previous if it overlaps\n and keep iterating forward while the intervals are overlapping.\n\n QueryRange:\n We first find the range of values in [left, right). Then for each of the overlapping intervals,\n we subtract the common range. Finally if the entire range is covered, then the range will become zero.\n*/\nclass RangeModule {\nprivate:\n struct Interval {\n const bool operator<(const Interval& b) const {\n // Important to implement for == case, otherwise intervals\n // with same start won't exist\n // return start < b.start || (start == b.start && end < b.end);\n\n // This is the best way to compare since tuple already have ordering implemented for\n // fields\n return tie(start, end) < tie(b.start, b.end);\n }\n\n int start = -1, end = -1;\n Interval(int start, int end): start(start), end(end) {};\n };\n\n set intervals;\npublic:\n RangeModule() {\n\n }\n\n // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all, insertion would take O(1)\n // SC: O(1)\n void addRange(int left, int right) {\n Interval interval(left, right);\n // Find the position where interval should lie st the next interval's\n // start >= left\n auto it = intervals.lower_bound(interval);\n\n // check if previous overlaps, move the iterator backwards\n if(!intervals.empty() && it != intervals.begin() && prev(it)->end >= interval.start) {\n --it;\n interval.start = min(it->start, interval.start);\n }\n\n // merge while intervals overlap\n while(it != intervals.end() && it->start <= interval.end) {\n interval.end = max(it->end, interval.end);\n intervals.erase(it++);\n }\n intervals.insert(interval);\n }\n\n // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all\n // SC: O(1)\n bool queryRange(int left, int right) {\n Interval interval(left, right);\n // Range of numbers that needs to be checked\n int range = right - left;\n // Find the position where interval should lie st the next interval's\n // start >= left\n auto it = intervals.lower_bound(interval);\n\n // check if previous interval overlaps the range, previous only\n // covers iff the open end > start of current. [prev.start, prev.end) [left, right)\n if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start) {\n // remove the common portion\n int common = min(interval.end, prev(it)->end) - interval.start;\n range -= common;\n }\n // for all the following overlapping intervals, remove the common portion\n while(it != intervals.end() && it->start <= interval.end) {\n int common = min(interval.end, it->end) - it->start;\n range -= common;\n ++it;\n }\n // Check if the entire range was covered or not\n return range == 0;\n }\n\n // TC: Searching O(logn) + O(n) Merging, worst case when current interval covers all\n // SC: O(1)\n void removeRange(int left, int right) {\n Interval interval(left, right);\n // Find the position where interval should lie st the next interval's\n // start >= left\n auto it = intervals.lower_bound(interval);\n\n // check if previous overlaps, then move the iterator position backwards\n if(!intervals.empty() && it != intervals.begin() && prev(it)->end > interval.start)\n --it;\n\n // For each of the overlapping intervals, remove the common portions\n while(it != intervals.end() && it->start < interval.end) {\n // Start and End of common portion\n int common_start = max(interval.start, it->start);\n int common_end = min(interval.end, it->end);\n\n // only a section of interval overlaps, remove that part\n // an overlapping interval might have to be broken into two non-overlapping parts\n // Eg [---------------------) Bigger interval\n // [--------) Ongoing interval\n // [------) [-----) Original interval broken into left and right parts\n\n // check if there is some range left on the left side\n if(it->start < common_start)\n intervals.insert(Interval(it->start, common_start));\n\n // check if there is some range left on the right side\n if(it->end > common_end)\n intervals.insert(Interval(common_end, it->end));\n\n // Remove the original interval\n intervals.erase(it++);\n }\n }\n};\n\n/**\n * Your RangeModule object will be instantiated and called as such:\n * RangeModule* obj = new RangeModule();\n * obj->addRange(left,right);\n * bool param_2 = obj->queryRange(left,right);\n * obj->removeRange(left,right);\n */" }, { "title": "Asteroid Collision", "algo_input": "We are given an array asteroids of integers representing asteroids in a row.\n\nFor each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.\n\nFind out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.\n\n \nExample 1:\n\nInput: asteroids = [5,10,-5]\nOutput: [5,10]\nExplanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\n\n\nExample 2:\n\nInput: asteroids = [8,-8]\nOutput: []\nExplanation: The 8 and -8 collide exploding each other.\n\n\nExample 3:\n\nInput: asteroids = [10,2,-5]\nOutput: [10]\nExplanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n\n\n \nConstraints:\n\n\n\t2 <= asteroids.length <= 104\n\t-1000 <= asteroids[i] <= 1000\n\tasteroids[i] != 0\n\n", "solution_py": "class Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for a in asteroids:\n while stack and stack[-1] > 0 > a:\n if stack[-1] < abs(a):\n stack.pop()\n continue\n elif stack[-1] == abs(a):\n stack.pop()\n break # this means asteroid must be destroyed (not add to stack in else statement below)\n else:\n stack.append(a)\n \n return stack", "solution_js": "/**\n * @param {number[]} asteroids\n * @return {number[]}\n */\nvar asteroidCollision = function(asteroids) {\n\n const s = [];\n for (let i = 0; i < asteroids.length; i++) {\n const a = asteroids[i];\n\n // Negative asteroids to the left of the stack can be ignored.\n // They'll never collide. Let's just add it to the answer stack and\n // move on. I consider this a special case.\n if ((s.length === 0 || s[s.length -1] < 0) && a < 0 ) {\n s.push(a);\n\n // If an asteroid a is positive (l to r), it may still collide with an\n // a negative asteroid further on in the asteroids array\n } else if (a > 0) {\n s.push(a);\n\n // a is negative. It can only collide with positive ones in\n // the stack. The following will keep on iterating\n // until it is dealt with.\n } else {\n const pop = s.pop();\n\n // positive pop beats negative a, so pick up pop\n // and re-add it to the stack.\n if (Math.abs(pop) > Math.abs(a)) {\n s.push(pop);\n\n // a has larger size than pop, so pop will get dropped\n // and we'll retry another iteration with the same\n // negative a asteroid and whatever the stack's state is.\n } else if (Math.abs(pop) < Math.abs(a)) {\n i--;\n // magnitude of positive pop and negative a are the same\n // so we can drop both of them.\n } else {\n continue;\n }\n }\n }\n\n // The stack should be the answer\n return s;\n\n};", "solution_java": "/*\n0. Start iterating over the asteroid one by one.\n1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n6. Convert the stack to an array in return it.\n\n*/\nclass Solution {\n public int[] asteroidCollision(int[] asteroids) {\n Stack stack = new Stack<>();\n //0. Start iterating over the asteroid one by one.\n for(int a : asteroids) {\n\n //1. If the stack is not empty, and its top > 0 (right moving asteroid) and current asteroid < 0 (left moving), we have collision.\n //2. Pop all the smaller sized right moving asteroids (i.e. values > 0 but lesser than absolute value of left moving asteroid i.e. abs(<0))\n while(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() < Math.abs(a)) {\n stack.pop();\n }\n\n //3. Now that we have taken care of collisions with smaller size right moving asteroids, we need to see if there's a same sized right moving asteroid. If yes, just remove that one as well. Do not add the current left moving asteroid to the stack as it will be annihilated by the same sized right moving asteroid. Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() == Math.abs(a)) {\n stack.pop();\n continue;\n }\n\n //4. If we are here, we still need to deal with the current left moving asteroid. Check the top of the stack as to what is there on top. If its a larger sized right moving asteroid, it will annihilate this current left moving asteroid. So Continue to the next iteration, we are done handling with this left moving asteroid.\n if(!stack.isEmpty() && stack.peek() > 0 && a < 0 && stack.peek() > Math.abs(a)) {\n continue;\n }\n\n //5. If we are here, it means the current asteroid has survived till now either because it did not meet any collisions or won in the collisions. In this case, push the asteroid on to the stack.\n stack.push(a);\n\n }\n\n //6. Convert the stack to an array in return it.\n int[] ans = new int[stack.size()];\n int i = stack.size() - 1;\n while(!stack.isEmpty()) {\n ans[i] = stack.pop();\n i--;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector asteroidCollision(vector& asteroids) {\n \n vectorv;\n stacks;\n \n for(auto x: asteroids){\n \n if(x > 0) s.push(x);\n \n else{\n \n // Case 1: whem top is less than x\n \n while(s.size() > 0 && s.top() > 0 && s.top() < -x){\n s.pop();\n }\n \n // case 2 : when both of same size\n if( s.size() > 0 && s.top()==-x) {\n s.pop();\n }\n \n // case 3: when top is greater\n \n else if( s.size() > 0 && s.top() > -x ){\n // do nothing\n }\n \n // case 4: when same direction \n \n else{\n s.push(x);\n }\n }\n }\n \n while(!s.empty()){\n v.push_back(s.top());\n s.pop();\n }\n \n reverse(v.begin(),v.end());\n \n return v;\n }\n};" }, { "title": "3Sum With Multiplicity", "algo_input": "Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.\n\nAs the answer can be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput: 20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.\n\n\nExample 2:\n\nInput: arr = [1,1,2,2,2,2], target = 5\nOutput: 12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.\n\n\nExample 3:\n\nInput: arr = [2,1,3], target = 6\nOutput: 1\nExplanation: (1, 2, 3) occured one time in the array so we return 1.\n\n\n \nConstraints:\n\n\n\t3 <= arr.length <= 3000\n\t0 <= arr[i] <= 100\n\t0 <= target <= 300\n\n", "solution_py": "class Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n arr.sort()\n count = 0\n for i in range(0, len(arr)-2):\n rem_sum = target - arr[i]\n hash_map = {}\n for j in range(i+1, len(arr)):\n if arr[j] > rem_sum:\n break\n if rem_sum - arr[j] in hash_map:\n count = count + hash_map[rem_sum-arr[j]]\n # update the hash_map\n hash_map[arr[j]] = hash_map.get(arr[j], 0) + 1\n return count % 1000000007", "solution_js": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nvar threeSumMulti = function(arr, target) {\n let count=0\n arr.sort((a,b)=>a-b)\n for(let i=0;itarget){\n k--\n }\n else{\n if(arr[j]!==arr[k]){\n let j1=j,k1=k\n while(arr[j]===arr[j1]){\n j1++\n }\n while(arr[k]===arr[k1]){\n k1--\n }\n count+=((j1-j)*(k-k1))\n j=j1\n k=k1\n }\n else{\n for(let n=1;n<=k-j;n++){\n count+=n\n }\n break\n }\n }\n }\n }\n return count% (10**9 + 7)\n};", "solution_java": "class Solution {\n public int threeSumMulti(int[] arr, int target) {\n long[] cnt = new long[101];\n long res = 0;\n for (int i : arr) {\n cnt[i]++;\n }\n for (int i = 0; i < 101 && i <= target; i++) {\n if (cnt[i] == 0) {\n continue;\n }\n for (int j = i; j < 101 && i + j <= target; j++) {\n int k = target - i - j;\n if (k < j) {\n break;\n }\n if (cnt[j] == 0 || k >= 101 || cnt[k] == 0) {\n continue;\n }\n if (i == j && j == k) {\n res += cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 3 / 2;\n } else if (i == j) {\n res += cnt[k] * cnt[j] * (cnt[j] - 1) / 2;\n } else if (j == k) {\n res += cnt[i] * cnt[j] * (cnt[j] - 1) / 2;\n } else {\n res += cnt[i] * cnt[j] * cnt[target - i - j];\n }\n }\n }\n return (int) (res % (Math.pow(10, 9) + 7));\n }\n}", "solution_c": "class Solution {\npublic:\n int threeSumMulti(vector& arr, int target) {\n long long ans = 0;\n int MOD = pow(10, 9) + 7;\n \n // step 1: create a counting array;\n vector counting(101); // create a vector with size == 101;\n \n for(auto &value : arr) counting[value]++; // count the number;\n \n // step 2: evaluate all cases: x, y, z;\n // case 1: x != y != z;\n for(int x_idx = 0; x_idx < counting.size() - 2; x_idx++){\n if(counting[x_idx] < 1) continue;\n \n int target_tmp = target - x_idx;\n for(int y_idx = x_idx + 1; y_idx < counting.size() - 1; y_idx++){\n if(counting[y_idx] < 1) continue;\n \n if(target_tmp - y_idx <= 100 && target_tmp - y_idx > y_idx){\n ans += counting[x_idx] * counting[y_idx] * counting[target_tmp - y_idx];\n ans %= MOD;\n }\n }\n }\n \n // case 2: x == y != z;\n for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){\n if(counting[x_idx] < 2) continue;\n \n int target_tmp = target - 2 * x_idx;\n if(target_tmp <= 100 && target_tmp > x_idx){\n ans += counting[x_idx] * (counting[x_idx] - 1) / 2 * counting[target_tmp];\n ans %= MOD;\n }\n }\n \n // case 3: x != y == z;\n for(int x_idx = 0; x_idx < counting.size() - 1; x_idx++){\n if(counting[x_idx] < 1) continue;\n \n int target_tmp = target - x_idx;\n if(target_tmp %2 != 0) continue;\n \n if(target_tmp/2 <= 100 && target_tmp/2 > x_idx && counting[target_tmp/2] > 1){\n ans += counting[x_idx] * counting[target_tmp/2] * (counting[target_tmp/2] - 1) / 2;\n ans %= MOD;\n }\n }\n \n // case 4: x == y == z;\n for(int x_idx = 0; x_idx < counting.size(); x_idx++){\n if(counting[x_idx] < 3) continue;\n \n if(x_idx * 3 == target){\n ans += counting[x_idx] * (counting[x_idx] - 1) * (counting[x_idx] - 2) / 6;\n ans %= MOD;\n }\n }\n \n return ans;\n }\n};" }, { "title": "Crawler Log Folder", "algo_input": "The Leetcode file system keeps a log each time some user performs a change folder operation.\n\nThe operations are described below:\n\n\n\t\"../\" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).\n\t\"./\" : Remain in the same folder.\n\t\"x/\" : Move to the child folder named x (This folder is guaranteed to always exist).\n\n\nYou are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.\n\nThe file system starts in the main folder, then the operations in logs are performed.\n\nReturn the minimum number of operations needed to go back to the main folder after the change folder operations.\n\n \nExample 1:\n\n\n\nInput: logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\nOutput: 2\nExplanation: Use this change folder operation \"../\" 2 times and go back to the main folder.\n\n\nExample 2:\n\n\n\nInput: logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\nOutput: 3\n\n\nExample 3:\n\nInput: logs = [\"d1/\",\"../\",\"../\",\"../\"]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= logs.length <= 103\n\t2 <= logs[i].length <= 10\n\tlogs[i] contains lowercase English letters, digits, '.', and '/'.\n\tlogs[i] follows the format described in the statement.\n\tFolder names consist of lowercase English letters and digits.\n\n", "solution_py": "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n m='../'\n r='./'\n\t\t#create an empty stack\n stk=[]\n\t\t#iterate through the list\n for i in logs:\n\t\t\t#if Move to the parent folder (../) operator occurs and stack is not empty, pop element from stack\n if(i==m):\n if(len(stk)>0):\n stk.pop()\n\t\t\t#else if Remain in the same folder (./) operator occurs, do nothing and move to next element in list\n elif(i==r):\n continue\n\t\t\t#else add element to the stack\n else:\n stk.append(i)\n\t\t#now return the size of the stack which would be the minimum number of operations needed to go back to the main folder\n return(len(stk))\n\t\t```", "solution_js": "var minOperations = function(logs) {\n let count = 0;\n for(i=0;i 0) count = count - 1;\n continue\n }\n if(logs[i] === './') continue;\n else count = count + 1;\n }\n return count\n};", "solution_java": "class Solution {\n public int minOperations(String[] logs) {\n var stack = new Stack();\n for(var log : logs){\n if(log.equals(\"../\")){\n if(!stack.empty())\n stack.pop();\n }else if(log.equals(\"./\")){\n\n }else{\n stack.push(log);\n }\n }\n return stack.size();\n }\n}", "solution_c": "//1.using stack\nclass Solution {\npublic:\n int minOperations(vector& logs) {\n\t\n if(logs.size()==0) return 0;\n\t\t\n stack st;\n for(auto x: logs){\n if (x[0] != '.') //Move to the child folder so add children\n st.push(x);\n else if(x==\"../\"){ // Move to the parent folder of the current folder so pop\n if(!st.empty()) st.pop(); \n else continue; //don’t move the pointer beyond the main folder.\n }\n }\n return st.size();\n }\n};\n//2.\nclass Solution {\npublic:\n int minOperations(vector& logs) {\n int ans = 0;\n for (string log : logs) {\n if (log == \"../\") { // go deeper\n ans--; \n ans = max(ans, 0);\n } else if (log != \"./\") // one level up\n\t\t\t ans++; \n }\n return ans;\n }\n};\n//3.\nclass Solution {\npublic:\n int minOperations(vector& logs) {\n int res = 0;\n for (string s : logs) {\n if (s==\"../\") res = max(0, --res);\n else if (s==\"./\") continue;\n else res++;\n }\n return res;\n }\n};" }, { "title": "Single Number", "algo_input": "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.\n\nYou must implement a solution with a linear runtime complexity and use only constant extra space.\n\n \nExample 1:\nInput: nums = [2,2,1]\nOutput: 1\nExample 2:\nInput: nums = [4,1,2,1,2]\nOutput: 4\nExample 3:\nInput: nums = [1]\nOutput: 1\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 3 * 104\n\t-3 * 104 <= nums[i] <= 3 * 104\n\tEach element in the array appears twice except for one element which appears only once.\n\n", "solution_py": "class Solution:\n def singleNumber(self, nums: List[int]) -> int:\n nums.sort()\n i=0\n while i& nums) { \n unordered_map a;\n\t for(auto x: nums)\n\t\t a[x]++;\n\t for(auto z:a)\n\t\t if(z.second==1)\n\t\t\t return z.first;\n\t return -1;\n }\n};" }, { "title": "Find the Shortest Superstring", "algo_input": "Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.\n\nYou may assume that no string in words is a substring of another string in words.\n\n \nExample 1:\n\nInput: words = [\"alex\",\"loves\",\"leetcode\"]\nOutput: \"alexlovesleetcode\"\nExplanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n\n\nExample 2:\n\nInput: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\nOutput: \"gctaagttcatgcatc\"\n\n\n \nConstraints:\n\n\n\t1 <= words.length <= 12\n\t1 <= words[i].length <= 20\n\twords[i] consists of lowercase English letters.\n\tAll the strings of words are unique.\n\n", "solution_py": "class Solution:\n def shortestSuperstring(self, A):\n @lru_cache(None)\n def suffix(i,j):\n for k in range(min(len(A[i]),len(A[j])),0,-1):\n if A[j].startswith(A[i][-k:]):\n return A[j][k:]\n return A[j]\n n = len(A)\n @lru_cache(None)\n def dfs(bitmask, i):\n if bitmask + 1 == 1 << n: return \"\"\n return min([suffix(i, j)+dfs(bitmask | 1< new Uint8Array(N))\n\n // Build the edge graph\n for (let i = 0, word = words; i < N; i++) {\n let word = words[i]\n for (let k = 1; k < word.length; k++) {\n let sub = word.slice(k)\n if (suffixes.has(sub)) suffixes.get(sub).push(i)\n else suffixes.set(sub, [i])\n }\n }\n for (let j = 0; j < N; j++) {\n let word = words[j]\n for (let k = 1; k < word.length; k++) {\n let sub = word.slice(0,k)\n if (suffixes.has(sub))\n for (let i of suffixes.get(sub))\n edges[i][j] = Math.max(edges[i][j], k)\n }\n }\n\n // Initialize DP array\n let M = N - 1,\n dp = Array.from({length: M}, () => new Uint16Array(1 << M))\n\n // Helper function to find the best value for dp[curr][currSet]\n // Store the previous node with bit manipulation for backtracking\n const solve = (curr, currSet) => {\n let prevSet = currSet - (1 << curr), bestOverlap = 0, bestPrev\n if (!prevSet) return (edges[M][curr] << 4) + M\n for (let prev = 0; prev < M; prev++)\n if (prevSet & 1 << prev) {\n let overlap = edges[prev][curr] + (dp[prev][prevSet] >> 4)\n if (overlap >= bestOverlap)\n bestOverlap = overlap, bestPrev = prev\n }\n return (bestOverlap << 4) + bestPrev\n }\n\n // Build DP using solve\n for (let currSet = 1; currSet < 1 << M; currSet++)\n for (let curr = 0; curr < N; curr++)\n if (currSet & 1 << curr)\n dp[curr][currSet] = solve(curr, currSet)\n\n // Join the ends at index M\n let curr = solve(M, (1 << N) - 1) & (1 << 4) - 1\n\n // Build the circle by backtracking path info from dp\n // and find the best place to cut the circle\n let path = [curr], currSet = (1 << M) - 1,\n bestStart = 0, lowOverlap = edges[curr][M], prev\n while (curr !== M) {\n prev = dp[curr][currSet] & (1 << 4) - 1, currSet -= 1 << curr\n let overlap = edges[prev][curr]\n if (overlap < lowOverlap)\n lowOverlap = overlap, bestStart = N - path.length\n curr = prev, path.unshift(curr)\n }\n\n // Build and return ans by cutting the circle at bestStart\n let ans = []\n for (let i = bestStart; i < bestStart + M; i++) {\n let curr = path[i%N], next = path[(i+1)%N], word = words[curr]\n ans.push(word.slice(0, word.length - edges[curr][next]))\n }\n ans.push(words[path[(bestStart+M)%N]])\n return ans.join(\"\")\n};", "solution_java": "class Solution {\n public String shortestSuperstring(String[] words) {\n int n = words.length;\n int[][] discount = new int[n][n];\n for (int i = 0; i < n; i++){\n for (int j = 0; j < n; j++){\n for (int k = 0; k < words[i].length()&&i!=j; k++){ // build discount map from i->j and j->i\n if (words[j].startsWith(words[i].substring(k))){\n discount[i][j]=words[i].length()-k;\n break;\n }\n }\n }\n }\n int[][] dp = new int[1<0; k++){\n if ((i&1<=dp[i|1<dp[(1<dp[(1<0){\n ans[--idx]=words[end].substring((m&(m-1))==0?0:discount[path[m][end]][end]);\n m^=1< > dp,pre,par;\n\nbool startWith(string s, string t)\n{\n// returns true if string s starts with string t\n int i;\n for(i=0; i& A) {\n n=A.size();\n pre.assign(n,vector(n)); // for pre-computing calc(a,b) for all pairs of strings\n par.assign(1<(n,-1)); \n for(int i=0; i(n,-1));\n int len=INT_MAX; // len will contain minimum length of required string\n int ind;\n for(int i=0; i int:\n max_row, max_col = len(grid), len(grid[0])\n dp = [[-1] * max_col for _ in range(max_row)] \n\n def recursion(row, col):\n if row == max_row - 1: # If last row then return nodes value\n return grid[row][col]\n if dp[row][col] == -1: # If DP for this node is not computed then we will do so now.\n current = grid[row][col] # Current Node Value\n res = float('inf') # To store best path from Current Node\n for c in range(max_col): # Traverse all path from Current Node\n val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value\n res = min(res, val)\n dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val\n return dp[row][col]\n\n for c in range(max_col):\n recursion(0, c) # Start recursion from all nodes in 1st row\n return min(dp[0]) # Return min value from 1st row", "solution_js": "var minPathCost = function(grid, moveCost) {\n const rows = grid.length;\n const cols = grid[0].length;\n\n const cache = [];\n \n for (let i = 0; i < rows; i++) {\n cache.push(Array(cols).fill(null));\n }\n \n function move(row, col) {\n const val = grid[row][col];\n \n if (cache[row][col] !== null) {\n return cache[row][col];\n }\n \n if (row === rows - 1) {\n return val;\n }\n \n let ans = Number.MAX_SAFE_INTEGER;\n\n for (let i = 0; i < cols; i++) {\n const addCost = moveCost[val][i];\n\n ans = Math.min(ans, move(row + 1, i) + val + addCost);\n }\n \n cache[row][col] = ans;\n \n return ans;\n }\n\n let ans = Number.MAX_SAFE_INTEGER;\n \n for (let i = 0; i < cols; i++) {\n ans = Math.min(ans, move(0, i));\n }\n \n return ans;\n};", "solution_java": "class Solution {\n Integer dp[][];\n public int minPathCost(int[][] grid, int[][] moveCost) \n {\n dp=new Integer[grid.length][grid[0].length];\n int ans=Integer.MAX_VALUE;\n \n for(int i=0;i> &grid,vector>& moveCost,int i,int j,int n,int m){\n if(i==n-1){\n return grid[i][j];\n }\n int ans=INT_MAX;\n for(int k=0;k>& grid, vector>& moveCost) {\n int ans=INT_MAX;\n int n=grid.size();\n int m=grid[0].size();\n for(int i=0;i int:\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n return sum(bin(n).count('1') in primes for n in range(left, right + 1))", "solution_js": "/**\n * @param {number} L\n * @param {number} R\n * @return {number}\n */\nvar countPrimeSetBits = function(L, R) {\n let set = new Set([2, 3, 5, 7, 11, 13, 17, 19]);\n let countPrime = 0;\n \n for (let i = L; i <= R; i++) {\n if (set.has(i.toString(2).replace(/0/g, '').length)) countPrime++;\n }\n\n return countPrime;\n};", "solution_java": "class Solution {\n public int calculateSetBits(String s){\n int count=0;\n for (int i = 0; i < s.length(); i++) {\n if(s.charAt(i)=='1') count++;\n }\n return count;\n }\n\n public boolean isPrime(int n){\n if (n==0 || n==1) return false;\n for (int i = 2; i <= n/2; i++) {\n if(n%i ==0 ) return false;\n }\n// System.out.println(n+\" - \");\n return true;\n }\n\n public int countPrimeSetBits(int left, int right) {\n int count=0;\n for(int i=left;i<=right;i++){\n String b= Integer.toBinaryString(i);\n\n int n=calculateSetBits(b);\n\n if(isPrime(n)) count++;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n ++left;\n }\n return ans;\n }\n};" }, { "title": "Partition Array Into Three Parts With Equal Sum", "algo_input": "Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.\n\nFormally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])\n\n \nExample 1:\n\nInput: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput: true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n\n\nExample 2:\n\nInput: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput: false\n\n\nExample 3:\n\nInput: arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput: true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n\n\n \nConstraints:\n\n\n\t3 <= arr.length <= 5 * 104\n\t-104 <= arr[i] <= 104\n\n", "solution_py": "class Solution:\n def canThreePartsEqualSum(self, arr: List[int]) -> bool:\n total = sum(arr)\n if total % 3 != 0:\n return False\n ave = total // 3\n stage = 0\n add = 0\n for i in arr[:-1]:\n add += i\n if add == ave:\n stage +=1\n add = 0\n if stage == 2:\n return True\n return False", "solution_js": "var canThreePartsEqualSum = function(arr) {\n const length = arr.length;\n let sum =0, count = 0, partSum = 0;\n for(let index = 0; index < length; index++) {\n sum += arr[index];\n }\n if(sum%3 !== 0) return false;\n partSum = sum/3;\n sum = 0;\n for(let index = 0; index < length; index++) {\n sum += arr[index];\n if(sum === partSum){\n count++;\n sum = 0;\n if(count == 2 && index < length-1) return true;\n }\n }\n return false;\n};", "solution_java": "class Solution { \n public boolean canThreePartsEqualSum(int[] arr) {\n int sum = 0;\n \n for (Integer no : arr) {\n sum += no;\n }\n if (sum % 3 != 0) {\n return false;\n }\n sum = sum / 3;\n int tempSum = 0;\n int count = 0;\n\n for (int i = 0; i < arr.length; i++) {\n tempSum += arr[i];\n if (tempSum == sum) {\n count++;\n tempSum = 0;\n }\n }\n\n return count >= 3;\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool canThreePartsEqualSum(vector& arr) {\n\t\tint sum=0;\n\t\tfor(auto i : arr)\n\t\t\tsum+=i;\n\t\tif(sum%3!=0)\n\t\t\treturn false; //partition not possible\n\t\tint part=sum/3,temp=0,found=0;\n\t\tfor(int i=0;i=3 ? true : false;\n\t}\n};\n\nfeel free to ask your doubts :)\nand pls upvote if it was helpful :)" }, { "title": "Minimum Genetic Mutation", "algo_input": "A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.\n\nSuppose we need to investigate a mutation from a gene string start to a gene string end where one mutation is defined as one single character changed in the gene string.\n\n\n\tFor example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation.\n\n\nThere is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.\n\nGiven the two gene strings start and end and the gene bank bank, return the minimum number of mutations needed to mutate from start to end. If there is no such a mutation, return -1.\n\nNote that the starting point is assumed to be valid, so it might not be included in the bank.\n\n \nExample 1:\n\nInput: start = \"AACCGGTT\", end = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput: 1\n\n\nExample 2:\n\nInput: start = \"AACCGGTT\", end = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput: 2\n\n\nExample 3:\n\nInput: start = \"AAAAACCC\", end = \"AACCCCCC\", bank = [\"AAAACCCC\",\"AAACCCCC\",\"AACCCCCC\"]\nOutput: 3\n\n\n \nConstraints:\n\n\n\tstart.length == 8\n\tend.length == 8\n\t0 <= bank.length <= 10\n\tbank[i].length == 8\n\tstart, end, and bank[i] consist of only the characters ['A', 'C', 'G', 'T'].\n\n", "solution_py": "class Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n q = deque()\n q.append(start)\n n = len(bank)\n last = 0\n used = [False] * n\n for i, x in enumerate(bank):\n if start == x:\n used[i] = True\n if end == x:\n last = i\n dist = 0\n while q:\n dist += 1\n for _ in range(len(q)):\n w = q.popleft()\n for i, x in enumerate(bank):\n if used[i]:\n continue\n bad = 0\n for j in range(8):\n if w[j] != x[j]:\n bad += 1\n if bad == 2:\n break\n if bad == 1:\n if last == i:\n return dist\n used[i] = True\n q.append(x)\n return -1", "solution_js": "/**\n * @param {string} start\n * @param {string} end\n * @param {string[]} bank\n * @return {number}\n */\nvar minMutation = function(start, end, bank) {\n if(start.length!=end.length || !contains(end,bank)){\n return -1;\n }\n return bfs(start,end,bank);\n };\n function contains(end,bank){\n for(const x of bank){\n if(x==end){\n return true;\n }\n }\n return false;\n }\n function convertPossible(a,b){\n if(a.length != b.length) return false;\n let count=0;\n for(let i=0;i0){\n let size=q.length;\n\n for(let i=0;i{\n if(convertPossible(curr,x) && !set.has(x)){\n q.push(x);\n set.add(x);\n }\n })\n }\n count++;\n }\n return -1;\n }", "solution_java": "class Solution {\n public int minMutation(String start, String end, String[] bank) {\n Set set = new HashSet<>();\n for(String tmp: bank){\n set.add(tmp);\n }\n if(!set.contains(end)) return -1;\n if(start.equals(end)) return 0;\n char[] var = {'A','C','G','T'};\n Queue q = new LinkedList<>();\n q.add(start);\n int count = 0;\n while(!q.isEmpty()){\n int size = q.size();\n for(int i = 0; i < size; i ++){\n String str = q.poll();\n char[] tmp = str.toCharArray();\n if(str.equals(end)) return count;\n for(int j = 0; j < 8; j ++){\n char ch = tmp[j];\n for(int k = 0; k < 4; k ++){\n tmp[j] = var[k];\n String node = new String(tmp);\n if(set.contains(node)){\n q.add(node);\n set.remove(node);\n }\n }\n tmp[j] = ch;\n }\n }\n count++;\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int minMutation(string start, string end, vector& bank) {\n unordered_set st(bank.begin(), bank.end());\n if (st.find(end) == st.end()) return -1;\n \n queue q;\n q.push(start);\n \n unordered_set vis;\n vis.insert(start);\n \n int res=0;\n while (not q.empty()) {\n int sz = q.size();\n \n while (sz--) {\n string currString = q.front(); q.pop();\n if (currString == end) return res;\n \n for (int i=0;i None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n\n \"\"\"\n notzero = 0\n zero = 0\n\n while notzero < len(nums):\n if nums[notzero] != 0:\n nums[zero] , nums[notzero] = nums[notzero], nums[zero]\n zero += 1\n notzero += 1", "solution_js": "var moveZeroes = function(nums) {\n let lastNonZeroNumber = 0;\n\n //Moves all the non zero numbers at the start of the array\n for(let i=0; i& nums) {\n int nums_size = nums.size();\n int cntr=0;\n\n for(int i=0;i Optional[ListNode]:\n if head==None or head.next==None:\n return head\n p = None\n while(head != None):\n temp = head.next\n head.next = p\n p = head\n head = temp\n return p", "solution_js": "var reverseList = function(head) {\n \n // Iteratively\n [cur, rev, tmp] = [head, null, null]\n while(cur){\n tmp = cur.next;\n cur.next = rev;\n rev = cur;\n cur = tmp;\n //[current.next, prev, current] = [prev, current, current.next]\n }\n}", "solution_java": "/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode reverseList(ListNode head) {\n\n if(head == null || head.next == null) return head;\n\n ListNode curr = head;\n ListNode temp = null, next = curr.next;\n curr.next = null;\n\n while(curr !=null && next !=null)\n {\n // before cutting off link between next & its next, save next.next\n temp = next.next;\n // let next point to curr\n next.next = curr;\n\n curr = next;\n next = temp;\n\n }\n\n return curr;\n\n }\n}", "solution_c": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* reverseList(ListNode* head) {\n if(head==NULL||head->next==NULL)\n {\n return head;\n }\n ListNode *s=reverseList(head->next);\n ListNode *t=head->next;\n t->next=head;\n head->next=NULL;\n return s;\n \n }\n};" }, { "title": "Two Out of Three", "algo_input": "Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.\n \nExample 1:\n\nInput: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput: [3,2]\nExplanation: The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.\n\n\nExample 2:\n\nInput: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput: [2,3,1]\nExplanation: The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.\n\n\nExample 3:\n\nInput: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput: []\nExplanation: No value is present in at least two arrays.\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length, nums3.length <= 100\n\t1 <= nums1[i], nums2[j], nums3[k] <= 100\n\n", "solution_py": "class Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n output = []\n for i in nums1:\n if i in nums2 or i in nums3:\n if i not in output:\n output.append(i)\n for j in nums2:\n if j in nums3 or j in nums1:\n if j not in output:\n output.append(j)\n return output", "solution_js": "var twoOutOfThree = function(nums1, nums2, nums3) {\n let newArr = [];\n newArr.push(...nums1.filter(num => nums2.includes(num) || nums3.includes(num)))\n newArr.push(...nums2.filter(num => nums1.includes(num) || nums3.includes(num)))\n return Array.from(new Set(newArr))\n};", "solution_java": "class Solution {\n public List twoOutOfThree(int[] nums1, int[] nums2, int[] nums3) {\n int[] bits = new int[101];\n for (int n : nums1) bits[n] |= 0b110;\n for (int n : nums2) bits[n] |= 0b101;\n for (int n : nums3) bits[n] |= 0b011;\n List result = new ArrayList();\n for (int i = bits.length - 1; i > 0; i--)\n if (bits[i] == 0b111)\n result.add(i);\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n vector twoOutOfThree(vector& nums1, vector& nums2, vector& nums3) {\n vectorf(110, 0);\n for (int n : nums1) f[n] |= 1<<0;\n for (int n : nums2) f[n] |= 1<<1;\n for (int n : nums3) f[n] |= 1<<2;\n \n vectorret;\n for (int i = 1; i <= 100; i++) if (f[i] == 3 || f[i] >= 5) ret.push_back(i);\n return ret;\n }\n};" }, { "title": "Trim a Binary Search Tree", "algo_input": "Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.\n\nReturn the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.\n\n \nExample 1:\n\nInput: root = [1,0,2], low = 1, high = 2\nOutput: [1,null,2]\n\n\nExample 2:\n\nInput: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput: [3,2,null,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t0 <= Node.val <= 104\n\tThe value of each node in the tree is unique.\n\troot is guaranteed to be a valid binary search tree.\n\t0 <= low <= high <= 104\n\n", "solution_py": "class Solution:\n\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\tif not root: return root\n\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\troot.left = self.trimBST(root.left, low, high)\n\t\troot.right = self.trimBST(root.right, low, high)\n\t\treturn root", "solution_js": "var trimBST = function(root, low, high) {\n if(!root) return null;\n const { val, left, right } = root;\n if(val < low) return trimBST(root.right, low, high);\n if(val > high) return trimBST(root.left, low, high);\n \n root.left = trimBST(root.left, low, high);\n root.right = trimBST(root.right, low, high);\n return root;\n};", "solution_java": "class Solution {\n public TreeNode trimBST(TreeNode root, int low, int high) {\n if (root == null) return root;\n while (root.val < low || root.val > high) {\n root = root.val < low ? root.right : root.left;\n if (root == null)\n return root;\n }\n root.left = trimBST(root.left, low, high);\n root.right = trimBST(root.right, low, high);\n return root;\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* trimBST(TreeNode* root, int low, int high) {\n if(!root) return NULL;\n \n root->left = trimBST(root->left, low, high);\n root->right = trimBST(root->right, low, high);\n \n if(root->val < low){\n if(root->right){\n TreeNode* temp = root;\n // delete root;\n return temp->right;\n }else{\n return NULL;\n }\n }\n if(root->val > high){\n if(root->left){\n TreeNode* temp = root;\n // delete root;\n return temp->left;\n }else{\n return NULL;\n }\n }\n return root;\n }\n};" }, { "title": "Sliding Window Maximum", "algo_input": "You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.\n\nReturn the max sliding window.\n\n \nExample 1:\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation: \nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\n\n\nExample 2:\n\nInput: nums = [1], k = 1\nOutput: [1]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\t1 <= k <= nums.length\n\n", "solution_py": "class Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n ans = []\n pq = []\n\n for i in range(k): heapq.heappush(pq,(-nums[i],i))\n\n ans.append(-pq[0][0])\n\n for i in range(k,len(nums)):\n heapq.heappush(pq,(-nums[i],i))\n while pq and pq[0][1] < i-k+1 : heapq.heappop(pq)\n ans.append(-pq[0][0])\n\n return ans", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number[]}\n */\nvar maxSlidingWindow = function(nums, k) {\n var i=0, j=0, max=0, deque=[], output=[];\n while(j nums[j]){\n deque.push(nums[j])\n }else{\n while(deque[deque.length-1] < nums[j]){\n deque.pop()\n }\n deque.push(nums[j])\n }\n\n if(j-i+1 === k){\n if(nums[i] === deque[0]){\n output.push(deque.shift());\n }else{\n output.push(deque[0])\n }\n i++;\n }\n j++;\n\n }\n return output\n};", "solution_java": "class Solution {\n public int[] maxSlidingWindow(int[] nums, int k) {\n Deque queue = new LinkedList<>();\n int l = 0, r = 0;\n int[] res = new int[nums.length - k + 1];\n int index = 0;\n while (r < nums.length) {\n int n = nums[r++];\n while (!queue.isEmpty() && n > queue.peekLast()) {\n queue.pollLast();\n }\n queue.offer(n);\n while (r - l > k) {\n int m = nums[l++];\n if (m == queue.peekFirst()) {\n queue.pollFirst();\n }\n }\n if (r - l == k) {\n res[index++] = queue.peekFirst();\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n\t#define f first\n\t#define s second\n\tvector maxSlidingWindow(vector& nums, int k) {\n\t\tvector ans;\n\t\tpriority_queue> pq;\n\t\tfor(int i=0;i int:\n \n \n l = len(flips)\n s = 0\n c = 0\n \n for i in range(len(flips)):\n f = flips[i]\n s = 1 << (f - 1) | s\n if s == (1 << (i+1))-1:\n c += 1\n \n return c", "solution_js": "var numTimesAllBlue = function(flips) {\n const flipped = new Array(flips.length).fill(0);\n let prefixAlignedCount = 0;\n flips.forEach((i, step) => {\n flipped[i - 1] = 1;\n if(isPrefixAligned(step)) {\n ++prefixAlignedCount;\n }\n })\n return prefixAlignedCount;\n \n function isPrefixAligned(step) {\n for(let i = 0; i < flips.length; ++i) {\n if((i < step && flipped[i] === 0) || (i > step && flipped[i] === 1)) {\n return false;\n }\n }\n return true;\n }\n};", "solution_java": "class Solution {\n public int numTimesAllBlue(int[] flips) {\n int counter=0,total=0,max=Integer.MIN_VALUE;\n for(int i=0;ibit;\nint n;\nBIT(int n){\n bit.resize(n+1,0);\n this->n=n;\n}\n\nint findSum(int i){\n \n int sum=0;\n while(i>0){\n sum+=bit[i];\n i-=(i&(-i));\n }\n return sum;\n}\n\nvoid update(int i,int val){\n \n\n while(i<=n){\n bit[i]+=val;\n i+=(i&(-i));\n } \n}\n\n};\n\n\nclass Solution {\npublic:\nint numTimesAllBlue(vector& flips) {\n\n int n=flips.size();\n BIT tree(n+1);\n int res=0;\n string s=string(n,'0');\n \n int maxi=0;\n for(auto &x:flips){\n if(s[x-1]=='1'){\n tree.update(x,-1);\n s[x-1]='0';\n }\n else {\n s[x-1]='1';\n tree.update(x,1);\n }\n maxi=max(maxi,x);\n if(tree.findSum(x)==x && tree.findSum(maxi)==maxi)\n res++;\n \n \n \n }\n \n\t return res; \n\t}\n};" }, { "title": "Minimum Number of Moves to Seat Everyone", "algo_input": "There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.\n\nYou may perform the following move any number of times:\n\n\n\tIncrease or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)\n\n\nReturn the minimum number of moves required to move each student to a seat such that no two students are in the same seat.\n\nNote that there may be multiple seats or students in the same position at the beginning.\n\n \nExample 1:\n\nInput: seats = [3,1,5], students = [2,7,4]\nOutput: 4\nExplanation: The students are moved as follows:\n- The first student is moved from from position 2 to position 1 using 1 move.\n- The second student is moved from from position 7 to position 5 using 2 moves.\n- The third student is moved from from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.\n\n\nExample 2:\n\nInput: seats = [4,1,5,9], students = [1,3,2,6]\nOutput: 7\nExplanation: The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from from position 3 to position 4 using 1 move.\n- The third student is moved from from position 2 to position 5 using 3 moves.\n- The fourth student is moved from from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.\n\n\nExample 3:\n\nInput: seats = [2,2,6,6], students = [1,3,2,6]\nOutput: 4\nExplanation: Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from from position 1 to position 2 using 1 move.\n- The second student is moved from from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.\n\n\n \nConstraints:\n\n\n\tn == seats.length == students.length\n\t1 <= n <= 100\n\t1 <= seats[i], students[j] <= 100\n\n", "solution_py": "class Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats.sort()\n students.sort()\n return sum(abs(seat - student) for seat, student in zip(seats, students))", "solution_js": "var minMovesToSeat = function(seats, students) {\n let sum = 0\n seats=seats.sort((a,b)=>a-b) \n students=students.sort((a,b)=>a-b)\n for(let i=0;i& seats, vector& students) {\n sort(seats.begin(), seats.end());\n sort(students.begin(), students.end());\n \n int res = 0;\n for (int i = 0; i < seats.size(); i++) res += abs(seats[i] - students[i]);\n \n return res;\n }\n};" }, { "title": "Count Integers With Even Digit Sum", "algo_input": "Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.\n\nThe digit sum of a positive integer is the sum of all its digits.\n\n \nExample 1:\n\nInput: num = 4\nOutput: 2\nExplanation:\nThe only integers less than or equal to 4 whose digit sums are even are 2 and 4. \n\n\nExample 2:\n\nInput: num = 30\nOutput: 14\nExplanation:\nThe 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.\n\n\n \nConstraints:\n\n\n\t1 <= num <= 1000\n\n", "solution_py": "class Solution:\n def countEven(self, num: int) -> int:\n if num%2!=0:\n return (num//2)\n s=0\n t=num\n while t:\n s=s+(t%10)\n t=t//10\n if s%2==0:\n return num//2\n else:\n return (num//2)-1", "solution_js": "var countEven = function(num) {\n let count=0;\n for(let i=2;i<=num;i++){\n if(isEven(i)%2==0){\n count++;\n }\n }\n return count\n};\n\nconst isEven = (c) =>{\n let sum=0;\n while(c>0){\n sum+=(c%10)\n c=Math.floor(c/10)\n }\n return sum\n}", "solution_java": "class Solution\n{\n public int countEven(int num)\n {\n int count = 0;\n for(int i = 1; i <= num; i++)\n if(sumDig(i))\n count++;\n return count;\n }\n private boolean sumDig(int n)\n {\n int sum = 0;\n while(n > 0)\n {\n sum += n % 10;\n n /= 10;\n }\n\t\treturn (sum&1) == 0 ? true : false;\n }\n}", "solution_c": "class Solution {\npublic:\n int countEven(int num) {\n int temp = num, sum = 0;\n while (num > 0) {\n sum += num % 10;\n num /= 10;\n }\n return sum % 2 == 0 ? temp / 2 : (temp - 1) / 2;\n }\n};" }, { "title": "Reach a Number", "algo_input": "You are standing at position 0 on an infinite number line. There is a destination at position target.\n\nYou can make some number of moves numMoves so that:\n\n\n\tOn each move, you can either go left or right.\n\tDuring the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.\n\n\nGiven the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.\n\n \nExample 1:\n\nInput: target = 2\nOutput: 3\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to -1 (2 steps).\nOn the 3rd move, we step from -1 to 2 (3 steps).\n\n\nExample 2:\n\nInput: target = 3\nOutput: 2\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to 3 (2 steps).\n\n\n \nConstraints:\n\n\n\t-109 <= target <= 109\n\ttarget != 0\n\n", "solution_py": "class Solution: \n def reachNumber(self,target):\n jumpCount = 1 \n sum = 0 \n while sumfun(m)){\n i=m+1;\n }\n else{\n j=m-1;\n }\n\n }\n\n if(ans!=0){ // If we found our ans return it\n\n return ans;\n }\n else{\n //in this for loop i have set the limit too high it can be less then 10^6 as max value j can be is 44723, so loop will never run fully, whatever the value of j will be, loop will maximum run for 3-10 iterations\n for(int l=j+1;l<100000;l++){ // in the end of binary search we get the value of j(or high end) as the position of the number(in the sequence of continous sum of natural number from 1, i.e. 1, 3,6,10........) whose value is just less than x(searching element)\n\n if((fun(l)-x)%2 ==0){ // as the total step will be more than x if we go backward from zero, thing to note is that if we go -ve direction we also have to come back so we covering even distance\n ans=l;// when the first fun(l) - x is even that l is our minimum jump\n\n break; // no need to search further\n\n }\n }\n\n }\n\n return ans;\n }\n\n};" }, { "title": "Find Missing Observations", "algo_input": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.\n\nYou are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.\n\nReturn an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.\n\nThe average value of a set of k numbers is the sum of the numbers divided by k.\n\nNote that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.\n\n \nExample 1:\n\nInput: rolls = [3,2,4,3], mean = 4, n = 2\nOutput: [6,6]\nExplanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\n\n\nExample 2:\n\nInput: rolls = [1,5,6], mean = 3, n = 4\nOutput: [2,3,2,2]\nExplanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\n\n\nExample 3:\n\nInput: rolls = [1,2,3,4], mean = 6, n = 4\nOutput: []\nExplanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n\n\n \nConstraints:\n\n\n\tm == rolls.length\n\t1 <= n, m <= 105\n\t1 <= rolls[i], mean <= 6\n\n", "solution_py": "class Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)\n if rem == 0:\n if 1 <= missing_val <= 6:\n return [missing_val] * n\n elif 1 <= missing_val < 6:\n return [missing_val + 1] * rem + [missing_val] * (n - rem)\n return []", "solution_js": "var missingRolls = function(rolls, mean, n) {\n let res = [];\n let sum = ((n + rolls.length) * mean) - rolls.reduce((a,b)=>a+b);\n if(sum>6*n || sum<1*n) return res;\n let dec = sum % n;\n let num = Math.floor(sum / n);\n for(let i = 0; i < n; i++){\n if(dec) res.push(num+1), dec--;\n else res.push(num);\n }\n return res;\n};", "solution_java": "class Solution {\n public int[] missingRolls(int[] rolls, int mean, int n) {\n \n \tint i,m=rolls.length,sum=0;\n \tfor(i=0;i0?1:0);\n \t\tq--;\n \t}\n \treturn arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector missingRolls(vector& rolls, int mean, int n) {\n int size=rolls.size(),sum=accumulate(rolls.begin(),rolls.end(),0),missingSum=0;\n missingSum=mean*(n+size)-sum;\n if(missingSum6*n)\n return {};\n int rem=missingSum%n;\n vectorans(n,missingSum/n);\n for(int i=0;i int:\n return min(len(set(candyType)), (len(candyType)//2))", "solution_js": "/**\n * @param {number[]} candyType\n * @return {number}\n */\nvar distributeCandies = function(candyType) {\n\n const set = new Set();\n candyType.map(e => set.add(e));\n return candyType.length/2 > set.size ? set.size : candyType.length/2\n\n};", "solution_java": "class Solution {\n public int distributeCandies(int[] candyType) {\n Set set = new HashSet<>();\n for (int type : candyType) set.add(type);\n return Math.min(set.size(), candyType.length / 2);\n }\n}", "solution_c": "class Solution {\npublic:\n int distributeCandies(vector& candyType) \n {\n unordered_set s(candyType.begin(),candyType.end());\n return min(candyType.size()/2,s.size());\n \n \n }\n};\n//if you like the solution plz upvote." }, { "title": "Insert Interval", "algo_input": "You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.\n\nInsert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).\n\nReturn intervals after the insertion.\n\n \nExample 1:\n\nInput: intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput: [[1,5],[6,9]]\n\n\nExample 2:\n\nInput: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput: [[1,2],[3,10],[12,16]]\nExplanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n\n\n \nConstraints:\n\n\n\t0 <= intervals.length <= 104\n\tintervals[i].length == 2\n\t0 <= starti <= endi <= 105\n\tintervals is sorted by starti in ascending order.\n\tnewInterval.length == 2\n\t0 <= start <= end <= 105\n\n", "solution_py": "class Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n\n intervals.append(newInterval)\n intervals.sort(key=lambda x: x[0])\n\n result = []\n for interval in intervals:\n if not result or result[-1][1] < interval[0]:\n result.append(interval)\n else:\n result[-1][1] = max(result[-1][1],interval[1])\n\n return result", "solution_js": "var insert = function(intervals, newInterval) {\n //Edge case\n if (intervals.length === 0) {\n return [newInterval];\n }\n\t//Find the index to insert newIntervals\n let current = 0;\n while (current < intervals.length && intervals[current][0] < newInterval[0]) {\n current++;\n }\n intervals.splice(current, 0, newInterval);\n\t//If newInterval is not the last index, check the element behigh newInterval to see if merge is needed\n if (current !== intervals.length -1) {\n let pointer = current + 1;\n if (intervals[pointer][0] <= newInterval[1]) {\n while (pointer < intervals.length && intervals[pointer][0] <= newInterval[1]) {\n pointer++;\n }\n newInterval[1] = Math.max(newInterval[1], intervals[pointer - 1][1]);\n intervals.splice(current + 1, pointer - (current + 1));\n }\n }\n\t//If newInterval is not the first index, check the element berfore newInterval to see if merge is needed\n if (current !== 0) {\n if (intervals[current - 1][1] >= newInterval[0]) {\n newInterval[0] = intervals[current - 1][0];\n newInterval[1] = Math.max(newInterval[1], intervals[current - 1][1]);\n intervals.splice(current - 1, 1);\n }\n }\n return intervals;\n};", "solution_java": "class Solution {\n public int[][] insert(int[][] intervals, int[] newInterval) {\n if (newInterval == null || newInterval.length == 0) return intervals;\n \n List merged = new LinkedList<>();\n int i = 0;\n // add not overlapping\n while (i < intervals.length && intervals[i][1] < newInterval[0]) {\n merged.add(intervals[i]);\n i++;\n }\n // add overlapping\n while (i < intervals.length && intervals[i][0] <= newInterval[1]) {\n newInterval[0] = Math.min(intervals[i][0], newInterval[0]);\n newInterval[1] = Math.max(intervals[i][1], newInterval[1]);\n i++;\n }\n merged.add(newInterval);\n // add rest\n while (i < intervals.length) {\n merged.add(intervals[i]);\n i++;\n }\n return merged.toArray(new int[merged.size()][]);\n }\n}", "solution_c": "class Solution {\npublic:\n vector> insert(vector>& intervals, vector& newInterval) {\n vector> output;\n int n = intervals.size();\n int i = 0;\n while(i < n){\n if(newInterval[1] < intervals[i][0]){\n output.push_back(newInterval);\n while(i < n){\n output.push_back(intervals[i]);\n i++;\n }\n return output;\n }\n else if(newInterval[0] > intervals[i][1]){\n output.push_back(intervals[i]);\n i++;\n }\n else{\n newInterval[0] = min(newInterval[0], intervals[i][0]);\n newInterval[1] = max(newInterval[1], intervals[i][1]);\n i++;\n }\n }\n output.push_back(newInterval);//think about it\n return output;\n }\n};" }, { "title": "Remove K Digits", "algo_input": "Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.\n\n \nExample 1:\n\nInput: num = \"1432219\", k = 3\nOutput: \"1219\"\nExplanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n\n\nExample 2:\n\nInput: num = \"10200\", k = 1\nOutput: \"200\"\nExplanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n\n\nExample 3:\n\nInput: num = \"10\", k = 2\nOutput: \"0\"\nExplanation: Remove all the digits from the number and it is left with nothing which is 0.\n\n\n \nConstraints:\n\n\n\t1 <= k <= num.length <= 105\n\tnum consists of only digits.\n\tnum does not have any leading zeros except for the zero itself.\n\n", "solution_py": "# Lets make monotonically growing stack and save the indexes of popped elements into deletes dict.\n#as soon as len(delete) == k delete those indexes from the initial string and thats the answer.\n#if len(delete) < k remove k-len(delete) chars from right and thats the answer\nclass Solution:\n def removeKdigits(self, s: str, k: int) -> str:\n if len(s) == k:\n return '0'\n stack = []\n delete = {}\n for i in range(len(s)):\n\n while stack and s[i] < stack[-1][0]:\n delete[stack.pop()[1]] = 1\n if len(delete) == k:\n break\n if len(delete) == k:\n return self.deleteindexes(s, delete, k)\n stack.append([s[i], i])\n s1 = self.deleteindexes(s, delete, k)\n\n return str(int(s1[:len(s1)-k +len(delete)]))\n\n\n def deleteindexes(self, s, delete, k):\n if not delete:\n return s\n if len(delete) == k:\n return str(int(''.join([c for ind, c in enumerate(s) if ind not in delete])))\n else:\n return ''.join([c for ind, c in enumerate(s) if ind not in delete])", "solution_js": "var removeKdigits = function(num, k) {\n if(k == num.length) {\n return '0'\n }\n let stack = []\n for(let i = 0; i < num.length; i++) {\n while(stack.length > 0 && num[i] < stack[stack.length - 1] && k > 0) {\n stack.pop()\n k--\n }\n stack.push(num[i])\n }\n while(k > 0) {\n stack.pop()\n k--\n }\n while(stack[0] == 0 && stack.length > 1) {\n stack.shift()\n }\n return stack.join('')\n}", "solution_java": "class Solution {\n public String removeKdigits(String num, int k) {\n int n = num.length();\n if(n == k){\n return \"0\";\n }\n Deque dq = new ArrayDeque<>();\n for(char ch : num.toCharArray()){\n while(!dq.isEmpty() && k > 0 && dq.peekLast() > ch){\n dq.pollLast();\n k--;\n }\n dq.addLast(ch);\n }\n StringBuilder sb = new StringBuilder();\n while(!dq.isEmpty() && dq.peekFirst() == '0'){\n dq.pollFirst();\n }\n while(!dq.isEmpty()){\n sb.append(dq.pollFirst());\n }\n if(k >= sb.length()){\n return \"0\";\n }\n return sb.length() == 0 ? \"0\" : sb.toString().substring(0,sb.length()-k);\n }\n}", "solution_c": "\t\t\t\t\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n string removeKdigits(string num, int k) {\n // number of operation greater than length we return an empty string\n if(num.length() <= k) \n return \"0\";\n \n // k is 0 , no need of removing / preforming any operation\n if(k == 0)\n return num;\n \n string res = \"\";// result string\n stack s; // char stack\n \n s.push(num[0]); // pushing first character into stack\n \n for(int i = 1; i 0 && !s.empty() && num[i] < s.top())\n {\n // if k greater than 0 and our stack is not empty and the upcoming digit,\n // is less than the current top than we will pop the stack top\n --k;\n s.pop();\n }\n \n s.push(num[i]);\n \n // popping preceding zeroes\n if(s.size() == 1 && num[i] == '0')\n s.pop();\n }\n \n while(k && !s.empty())\n {\n // for cases like \"456\" where every num[i] > num.top()\n --k;\n s.pop();\n }\n \n while(!s.empty())\n {\n res.push_back(s.top()); // pushing stack top to string\n s.pop(); // pop the top element\n }\n \n reverse(res.begin(),res.end()); // reverse the string \n \n if(res.length() == 0)\n return \"0\";\n \n return res;\n \n \n }\n};" }, { "title": "Convert a Number to Hexadecimal", "algo_input": "Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.\n\nAll the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.\n\nNote: You are not allowed to use any built-in library method to directly solve this problem.\n\n \nExample 1:\nInput: num = 26\nOutput: \"1a\"\nExample 2:\nInput: num = -1\nOutput: \"ffffffff\"\n\n \nConstraints:\n\n\n\t-231 <= num <= 231 - 1\n\n", "solution_py": "class Solution:\n def toHex(self, num: int) -> str:\n ret = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n ans = \"\"\n\n if num < 0:\n num = pow(2,32) +num\n\n if num == 0:\n return \"0\"\n while num > 0:\n ans = ret[num%16] +ans\n num = num//16\n\n return ans", "solution_js": " var toHex = function(num) {\n let hexSymbols = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"];\n if (num >= 0) {\n let hex = \"\";\n do {\n let reminder = num % 16;\n num = Math.floor(num/16);\n hex = hexSymbols[reminder] + hex;\n } while (num > 0)\n return hex;\n } else {\n num = -num;\n let invertedHex = \"\"; //FFFFFFFF - hex\n let needToCarry1 = true; //adding + 1 initially and carrying it on if needed\n while (num > 0) {\n let reminder = num % 16;\n let invertedReminder = 15 - reminder; //inverting\n if (needToCarry1) { //adding 1 for 2's complement\n invertedReminder += 1;\n if (invertedReminder === 16) { //overflow, carrying 1 to the left\n invertedReminder = 0;\n needToCarry1 = true;\n } else {\n needToCarry1 = false;\n }\n }\n num = Math.floor(num/16);\n invertedHex = hexSymbols[invertedReminder] + invertedHex;\n }\n //formatting as \"FFFFFFFF\"\n while (invertedHex.length < 8) {\n invertedHex = \"f\" + invertedHex;\n }\n return invertedHex;\n }\n};", "solution_java": "class Solution {\n public String toHex(int num) {\n if(num == 0) return \"0\";\n\n boolean start = true;\n\n StringBuilder sb = new StringBuilder();\n\n for(int i = 28; i >= 0; i -= 4) {\n int digit = (num >> i) & 15;\n if(digit > 9) {\n char curr = (char)(digit%10 + 'a');\n sb.append(curr);\n start = false;\n } else if(digit != 0) {\n char curr = (char)(digit + '0');\n sb.append(curr);\n start = false;\n } else {//digit == 0\n if(start == false) { //avoid case: 00001a\n sb.append('0');\n }\n }\n\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution\n{\npublic:\n string toHex(int num)\n {\n string hex = \"0123456789abcdef\";\n unsigned int n = num; // to handle neg numbers\n string ans = \"\";\n if (n == 0)\n return \"0\";\n while (n > 0)\n {\n int k = n % 16;\n ans += hex[k];\n n /= 16;\n }\n reverse(ans.begin(), ans.end()); // as we stored it in the opposite order\n return ans;\n }\n};" }, { "title": "Smallest Range I", "algo_input": "You are given an integer array nums and an integer k.\n\nIn one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.\n\nThe score of nums is the difference between the maximum and minimum elements in nums.\n\nReturn the minimum score of nums after applying the mentioned operation at most once for each index in it.\n\n \nExample 1:\n\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n\n\nExample 2:\n\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n\n\nExample 3:\n\nInput: nums = [1,3,6], k = 3\nOutput: 0\nExplanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t0 <= nums[i] <= 104\n\t0 <= k <= 104\n\n", "solution_py": "class Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n return max(0, max(nums)-min(nums)-2*k)", "solution_js": "var smallestRangeI = function(nums, k) {\n let max = Math.max(...nums);\n let min = Math.min(...nums);\n return Math.max(0, max - min- 2*k)\n};", "solution_java": "class Solution {\n public int smallestRangeI(int[] nums, int k) {\n if (nums.length == 1)\n return 0;\n\n int min = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE;\n\n for (int num: nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n int diff = max - min;\n\n return Math.max(0, diff - 2*k);\n }\n}", "solution_c": "class Solution {\npublic:\n int smallestRangeI(vector& nums, int k) {\n int mx = *max_element(nums.begin(), nums.end());\n int mn = *min_element(nums.begin(), nums.end());\n \n return max(0, (mx-mn-2*k));\n }\n};" }, { "title": "Number of Longest Increasing Subsequence", "algo_input": "Given an integer array nums, return the number of longest increasing subsequences.\n\nNotice that the sequence has to be strictly increasing.\n\n \nExample 1:\n\nInput: nums = [1,3,5,4,7]\nOutput: 2\nExplanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2]\nOutput: 5\nExplanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2000\n\t-106 <= nums[i] <= 106\n\n", "solution_py": "class Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n \n if not nums or len(nums) == 0:\n return 0\n \n def find_pos(sub, val):\n left, right = 0, len(sub) - 1\n while left < right:\n mid = (left + right) >> 1\n if sub[mid] >= val: \n right = mid\n else:\n left = mid + 1\n return left \n \n \n sub_list = []\n \n for val in nums:\n if len(sub_list) == 0 or val > sub_list[-1][-1][0]:\n # should append a new element at the end\n cur_count = sum([x[1] for x in sub_list[-1] if val > x[0]]) if len(sub_list) != 0 else 1\n sub_list.append([(val, cur_count)])\n else:\n # get the last number to turn it back to a LIS problem\n cur_sub = [array[-1][0] for array in sub_list]\n pos = find_pos(cur_sub, val)\n # if pos == 0, means it is smallest, no need to look the previous level and set it to be 1\n cur_count = sum([x[1] for x in sub_list[pos - 1] if val > x[0]]) if pos > 0 else 1\n sub_list[pos].append((val, cur_count))\n \n return sum([x[1] for x in sub_list[-1]])", "solution_js": "var findNumberOfLIS = function(nums) {\n const { length } = nums;\n const dpLength = Array(length).fill(1);\n const dpCount = Array(length).fill(1);\n\n for (let right = 0; right < length; right++) {\n for (let left = 0; left < right; left++) {\n if (nums[left] >= nums[right]) continue;\n if (dpLength[left] + 1 === dpLength[right]) {\n dpCount[right] += dpCount[left];\n } else if (dpLength[left] + 1 > dpLength[right]) {\n dpLength[right] = dpLength[left] + 1;\n dpCount[right] = dpCount[left];\n }\n }\n }\n\n const maxLength = Math.max(...dpLength);\n return dpLength.reduce((result, length, index) => {\n const count = dpCount[index];\n return result + (maxLength === length ? count : 0);\n }, 0);\n};", "solution_java": "class Solution {\n public int findNumberOfLIS(int[] nums) {\n int N = nums.length;\n int []dp =new int[N];\n int []count = new int[N];\n Arrays.fill(dp,1);Arrays.fill(count,1);\n int maxi = 1;\n for(int i=0;i dp[i]){\n dp[i] = dp[j]+1;\n //inherit a new one\n count[i]=count[j];\n maxi = Math.max(dp[i],maxi);\n }else if(nums[j] < nums[i] && dp[j]+1 == dp[i]){\n //got one as same len, increase count\n count[i]+=count[j];\n }\n }\n }//for ends\n int maxlis=0;\n for(int i=0;i& nums) {\n\t\tint n = nums.size(), maxI=0, inc=0;\n\t\tvector dp(n,1), count(n,1);\n\t\tfor(int i=0;inums[j] && 1+dp[j] > dp[i])\n\t\t\t\t{\n\t\t\t\t\tdp[i] = 1+dp[j];\n\t\t\t\t\tcount[i] = count[j];\n\t\t\t\t}\n\t\t\t\telse if(nums[i]>nums[j] && 1+dp[j] == dp[i])\n\t\t\t\t\tcount[i] += count[j];\n\t\t\t}\n\t\t\tmaxI = max(maxI, dp[i]);\n\t\t}\n\t\tfor(int i=0;i int:\n n = len(arr)\n i = 0\n while i < n-1 and arr[i+1] >= arr[i]:\n i += 1\n \n if i == n-1:\n return 0\n \n j = n-1\n while j >= 0 and arr[j-1] <= arr[j]:\n j -= 1\n \n ans = min(n, n-i-1, j)\n \n for l in range(i+1):\n r = j\n while r < n and arr[r] < arr[l]:\n r += 1\n ans = min(ans, r-l-1)\n \n return ans", "solution_js": "var findLengthOfShortestSubarray = function(arr) {\n const n = arr.length;\n \n if (n <= 1) {\n return 0;\n }\n \n let prefix = 1;\n \n while (prefix < n) {\n if (arr[prefix - 1] <= arr[prefix]) {\n prefix++;\n } else {\n break;\n }\n }\n \n if (prefix === n) {\n return 0;\n }\n \n let suffix = 1;\n \n while (suffix < n) {\n const i = n - 1 - suffix;\n \n if (arr[i] <= arr[i + 1]) {\n suffix++;\n } else {\n break;\n }\n }\n\n let res = Math.min(n - prefix, n - suffix);\n let left = 0;\n let right = n - suffix;\n\n while (left < prefix && right < n) {\n if (arr[left] <= arr[right]) {\n res = Math.min(res, right - left - 1);\n left++;\n } else {\n right++;\n }\n }\n\n return res;\n};", "solution_java": "class Solution {\n public int findLengthOfShortestSubarray(int[] arr) {\n int firstLast=0,lastFirst=arr.length-1;\n for(;firstLastarr[firstLast+1]) break;\n }\n\t\t//Base case for a non-decreasing sequence\n if(firstLast==arr.length-1) return 0;\n for( ;lastFirst>0;lastFirst--){\n if(arr[lastFirst]=0;firstLast--){\n for(int i=lastFirst;iarr[i]) continue;\n minLength = Math.min(minLength,i-firstLast-1);\n break;\n }\n }\n return minLength;\n }\n}", "solution_c": "// itne me hi thakk gaye?\nclass Solution {\npublic:\n bool ok(int &size, vector &pref, vector &suff, vector &arr, int &n) {\n for(int start=0; start<=n-size; start++) {\n int end = start + size - 1;\n int left = (start <= 0) ? 0 : pref[start-1];\n int right = (end >= n-1) ? 0 : suff[end+1];\n int le = (start <= 0) ? -1e9+2 : arr[start-1];\n int re = (end >= n-1) ? 1e9+2 : arr[end+1];\n if (left + right == n-size && le <= re) {\n return true;\n }\n }\n return false;\n }\n int findLengthOfShortestSubarray(vector& arr) {\n int n = arr.size();\n if (!n || n==1) return 0;\n vector pref(n, 1);\n vector suff(n, 1);\n for(int i=1; i= arr[i-1]) pref[i] = pref[i-1]+1;\n }\n for(int i=n-2; i>=0; i--) {\n if (arr[i] <= arr[i+1]) suff[i] = suff[i+1]+1;\n }\n int low = 0;\n int high = n-1;\n while(low < high) {\n int mid = (low + high)/2;\n if(ok(mid, pref, suff, arr, n)) high = mid;\n else low = mid+1;\n if(high - low == 1) break;\n }\n if (ok(low, pref, suff, arr, n)) return low;\n return high;\n }\n};" }, { "title": "Check If a String Contains All Binary Codes of Size K", "algo_input": "Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.\n\n \nExample 1:\n\nInput: s = \"00110110\", k = 2\nOutput: true\nExplanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n\n\nExample 2:\n\nInput: s = \"0110\", k = 1\nOutput: true\nExplanation: The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring. \n\n\nExample 3:\n\nInput: s = \"0110\", k = 2\nOutput: false\nExplanation: The binary code \"00\" is of length 2 and does not exist in the array.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 * 105\n\ts[i] is either '0' or '1'.\n\t1 <= k <= 20\n\n", "solution_py": "class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n \n Z = set()\n\n for i in range(len(s)-k+1):\n Z.add(s[i:i+k])\n \n if len(Z) == 2**k:\n return True\n\n return False", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {boolean}\n */\nvar hasAllCodes = function(s, k) {\n \n if (k > s.length) {\n return false;\n }\n \n /* Max strings can be generated of k chars 0/1. */\n const max = Math.pow(2, k);\n \n /*\n * Create a set. \n * It will contain all unique values.\n */ \n const set = new Set();\n \n for(let i = 0; i < s.length - k + 1; i++) {\n /* Generate substring of size k from index i */\n const substr = s.substr(i, k); \n set.add(substr);\n \n /* \n * if enough of unique strings are generated, \n * break the loop as there is no point of iterating\n * as we have found all necessary strings.\n */\n if (set.size === max) {\n return true;\n }\n }\n \n return set.size === max;\n};", "solution_java": "class Solution {\n public boolean hasAllCodes(String s, int k) {\n HashSet hs=new HashSet();\n for(int i=0;i<=s.length()-k;i++){\n hs.add(s.substring(i,i+k));\n }\n if(hs.size() == Math.pow(2,k))return true;\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool hasAllCodes(string s, int k) {\n if (s.size() < k)\n {\n return false;\n }\n unordered_set binary_codes;\n for (int i = 0; i < s.size()-k+1; i++)\n {\n string str = s.substr(i, k);\n binary_codes.insert(str);\n if (binary_codes.size() == (int)pow(2, k))\n {\n return true;\n }\n }\n return false;\n }\n};" }, { "title": "Minimum Swaps to Make Strings Equal", "algo_input": "You are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].\n\nReturn the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.\n\n \nExample 1:\n\nInput: s1 = \"xx\", s2 = \"yy\"\nOutput: 1\nExplanation: Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".\n\n\nExample 2:\n\nInput: s1 = \"xy\", s2 = \"yx\"\nOutput: 2\nExplanation: Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.\n\n\nExample 3:\n\nInput: s1 = \"xx\", s2 = \"xy\"\nOutput: -1\n\n\n \nConstraints:\n\n\n\t1 <= s1.length, s2.length <= 1000\n\ts1, s2 only contain 'x' or 'y'.\n\n", "solution_py": "class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n h = defaultdict(int)\n count = 0 # variable to keep track of the number of mismatches; it is impossible to make strings equal if count is odd\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count += 1\n h[s1[i]] += 1\n if count % 2 != 0: \n return -1\n res, a, b = 0, h['x'], h['y']\n res += a // 2 + b // 2\n if a % 2 == 0:\n return res\n return res + 2", "solution_js": "var minimumSwap = function(s1, s2) {\n let count1 = 0;\n let count2 = 0;\n for(let i in s1) {\n if(s1[i] === \"x\" && s2[i] === \"y\") {\n count1++\n }\n if(s1[i] === \"y\" && s2[i] === \"x\") {\n count2++\n }\n }\n\n let ans = Math.floor(count1 / 2) + Math.floor(count2 / 2);\n if(count1 % 2 === 0 && count2 % 2 === 0){\n return ans\n }\n else if(count1 % 2 !== 0 && count2 % 2 !== 0){\n return ans + 2;\n }\n else {\n return -1;\n }\n};", "solution_java": "class Solution {\n public int minimumSwap(String s1, String s2) {\n if(s1.length() != s2.length()) return -1;\n\t\tint n = s1.length();\n int x = 0 , y = 0;\n \n for(int i = 0 ; i < n ; i ++){\n char c1 = s1.charAt(i) , c2 = s2.charAt(i);\n if(c1 == 'x' && c2 == 'y') x++;\n else if(c1 == 'y' && c2 == 'x') y++;\n }\n \n if(x % 2 == 0 && y % 2 == 0) return x/2 + y/2;\n else if(x % 2 == 1 && y % 2 == 1) return x/2 + y/2 + 2;\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumSwap(string s1, string s2) {\n int n = s1.size();\n int cnt1=0,cnt2=0,i=0;\n \n while(i int:\n z_count = 0 #count zeors in nums\n mx_ones = 0\n j = 0\n for i in range(len(nums)):\n if nums[i] == 0: \n z_count+=1\n while z_count>k:#if zeros count cross k decrease count\n if nums[j] == 0:\n z_count-=1\n j+=1\n print(i,j)\n mx_ones = max(mx_ones, i-j+1)\n return mx_ones", "solution_js": " * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar longestOnes = function(nums, k) {\n let left = 0;\n let oneCount = 0;\n let maxLength = 0;\n \n for (let right = 0; right < nums.length; right ++) {\n if (nums[right]) { // so if the element is a 1 since 0 is falsy\n oneCount++\n }\n \n if ((right - left + 1 - oneCount) > k) { // check if we've used all of our replacements\n if (nums[left]) { // start shrinking the window if its a 1 we subtract a count from oneCount\n oneCount--\n }\n left++\n }\n \n maxLength = Math.max(maxLength, right - left + 1); // update maxLength each iteration for largest window\n }\n \n return maxLength\n};", "solution_java": "class Solution {\n public int longestOnes(int[] nums, int k) {\n int ans = 0;\n int j = -1;\n int count = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n count++;\n }\n while (count > k) {\n j++;\n if (nums[j] == 0) {\n count--;\n }\n }\n int len = i - j;\n if (len > ans) ans = len;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int longestOnes(vector& nums, int k) {\n \n // max length of subarray with at most k zeroes \n \n int i=0;\n int j=0;\n int cnt = 0;\n int ans = 0;\n\n int n = nums.size();\n\n while(jk\n {\n while(cnt>k)\n {\n if(nums[i]==0)\n cnt--;\n i++;\n }\n j++;\n }\n }\n return ans;\n \n }\n};" }, { "title": "Longest Cycle in a Graph", "algo_input": "You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\n\nThe graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.\n\nReturn the length of the longest cycle in the graph. If no cycle exists, return -1.\n\nA cycle is a path that starts and ends at the same node.\n\n \nExample 1:\n\nInput: edges = [3,3,4,2,3]\nOutput: 3\nExplanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.\n\n\nExample 2:\n\nInput: edges = [2,-1,3,1]\nOutput: -1\nExplanation: There are no cycles in this graph.\n\n\n \nConstraints:\n\n\n\tn == edges.length\n\t2 <= n <= 105\n\t-1 <= edges[i] < n\n\tedges[i] != i\n\n", "solution_py": "class Solution:\n def longestCycle(self, edges: List[int]) -> int:\n preorder = [-1 for _ in range(len(edges))]\n self.ans = -1\n self.pre = 0\n \n def dfs(self, i: int, st: int) -> None:\n preorder[i] = self.pre\n self.pre += 1\n \n if edges[i] == -1:\n return\n elif preorder[edges[i]] == -1:\n dfs(self, edges[i], st)\n return\n elif preorder[edges[i]] >= st:\n self.ans = max(self.ans, preorder[i] - preorder[edges[i]] + 1)\n return\n \n for i in range(len(edges)):\n if preorder[i] == -1 and edges[i] != -1:\n dfs(self, i, self.pre)\n \n return self.ans", "solution_js": "/**\n * @param {number[]} edges\n * @return {number}\n */\nfunction getCycleTopology(edges){\n const indeg = new Array(edges.length).fill(0);\n const queue = [];\n const map = {};\n for(const src in edges){\n const des = edges[src]\n if(des >= 0){\n indeg[des] ++;\n }\n map[src] ? map[src].push(des) : map[src] = [des]\n }\n for(const node in indeg){\n if(indeg[node] === 0){\n queue.push(node)\n }\n }\n while(queue.length > 0){\n const node = queue.shift();\n for(const connectedNode of map[node]){\n if(connectedNode !== -1){\n indeg[connectedNode] --;\n if(indeg[connectedNode] === 0){\n queue.push(connectedNode);\n }\n }\n }\n }\n return indeg\n}\nclass DisjointSet{\n constructor(n){\n this.n = n;\n this.root = new Array(n).fill(0).map((_,i) => i);\n this.rank = new Array(n).fill(1);\n\n }\n find(x){\n if(x === this.root[x]) return x;\n return this.root[x] = this.find(this.root[x]);\n }\n union(x,y){\n const x_root = this.find(x);\n const y_root = this.find(y);\n\n if(this.rank[x_root] < this.rank[y_root]){\n [this.rank[x_root] , this.rank[y_root]] = [this.rank[y_root] , this.rank[x_root]];\n }\n this.root[y_root] = x_root;\n if(this.rank[x_root] === this.rank[y_root]) this.rank[x_root] ++;\n }\n _getGroupsComponentCounts(){\n let groups = {};\n for(const node of this.root){\n const node_root = this.find(node);\n groups[node_root] = groups[node_root] +1 || 1\n }\n return groups\n }\n getLongestGroupComponentLength(){\n let longestLength = 1;\n const lengths = this._getGroupsComponentCounts();\n for(const length of Object.values(lengths)){\n if(length > 1){\n longestLength = Math.max(longestLength, length);\n }\n }\n return longestLength > 1 ? longestLength : -1;\n }\n}\nvar longestCycle = function(edges) {\n const djs = new DisjointSet(edges.length);\n let res = -1\n\n // topology sort results topology array.\n // component with greater than 0 is cyclic component.\n // now we need to get groups of cycle since we can't distinguish each cycles with current datas.\n const cycleComponent = getCycleTopology(edges); \n\n //with edges info and cycle component data, we can now distinguish each cycle group by union finde\n // because each cycle r independent with each other.\n for(const src in edges){\n const des = edges[src];\n if(cycleComponent[src] && cycleComponent[des]){\n djs.union(src, des);\n }\n }\n res = djs.getLongestGroupComponentLength()\n return res\n};", "solution_java": "class Solution {\n public int longestCycle(int[] edges) {\n int[] map = new int[edges.length];\n int result = -1;\n\n for (int i = 0; i < edges.length; i++)\n result = Math.max(result, helper(i, 1, edges, map));\n\n return result;\n }\n\n int helper(int index, int total, int[] edges, int[] map) {\n if (index == -1 || map[index] == -1)\n return -1;\n\n if (map[index] != 0)\n return total - map[index];\n\n map[index] = total;\n int result = helper(edges[index], total + 1, edges, map);\n map[index] = -1;\n\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n \n int maxLength = -1;\n \n void getcycle(vector &edges,int si,vector& visit,vector& store){\n if(si == -1)return ;\n if(visit[si]){\n int count = -1;\n for(int i =0;i& edges) {\n \n vector visit(edges.size(),0);\n \n for(int i =0;i store;\n getcycle(edges,i,visit,store);\n \n }\n \n return maxLength;\n \n }\n};" }, { "title": "Validate Stack Sequences", "algo_input": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.\n\n \nExample 1:\n\nInput: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput: true\nExplanation: We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n\n\nExample 2:\n\nInput: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput: false\nExplanation: 1 cannot be popped before 2.\n\n\n \nConstraints:\n\n\n\t1 <= pushed.length <= 1000\n\t0 <= pushed[i] <= 1000\n\tAll the elements of pushed are unique.\n\tpopped.length == pushed.length\n\tpopped is a permutation of pushed.\n\n", "solution_py": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n i=0\n for num in pushed:\n stack.append(num) #we are pushing the number to the stack\n while len(stack) >0 and stack[len(stack)-1] == popped[i] :\n #if the last element of the stack is equal to the popped element\n stack.pop()\n i+=1 #we are incrementing i\n return True if len(stack) ==0 else False\n\t\t", "solution_js": "var validateStackSequences = function(pushed, popped) {\n let stack = [];\n let j = 0;\n \n for(let i=0; i st = new Stack<>(); // Create a stack\n\n int j = 0; // Intialise one pointer pointing on popped array\n\n for(int val : pushed){\n st.push(val); // insert the values in stack\n while(!st.isEmpty() && st.peek() == popped[j]){ // if st.peek() values equal to popped[j];\n st.pop(); // then pop out\n j++; // increment j\n }\n }\n return st.isEmpty(); // check if stack is empty return true else false\n }\n}", "solution_c": "class Solution {\npublic:\n bool validateStackSequences(vector& pushed, vector& popped) {\n stack st; // Create a stack\n \n int j = 0; // Intialise one pointer pointing on popped array\n \n for(auto val : pushed){\n st.push(val); // insert the values in stack\n while(st.size() > 0 && st.top() == popped[j]){ // if st.peek() values equal to popped[j];\n st.pop(); // then pop out\n j++; // increment j\n }\n }\n return st.size() == 0; // check if stack is empty return true else false\n }\n};" }, { "title": "Number of Excellent Pairs", "algo_input": "You are given a 0-indexed positive integer array nums and a positive integer k.\n\nA pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:\n\n\n\tBoth the numbers num1 and num2 exist in the array nums.\n\tThe sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.\n\n\nReturn the number of distinct excellent pairs.\n\nTwo pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.\n\nNote that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.\n\n \nExample 1:\n\nInput: nums = [1,2,3,1], k = 3\nOutput: 5\nExplanation: The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.\n\nExample 2:\n\nInput: nums = [5,1,1], k = 10\nOutput: 0\nExplanation: There are no excellent pairs for this array.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 109\n\t1 <= k <= 60\n\n", "solution_py": "class Solution:\n def countExcellentPairs(self, nums: List[int], k: int) -> int:\n hamming = sorted([self.hammingWeight(num) for num in set(nums)])\n ans = 0\n for h in hamming:\n ans += len(hamming) - bisect.bisect_left(hamming, k - h)\n return ans\n\n def hammingWeight(self, n):\n ans = 0\n while n:\n n &= (n - 1)\n ans += 1\n return ans", "solution_js": "var countExcellentPairs = function(nums, k) {\n const map = new Map();\n const set = new Set();\n const l = nums.length;\n let res = 0;\n for (let num of nums) {\n let temp = num.toString(2).split(\"1\").length - 1;\n if (!map.has(temp)) {\n map.set(temp, new Set([num]));\n } else {\n map.get(temp).add(num);\n }\n }\n \n for (let num of nums) {\n let temp = num.toString(2).split(\"1\").length - 1;\n if(!set.has(num)) {\n let gap = Math.max(0, k - temp)\n for (let key of map.keys()) {\n if (key >= gap) {\n res += map.get(key).size;\n }\n } \n set.add(num);\n }else {\n continue;\n }\n }\n return res;\n};", "solution_java": "class Solution {\n public long countExcellentPairs(int[] nums, int k) {\n HashMap> map = new HashMap<>();\n for(int i : nums){\n int x = Integer.bitCount(i);\n map.putIfAbsent(x,new HashSet<>());\n map.get(x).add(i);\n }\n long ans = 0;\n HashSet vis = new HashSet<>();\n for(int i : nums){\n if(vis.contains(i)) continue;\n int need = Math.max(0,k-Integer.bitCount(i));\n for(int key : map.keySet()) // runs at max 30 times\n if(key >= need) ans += (long) map.get(key).size();\n vis.add(i);\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n typedef long long ll;\n int setbits(int n){\n int cnt = 0;\n while(n){\n cnt += (n%2);\n n /= 2;\n }\n return cnt;\n }\n \n long long countExcellentPairs(vector& nums, int k) {\n unordered_set s(nums.begin(),nums.end());\n vector v;\n for(auto& i: s){\n int x = setbits(i);\n v.push_back(x);\n }\n sort(v.begin(),v.end());\n \n ll ans = 0;\n for(int i=0;i int:\n\n\t\tresult = 0\n\n\t\tarray2 = sorted(array2)\n\n\t\tfor num in array1:\n\n\t\t\tflag = True\n\n\t\t\tlow = 0\n\t\t\thigh = len(array2)-1\n\n\t\t\twhile low <= high:\n\n\t\t\t\tmid = (low + high) // 2\n\n\t\t\t\tif abs(array2[mid] - num) <= d:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\n\t\t\t\telif array2[mid] > num:\n\t\t\t\t\thigh = mid - 1\n\n\t\t\t\telse:\n\t\t\t\t\tlow = mid + 1;\n\n\t\t\tif flag == True:\n\n\t\t\t\tresult = result + 1\n\n\t\treturn result", "solution_js": "/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @param {number} d\n * @return {number}\n */\nvar findTheDistanceValue = function(arr1, arr2, d) {\n const arr2Sorted = arr2.sort((a, b) => a - b);\n let dist = 0;\n\n for (const num of arr1) {\n if (isDistanceValid(num, d, arr2Sorted)) {\n dist += 1;\n }\n }\n\n return dist;\n};\n\nfunction isDistanceValid(number, dist, array) {\n let left = 0;\n let right = array.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (Math.abs(number - array[mid]) <= dist) {\n return false;\n }\n\n if (array[mid] < number) {\n left = mid + 1;\n }\n\n if (array[mid] > number) {\n right = mid - 1;\n }\n }\n\n return true;\n}", "solution_java": "class Solution {\n public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {\n int x=0,val=0;\n for(int i:arr1){\n for(int j:arr2){\n if(Math.abs(i-j)<=d){\n x--;\n break;\n }\n }\n x++;\n }\n return x;\n }\n}", "solution_c": "class Solution {\npublic:\n int findTheDistanceValue(vector& arr1, vector& arr2, int d) {\n sort(arr2.begin(),arr2.end());\n int ans = 0;\n for(int i : arr1){\n int id = lower_bound(arr2.begin(),arr2.end(),i) - arr2.begin();\n int closest = d+1;\n if(id != arr2.size()){\n closest = min(abs(arr2[id]-i), closest);\n } \n if(id != 0){\n closest = min(abs(arr2[id-1]-i), closest);\n }\n if(closest > d) ans++;\n }\n return ans;\n }\n};" }, { "title": "Long Pressed Name", "algo_input": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.\n\nYou examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.\n\n \nExample 1:\n\nInput: name = \"alex\", typed = \"aaleex\"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\n\n\nExample 2:\n\nInput: name = \"saeed\", typed = \"ssaaedd\"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.\n\n\n \nConstraints:\n\n\n\t1 <= name.length, typed.length <= 1000\n\tname and typed consist of only lowercase English letters.\n\n", "solution_py": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n #dic for memoization\n\t\tdic = {}\n def dfs(i, j):\n if (i, j) in dic:\n return dic[(i, j)]\n \n\t\t\t#see if there is any case where both i and j reach to the end, cuz that will be the true condition\n\t\t\t#I only need one True \n if i >= len(name):\n return j == len(typed)\n\t\t\t#we iterated through the end of typed, and not yet for name \n if j >= len(typed):\n return False\n \n\t\t\t#if the characters don't match, return False\n if name[i] != typed[j]:\n dic[(i, j)] = False\n return False\n \n\t\t\t#if the two characters match\n\t\t\t#two options, either you move on (dfs(i + 1, j + 1)) or you consider it as an extra character (dfs(i, j + 1))\n\t\t\t#return if any of them is True, which means that i, j reach to the end as aforementioned\n dic[(i, j)] = dfs(i + 1, j + 1) or dfs(i, j + 1)\n return dic[(i, j)]\n \n\t\t#start from index 0, 0\n return dfs(0, 0)", "solution_js": "var isLongPressedName = function(name, typed) {\n let i = 0;\n let j = 0;\n while (j < typed.length) {\n if (i < name.length && name[i] === typed[j]) i++;\n else if (typed[j] !== typed[j - 1]) return false; // this needs when name is traversed but there is tail of characters in typed\n j++; // Base case. keep going through typed anyway hitting first condition from time to time: (i < name.length && name[i] === typed[j])\n }\n\n return i === name.length;\n};", "solution_java": "class Solution {\n public boolean isLongPressedName(String name, String typed) {\n int i = 0;\n int j = 0;\n int m = name.length();\n int n = typed.length();\n\n while(j < n)\n {\n if(i < m && name.charAt(i) == typed.charAt(j))\n {\n i++;\n j++;\n }\n else if(j > 0 && typed.charAt(j) == typed.charAt(j-1))\n {\n j++;\n }\n else\n {\n return false;\n }\n }\n\n return i == m;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isLongPressedName(string name, string typed) {\n \n int j = 0, i = 0;\n for( ; i int:\n tiles.sort()\n\t\t#j: window index\n j = cover = res = 0\n for i in range(len(tiles)):\n\t\t\t#slide the window as far as we can to cover fully the intervals with the carpet\n while j a[0]-b[0])\n let res = 0\n\n let total = 0\n let right = 0\n\n for (let tile of sorted){\n const start = tile[0]\n const end = start + carpetLen - 1\n while(right < sorted.length && tiles[right][1] < end){\n total += tiles[right][1] - tiles[right][0] + 1\n right+=1\n }\n if(right === sorted.length || sorted[right][0] > end){\n res = Math.max(res, total)\n } else{\n res = Math.max(res, total + (end-tiles[right][0] + 1))\n }\n total -= tile[1] - tile[0] + 1\n }\n\n return res\n};", "solution_java": "class Solution\n{\n public int maximumWhiteTiles(int[][] tiles, int carpetLen)\n {\n Arrays.sort(tiles,(a,b)->{return a[0]-b[0];});\n int x = 0;\n int y = 0;\n long maxCount = 0;\n long count = 0;\n \n while(y < tiles.length && x <= y)\n {\n long start = tiles[x][0];\n long end = tiles[y][1];\n \n if(end-start+1 <= carpetLen) \n {\n count += tiles[y][1] - tiles[y][0]+1;\n maxCount = Math.max(maxCount,count);\n y++;\n }\n else \n {\n long midDist = start+carpetLen-1;\n long s = tiles[y][0];\n long e = tiles[y][1];\n if(midDist <= e && midDist >= s) maxCount = Math.max(maxCount,count+midDist-s+1);\n count -= tiles[x][1] - tiles[x][0] + 1;\n x++;\n }\n }\n return (int)maxCount;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumWhiteTiles(vector>& tiles, int carpetLen) {\n long long n = tiles.size() , ans = INT_MIN;\n sort(tiles.begin(),tiles.end());\n vector len(n) , li(n);\n\t\t//len array stores the prefix sum of tiles\n\t\t//li array stores the last index tiles[i]\n for(int i=0;i=0){\n tc+=len[idx];\n tc-=(i==0) ? 0 : len[i-1];\n }\n }\n ans = max(ans,tc);\n }\n return (int)ans;\n }\n};" }, { "title": "Squares of a Sorted Array", "algo_input": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.\n\n \nExample 1:\n\nInput: nums = [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\nExplanation: After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].\n\n\nExample 2:\n\nInput: nums = [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-104 <= nums[i] <= 104\n\tnums is sorted in non-decreasing order.\n\n\n \nFollow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?", "solution_py": "class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n l,r = 0, len(nums)-1\n pointer = 0\n arr = [0] *len(nums)\n pointer = r\n while l<=r:\n if abs(nums[r]) > abs(nums[l]):\n arr[pointer] = nums[r] **2\n r-=1\n pointer-=1\n else:\n arr[pointer] = nums[l] **2\n l+=1\n pointer-=1\n \n \n return arr\n \n \n ", "solution_js": "var sortedSquares = function(nums) {\n\tlet left = 0;\n\tlet right = nums.length - 1;\n\tconst arr = new Array(nums.length);\n\tlet arrIndex = arr.length - 1;\n\n\twhile (left <= right) {\n\t\tif (Math.abs(nums[left]) > Math.abs(nums[right])) {\n\t\t\tarr[arrIndex] = nums[left] * nums[left];\n\t\t\tleft++;\n\t\t} else {\n\t\t\tarr[arrIndex] = nums[right] * nums[right];\n\t\t\tright--;\n\t\t}\n\t\tarrIndex--;\n\t}\n\n\treturn arr;\n};", "solution_java": "class Solution {\n public int[] sortedSquares(int[] nums) {\n int s=0;\n int e=nums.length-1;\n int p=nums.length-1;\n int[] a=new int[nums.length];\n while(s<=e){\n if(nums[s]*nums[s]>nums[e]*nums[e]){\n a[p--]=nums[s]*nums[s];\n s++;\n }\n else{\n a[p--]=nums[e]*nums[e];\n e--;\n }\n }\n return a;\n }\n}", "solution_c": "class Solution {\npublic:\n vector sortedSquares(vector& nums) {\n for(int i=0;i int:\n for row in range(1, len(matrix)):\n for col in range(0, len(matrix[row])):\n if col == 0:\n matrix[row][col] += min(matrix[row-1][col+1], matrix[row-1][col])\n elif col == len(matrix[row]) - 1:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col])\n else:\n matrix[row][col] += min(matrix[row-1][col-1], matrix[row-1][col], matrix[row-1][col+1])\n \n return min(matrix[-1])", "solution_js": "var minFallingPathSum = function(matrix) {\n let n = matrix.length;\n let m = matrix[0].length;\n let dp = new Array(n).fill(0).map(() => new Array(m).fill(0));\n \n // tabulation // bottom-up approach\n \n // base case - when i will be 0, dp[0][j] will be matrix[0][j]\n for(let j = 0; j < m; j++) dp[0][j] = matrix[0][j]\n \n for(let i = 1; i < n; i++) {\n for(let j = 0 ; j < m; j++) {\n let up = matrix[i][j] + dp[i - 1][j];\n \n let upLeft = matrix[i][j];\n if((j - 1) >= 0) upLeft += dp[i - 1][j - 1]; // if not out of bound\n else upLeft += 10000; // big enough number\n \n let upRight = matrix[i][j];\n if((j + 1) < m) upRight += dp[i - 1][j + 1]; // if not out of bound\n else upRight += 10000; // big enough number\n \n dp[i][j] = Math.min(up, upLeft, upRight);\n }\n }\n return Math.min(...dp[n - 1]);\n};", "solution_java": "class Solution {\n public int min(int[][] matrix, int[][]dp, int i, int j)\n {\n int a,b,c;\n if(i==0)\n return matrix[i][j];\n if(dp[i][j] != Integer.MAX_VALUE)\n return dp[i][j];\n if(j==0)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1))+matrix[i][j];\n }\n else if(j==matrix.length -1)\n {\n dp[i][j] = Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n else\n {\n dp[i][j] = Math.min(Math.min(min(matrix, dp, i-1,j),min(matrix, dp, i-1, j+1)),min(matrix, dp, i-1, j-1))+matrix[i][j];\n }\n return dp[i][j];\n }\n\n public int minFallingPathSum(int[][] matrix) {\n int dp[][] = new int[matrix.length][matrix.length];\n if(matrix.length == 1)\n return matrix[0][0];\n for(int i=0;i=n || j>=n )\n return 0;\n return 1;\n }\n \n int solve(vector>&mat , int i , int j , int n , vector>&dp ){\n \n if(not check( i , j , n ))\n return 999999;\n \n if(i == n-1 && j < n )return mat[i][j];\n \n if(dp[i][j]!= -1 )\n return dp[i][j];\n \n \n int op_1 = mat[i][j] + solve(mat , i+1, j - 1 , n , dp );\n int op_2 = mat[i][j] + solve(mat , i+1 , j , n , dp );\n int op_3 = mat[i][j] + solve(mat , i+1 , j + 1 , n , dp );\n \n \n return dp[i][j] = min( {op_1 , op_2 , op_3} );\n \n \n }\n \n int minFallingPathSum(vector>& matrix) {\n int n = matrix[0].size();\n \n// vector>dp(n+1 , vector(n +1 , -1 ));\n// int ans = INT_MAX;\n// for(int i = 0 ; i>dp(n , vector(n, 0));\n for( int i =0 ; i=0 && j+1 < n )\n dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] , dp[i-1][j] , dp[i-1][j+1] });\n else if(j == 0 )\n dp[i][j] = matrix[i][j] + min( { dp[i-1][j] , dp[i-1][j+1] });\n else if(j == n-1 )\n dp[i][j] = matrix[i][j] + min( {dp[i-1][j-1] , dp[i-1][j] });\n }\n }\n \n int ans = INT_MAX;\n for( int i = 0 ; i int:\n nums_len = len(nums)\n count_dict = dict()\n for i in range(nums_len):\n nums[i] -= i\n if nums[i] not in count_dict:\n count_dict[nums[i]] = 0\n count_dict[nums[i]] += 1\n \n count = 0\n for key in count_dict:\n count += math.comb(count_dict[key], 2)\n return math.comb(nums_len, 2) - count", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar countBadPairs = function(nums) {\n let map={},goodPair=0;\n for(let i=0;i seen = new HashMap<>();\n long count = 0;\n for(int i = 0; i < nums.length; i++){\n int diff = i - nums[i];\n if(seen.containsKey(diff)){\n count += (i - seen.get(diff));\n }else{\n count += i;\n }\n seen.put(diff, seen.getOrDefault(diff, 0) + 1);\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n long long countBadPairs(vector& nums) {\n \n //j - i != nums[j] - nums[i] means nums[i]-i != nums[j]-j\n mapmp;\n for(int i=0;i1)\n {\n totalPair -= (it.second)*(it.second-1)/2;\n } \n }\n \n \n \n return totalPair;\n }\n};" }, { "title": "Remove Outermost Parentheses", "algo_input": "A valid parentheses string is either empty \"\", \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.\n\n\n\tFor example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\n\n\nA valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.\n\nGiven a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.\n\nReturn s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.\n\n \nExample 1:\n\nInput: s = \"(()())(())\"\nOutput: \"()()()\"\nExplanation: \nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\n\n\nExample 2:\n\nInput: s = \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation: \nThe input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\n\n\nExample 3:\n\nInput: s = \"()()\"\nOutput: \"\"\nExplanation: \nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts[i] is either '(' or ')'.\n\ts is a valid parentheses string.\n\n", "solution_py": "class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n c=0\n res=''\n for i in s:\n if i==')' and c==1:\n c=c-1\n elif i=='(' and c==0:\n c=c+1\n elif i=='(':\n res=res+'('\n c=c+1\n elif i==')':\n res=res+')'\n c=c-1\n return res", "solution_js": "var removeOuterParentheses = function(s) {\n let open = -1, ans = \"\", stack = [];\n for(let c of s) {\n if(c == '(') {\n // open for top level open\n if(open != -1) ans += c;\n stack.push(open)\n open++;\n } else {\n open = stack.pop();\n // close for top level open\n if(open != -1) ans += c;\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public String removeOuterParentheses(String s) {\n // if '(' check stack size > 0 add ans else not add ans\n // if ')' check stack size > 0 add ans else not add ans\n Stack st = new Stack<>();\n StringBuilder sb = new StringBuilder();\n for(int i=0;i 0){\n sb.append(ch);\n }\n st.push(ch);\n }\n\n else{\n st.pop();\n if(st.size() > 0){\n sb.append(ch);\n }\n }\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n stackp;\n int count=0;\n string removeOuterParentheses(string s) {\n string ans={};\n\n for(auto &i:s){\n if(i=='(' && count==0){\n p.push(i);\n count++;\n }\n else if (i=='(' && count!=0){\n ans+='(';\n p.push(i);\n count++;\n }\n else{\n count--;\n p.pop();\n if(count>0) ans+=')';\n }\n \n }\n return ans;\n }\n};" }, { "title": "Split Array Largest Sum", "algo_input": "Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.\n\nWrite an algorithm to minimize the largest sum among these m subarrays.\n\n \nExample 1:\n\nInput: nums = [7,2,5,10,8], m = 2\nOutput: 18\nExplanation:\nThere are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8],\nwhere the largest sum among the two subarrays is only 18.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5], m = 2\nOutput: 9\n\n\nExample 3:\n\nInput: nums = [1,4,4], m = 3\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t0 <= nums[i] <= 106\n\t1 <= m <= min(50, nums.length)\n\n", "solution_py": "class Solution:\n def splitArray(self, nums: List[int], m: int) -> int:\n lo, hi = max(nums), sum(nums)\n while lo < hi:\n mid = (lo+hi)//2\n tot, cnt = 0, 1\n for num in nums:\n if tot+num<=mid: \n tot += num\n else:\n tot = num\n cnt += 1\n if cnt>m: lo = mid+1\n else: hi = mid\n return hi", "solution_js": "var splitArray = function(nums, m) {\nconst n = nums.length;\nvar mat = [];\nvar sumArr = [nums[0]];\nfor(let i=1; i {// recursive partition finder\n if(memo[m+'_'+lastPartition]!==undefined){\n return memo[m+'_'+lastPartition];//memoised\n }\n if(m==1){//base case, only 1 partition left\n memo[m+'_'+lastPartition] = mat[lastPartition][mat[0].length-1];\n return memo[m+'_'+lastPartition];\n }\n let min = Infinity;\n let maxSum = -Infinity;\n let lastval = Infinity;\n for(let i = lastPartition; i<=n-m; i++){//for mth partition, find the min sum for all possible partition placements\n while(i>0 && i& nums, int m) {\n long long low = 0;\n long long res =0;\n long long high = 1000000005;\n while(low<=high){\n long long mid = (low+high)/2;\n int cnt = 1;\n long long current_sum = 0;\n int can = 1;\n for(auto num: nums){\n if(num > mid){\n can = 0;\n break;\n }\n if(current_sum+num>mid){\n cnt ++;\n current_sum = 0;\n }\n current_sum += num;\n }\n if(can==1){\n if(cnt>m){\n low = mid+1;\n }\n else{\n res = mid;\n high = mid-1;\n }\n }\n else{\n low = mid+1;\n }\n }\n return res;\n }\n};" }, { "title": "Largest 1-Bordered Square", "algo_input": "Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.\n\n \nExample 1:\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 9\n\n\nExample 2:\n\nInput: grid = [[1,1,0,0]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= grid.length <= 100\n\t1 <= grid[0].length <= 100\n\tgrid[i][j] is 0 or 1\n", "solution_py": "class Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n dp = [[[grid[i][j]] * 4 for j in range(n)] for i in range(m)]\n for i in range(m):\n for j in range(n):\n if i > 0:\n if grid[i][j] == 1:\n dp[i][j][1] = dp[i - 1][j][1] + 1\n if j > 0:\n if grid[i][j] == 1:\n dp[i][j][0] = dp[i][j - 1][0] + 1\n for i in range(m - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n if i < m - 1:\n if grid[i][j] == 1:\n dp[i][j][2] = dp[i + 1][j][2] + 1\n if j < n - 1:\n if grid[i][j] == 1:\n dp[i][j][3] = dp[i][j + 1][3] + 1\n mside = min(m, n)\n for l in range(mside - 1, -1, -1):\n for i in range(m - l):\n for j in range(n - l):\n if min(dp[i][j][2], dp[i][j][3], dp[i + l][j + l][0], dp[i + l][j + l][1]) >= l + 1:\n return (l + 1) * (l + 1)\n return 0", "solution_js": "var largest1BorderedSquare = function(grid) {\n let m = grid.length, n = grid[0].length;\n let top = Array(m).fill(0).map(() => Array(n).fill(0));\n let left = Array(m).fill(0).map(() => Array(n).fill(0));\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === 1) {\n left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;\n top[i][j] = i > 0 ? top[i - 1][j] + 1 : 1;\n }\n }\n }\n\n let ans = 0;\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n let size = Math.min(top[i][j], left[i][j]);\n for (let k = size; k > 0; k--) {\n let bottomLeftTop = top[i][j - k + 1];\n let topRightLeft = left[i - k + 1][j];\n if (bottomLeftTop >= k && topRightLeft >= k) {\n ans = Math.max(ans, k * k);\n break;\n }\n }\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int largest1BorderedSquare(int[][] grid) {\n int m=grid.length;\n int n=grid[0].length;\n\t\t// rows[r][c] is the length of the line ended at [r,c] on row r\n int[][] rows=new int[m][n]; \n\t\t// the length of the line ended at [r,c] on colume c\n int[][] cols=new int[m][n];\n int res=0;\n for(int r=0;r=rows[r][c]||res>=cols[r][c]){\n continue;\n }\n res=Math.max(res,getD(rows,cols,r,c));\n }\n }\n }\n return res*res;\n }\n \n\t// get the dimension of the largest square which bottom-right point is [row,col]\n private int getD(int[][] rows,int[][] cols,int row,int col){\n int len=Math.min(rows[row][col],cols[row][col]);\n for(int i=len-1;i>=0;i--){\n if(rows[row-i][col]>i && cols[row][col-i]>i){\n return i+1;\n }\n }\n return 1;\n }\n}", "solution_c": "class Solution {\npublic:\n int largest1BorderedSquare(vector>& g) {\n int n=g.size();\n int m=g[0].size();\n int ver[n][m]; // to store lenght of continuous 1's vertically\n int hor[n][m]; // to store lenght of continuous 1's horizontally\n\t\t\n\t\t// fill vertical table\n for(int i=n-1;i>=0;i--){\n for(int j=0;j=0;i--){\n for(int j=m-1;j>=0;j--){\n if(g[i][j]==1){\n if(j==m-1) hor[i][j]=1;\n else hor[i][j]=hor[i][j+1]+1;\n }\n else hor[i][j]=0;\n }\n }\n \n\t\t// Iterate through the all i and j and find best solution\n int ans=0;\n for(int i=0;i=p+1) temp=p+1;\n }\n ans=max(ans,temp);\n }\n }\n ans*=ans;\n return ans;\n \n }\n};" }, { "title": "String Compression", "algo_input": "Given an array of characters chars, compress it using the following algorithm:\n\nBegin with an empty string s. For each group of consecutive repeating characters in chars:\n\n\n\tIf the group's length is 1, append the character to s.\n\tOtherwise, append the character followed by the group's length.\n\n\nThe compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.\n\nAfter you are done modifying the input array, return the new length of the array.\n\nYou must write an algorithm that uses only constant extra space.\n\n \nExample 1:\n\nInput: chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput: Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation: The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".\n\n\nExample 2:\n\nInput: chars = [\"a\"]\nOutput: Return 1, and the first character of the input array should be: [\"a\"]\nExplanation: The only group is \"a\", which remains uncompressed since it's a single character.\n\n\nExample 3:\n\nInput: chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput: Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation: The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".\n\n \nConstraints:\n\n\n\t1 <= chars.length <= 2000\n\tchars[i] is a lowercase English letter, uppercase English letter, digit, or symbol.\n\n", "solution_py": "class Solution:\n def compress(self, chars: List[str]) -> int:\n stri = ''\n stack = [chars.pop(0)]\n \n while chars:\n p = chars.pop(0)\n \n if p in stack:\n stack.append(p)\n else:\n stri = stri + stack[-1] + str(len(stack) if len(stack) > 1 else '')\n stack = [p] \n \n o = list(stri + stack[-1] + str(len(stack) if len(stack) > 1 else ''))\n \n for i in o:\n chars.append(i)", "solution_js": "var compress = function(chars) {\n for(let i = 0; i < chars.length; i++){\n let count = 1\n while(chars[i] === chars[i+count]){\n delete chars[i+count]\n count++\n }\n if(count > 1){\n let count2 = 1\n String(count).split('').forEach((a) =>{\n chars[i+count2] = a\n count2++\n })\n }\n i = i + count -1\n }\n return chars.flat().filter((x) => x).length\n};", "solution_java": "class Solution {\n public int compress(char[] chars) {\n int index = 0;\n int i = 0;\n\n while (i < chars.length) {\n int j = i;\n\n while (j < chars.length && chars[j] == chars[i]) {\n j++;\n }\n\n chars[index++] = chars[i];\n\n if (j - i > 1) {\n String count = j - i + \"\";\n\n for (char c : count.toCharArray()) {\n chars[index++] = c;\n }\n }\n\n i = j;\n }\n\n return index;\n }\n}\n\n// TC: O(n), SC: O(1)", "solution_c": "class Solution {\npublic:\n\nvoid add1(vector& arr) {\n \n if(arr.back() < 9) {\n arr.back()++;\n return ;\n }\n \n reverse(begin(arr),end(arr));\n int carry = 1;\n \n for(int i=0;i& chars) {\n \n int i=0;\n for(int j=0;j cnt{0};\n char ch = chars[j];\n while(j < chars.size()and chars[j] == ch) {\n j++;\n add1(cnt);\n }\n \n j--; // bcoz j will be incremented in for loop updation condition.\n chars[i++] = ch;\n \n for(auto& it:cnt)\n chars[i++] = '0'+it;\n \n }\n }\n chars.erase(chars.begin()+i,chars.end());\n return i;\n}" }, { "title": "Step-By-Step Directions From a Binary Tree Node to Another", "algo_input": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.\n\nFind the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction:\n\n\n\t'L' means to go from a node to its left child node.\n\t'R' means to go from a node to its right child node.\n\t'U' means to go from a node to its parent node.\n\n\nReturn the step-by-step directions of the shortest path from node s to node t.\n\n \nExample 1:\n\nInput: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput: \"UURL\"\nExplanation: The shortest path is: 3 → 1 → 5 → 2 → 6.\n\n\nExample 2:\n\nInput: root = [2,1], startValue = 2, destValue = 1\nOutput: \"L\"\nExplanation: The shortest path is: 2 → 1.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is n.\n\t2 <= n <= 105\n\t1 <= Node.val <= n\n\tAll the values in the tree are unique.\n\t1 <= startValue, destValue <= n\n\tstartValue != destValue\n\n", "solution_py": "class Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n def find(n: TreeNode, val: int, path: List[str]) -> bool:\n if n.val == val:\n return True\n if n.left and find(n.left, val, path):\n path += \"L\"\n elif n.right and find(n.right, val, path):\n path += \"R\"\n return path\n s, d = [], []\n find(root, startValue, s)\n find(root, destValue, d)\n while len(s) and len(d) and s[-1] == d[-1]:\n s.pop()\n d.pop()\n return \"\".join(\"U\" * len(s)) + \"\".join(reversed(d))", "solution_js": "var getDirections = function(root, startValue, destValue) {\n const getPath = (node, value, acc='') => {\n if (node === null) {\n return '';\n } else if (node.val === value) {\n return acc;\n } else {\n return getPath(node.left, value, acc + 'L') + getPath(node.right, value, acc + 'R')\n }\n }\n \n\t// generate the paths\n let startPath = getPath(root, startValue);\n let destPath = getPath(root, destValue);\n \n // find the lowest common ancestor\n let i = 0;\n for (; i < startPath.length && i < destPath.length && startPath[i] === destPath[i]; i++);\n \n\t// output the final path\n let output = '';\n for (let j = i; j < startPath.length; j++) {\n output += 'U';\n }\n \n return output + destPath.substring(i);\n};", "solution_java": "class Solution {\n \n private boolean DFS(TreeNode currNode, StringBuilder path, int destVal) {\n if(currNode == null) return false;\n if(currNode.val == destVal) return true;\n if(DFS(currNode.left, path, destVal)) path.append(\"L\");\n else if(DFS(currNode.right, path, destVal)) path.append(\"R\");\n return path.length() > 0;\n }\n \n public String getDirections(TreeNode root, int startValue, int destValue) {\n StringBuilder startToRoot = new StringBuilder();\n StringBuilder endToRoot = new StringBuilder();\n \n DFS(root, startToRoot, startValue);\n DFS(root, endToRoot, destValue);\n \n int i = startToRoot.length(), j = endToRoot.length();\n int cnt = 0;\n while(i > 0 && j > 0 && startToRoot.charAt(i-1) == endToRoot.charAt(j-1)) {\n cnt++; i--; j--;\n }\n \n String sPath = \"U\".repeat(startToRoot.length() - cnt);\n String ePath = endToRoot.reverse().toString().substring(cnt, endToRoot.length());\n \n return sPath + ePath;\n }\n}", "solution_c": "class Solution {\npublic:\n bool search(TreeNode* root, int target, string &s){\n if(root==NULL) {\n return false;\n }\n if(root->val==target) {\n return true;\n }\n \n bool find1=search(root->left,target, s+='L'); // search on left side\n if(find1) return true;\n s.pop_back(); // backtracking step\n \n bool find2= search(root->right,target, s+='R'); // search on right side\n if(find2) return true;\n s.pop_back(); // backtracking step\n return false;\n }\n \n TreeNode* lca(TreeNode* root ,int n1 ,int n2)\n {\n if(root==NULL)\n return NULL;\n if(root->val==n1 or root->val==n2)\n return root;\n \n TreeNode* left=lca(root->left,n1,n2);\n TreeNode* right=lca(root->right,n1,n2);\n \n if(left!=NULL && right!=NULL)\n return root;\n if(left)\n return left;\n if(right)\n return right;\n \n return NULL; // not present in tree\n \n }\n string getDirections(TreeNode* root, int startValue, int destValue) {\n TreeNode* temp=lca(root,startValue,destValue);\n \n string s1,s2;\n search(temp,startValue,s1);\n search(temp,destValue,s2);\n for(auto &it:s1){\n it='U';\n }\n return s1+s2;\n }\n};" }, { "title": "Number of People Aware of a Secret", "algo_input": "On day 1, one person discovers a secret.\n\nYou are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.\n\nGiven an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: n = 6, delay = 2, forget = 4\nOutput: 5\nExplanation:\nDay 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)\n\n\nExample 2:\n\nInput: n = 4, delay = 1, forget = 3\nOutput: 6\nExplanation:\nDay 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)\n\n\n \nConstraints:\n\n\n\t2 <= n <= 1000\n\t1 <= delay < forget <= n\n\n", "solution_py": "```class Solution:\n def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n table = [0]*(forget+1)\n table[1] = 1\n days = 1\n while days<=n-1:\n count = 0\n for k in range(forget-1,-1,-1):\n if k+1>delay:\n table[k+1] = table[k]\n count+=table[k]\n elif k+1<=delay:\n table[k+1] = table[k]\n table[1] = count\n days+=1\n count = 0\n for k in range(1,forget+1):\n count+=table[k]\n return count%(pow(10,9)+7)\n\t\t\nTC---O(forget*n)\nsc---O(forget)\n ", "solution_js": "/**\n * @param {number} n\n * @param {number} delay\n * @param {number} forget\n * @return {number}\n */\nvar peopleAwareOfSecret = function(n, delay, forget) {\n const dp=new Array(n+1).fill(0);\n let numberOfPeopleSharingSecret = 0;\n let totalNumberOfPeopleWithSecret = 0;\n const MOD = 1000000007n;\n \n dp[1]=1; // as on day one only one person knows the secret\n \n for(let i=2;i<=n;i++){\n const numberOfNewPeopleSharingSecret = dp[Math.max(i-delay,0)];\n const numberOfPeopleForgettingSecret = dp[Math.max(i-forget,0)];\n numberOfPeopleSharingSecret = BigInt(numberOfPeopleSharingSecret) + \n ( BigInt(numberOfNewPeopleSharingSecret) \n - BigInt(numberOfPeopleForgettingSecret) \n + BigInt(MOD)\n ) % BigInt(MOD);\n \n dp[i] = numberOfPeopleSharingSecret;\n }\n \n for(let i=n-forget+1;i<=n;i++){\n totalNumberOfPeopleWithSecret = \n (BigInt(totalNumberOfPeopleWithSecret) + BigInt(dp[i])) % BigInt(MOD); \n }\n \n return totalNumberOfPeopleWithSecret;\n};", "solution_java": "class Solution {\n public int peopleAwareOfSecret(int n, int delay, int forget) {\n long mod = 1000000007L;\n long[] shares = new long[n + 1];\n long[] forgets = new long[n + 1];\n\n if (delay < n) {\n shares[delay + 1] = 1;\n }\n if (forget < n) {\n forgets[forget + 1] = 1;\n }\n\n long shareToday = 0;\n long peopleKnow = 1;\n for (int i = delay; i <= n; i++) {\n shareToday += shares[i] % mod;\n shareToday -= forgets[i] % mod;\n\n peopleKnow -= forgets[i] % mod;\n peopleKnow += shareToday % mod;\n\n if (i + delay < n + 1) {\n shares[i + delay] += shareToday % mod;\n }\n if (i + forget < n + 1) {\n forgets[i + forget] += shareToday % mod;\n }\n }\n\n return (int) (peopleKnow % mod);\n }\n}", "solution_c": "static int MOD=1e9+7;\nclass Solution {\npublic:\n int delay,forget;\n vector memo;\n // Total number of people who would have found out about the secret by the nth day.\n long dp(int n) {\n if(!n)\n return 0;\n if(memo[n]!=-1) // Return cached result if exists.\n return memo[n];\n\t\t// Current contribution of 1 person who knows the secret\n long result=1;\n for(int i=delay;i=0)\n result=(result+dp(n-i))%MOD;\n return memo[n]=result;\n }\n int peopleAwareOfSecret(int n, int delay, int forget) {\n this->delay=delay;\n this->forget=forget;\n memo.resize(n+1,-1);\n return (dp(n)-dp(n-forget)+MOD)%MOD; // Subtract the people who found out by the `n-forget` day as observed.\n }\n};" }, { "title": "Minimum Difference in Sums After Removal of Elements", "algo_input": "You are given a 0-indexed integer array nums consisting of 3 * n elements.\n\nYou are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:\n\n\n\tThe first n elements belonging to the first part and their sum is sumfirst.\n\tThe next n elements belonging to the second part and their sum is sumsecond.\n\n\nThe difference in sums of the two parts is denoted as sumfirst - sumsecond.\n\n\n\tFor example, if sumfirst = 3 and sumsecond = 2, their difference is 1.\n\tSimilarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.\n\n\nReturn the minimum difference possible between the sums of the two parts after the removal of n elements.\n\n \nExample 1:\n\nInput: nums = [3,1,2]\nOutput: -1\nExplanation: Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1. \n\n\nExample 2:\n\nInput: nums = [7,9,5,8,1,3]\nOutput: 1\nExplanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.\n\n\n \nConstraints:\n\n\n\tnums.length == 3 * n\n\t1 <= n <= 105\n\t1 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def minimumDifference(self, nums: List[int]) -> int:\n h=heapq\n k=len(nums)//3\n min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol=[] , [] , [] , [] , 0 , 0, []\n h.heapify(max_heap) , h.heapify(min_heap)\n for x in nums[:-k]:\n h.heappush(min_heap,-x)\n min_sum+=x\n if len(min_heap)>k: min_sum+=h.heappop(min_heap)\n min_sol.append(min_sum)\n for x in nums[::-1][:-k]:\n h.heappush(max_heap,x)\n max_sum+=x\n if len(max_heap)>k: max_sum-=h.heappop(max_heap)\n max_sol.append(max_sum)\n min_sol =min_sol[k-1:]\n max_sol=max_sol[k-1:][::-1]\n return min( min_value - max_value for min_value , max_value in zip(min_sol,max_sol) )", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimumDifference = function(nums) {\n//Creating heap \n class Heap{\n constructor(type){\n this.type = type;\n this.data = [];\n this.data[0] = undefined;\n }\n print(){\n for(let i=1;i0){\n let temp = this.data[Math.floor(lastIndex/2)];\n this.data[Math.floor(lastIndex/2)] = this.data[lastIndex];\n this.data[lastIndex] = temp;\n lastIndex = Math.floor(lastIndex/2);\n }\n }\n //This returns a positive number if a is greater than b. Here meaing of being greater depends on the type of heap. For max heap it will return positive number if a>b and for min heap it will return positive number if a1){\n this.data[1] = this.data.pop();\n this.heapify(1);\n }else{//If the size is 0 then just remove the element, no shifting and hipify will be applicable\n this.data.pop();\n }\n return max;\n }\n getTop(){\n let max = null;\n if(this.getSize()>=1){\n max = this.data[1];\n }\n return max;\n }\n heapify(pos){\n if(pos*2>this.data.length-1){\n //That means element at index 'pos' is not having any child\n return;\n }\n if(\n (this.data[pos*2]!==undefined && this.compare(this.data[pos*2],this.data[pos])>0)\n || (this.data[pos*2+1]!==undefined && this.compare(this.data[pos*2+1],this.data[pos])>0)\n ){\n if(this.data[pos*2+1]===undefined || this.compare(this.data[pos*2+1],this.data[pos*2])<=0){\n let temp = this.data[pos*2];\n this.data[pos*2] = this.data[pos];\n this.data[pos] = temp;\n this.heapify(pos*2);\n }else{\n let temp = this.data[pos*2+1];\n this.data[pos*2+1] = this.data[pos];\n this.data[pos] = temp;\n this.heapify(pos*2+1);\n }\n }\n }\n }\n let maxHeap=new Heap(),minHeap=new Heap('min'),sum=0;\n let n = nums.length/3,leftArr=[],rightArr=[];\n for(let i=0;i<2*n;i++){\n if(maxHeap.getSize()nums[i]){\n let top = maxHeap.removeTop();\n sum -= top;\n sum += nums[i];\n maxHeap.insert(nums[i]);\n }\n \n }\n if(maxHeap.getSize()===n){\n leftArr.push(sum);\n }\n }\n sum=0;\n for(let i=3*n-1;i>=n;i--){\n if(minHeap.getSize() max=new PriorityQueue(Comparator.reverseOrder());\n\n long sum=0;\n\n // Initialize with the first 1/3 n part.\n for(int i=0;i min=new PriorityQueue();\n // Initialize with the last 1/3 n part.\n for(int i=0;i& nums) {\n int N = nums.size();\n int n = N/3;\n priority_queue pq;\n map m;\n long long sum = 0;\n for(int i=0;i, greater> p;\n for(int i=N-1;i>N-1-n;i--){\n sum += nums[i];\n p.push(nums[i]);\n }\n for(int i=0;i<=n;i++){\n if(i == 0){\n m[n-i] -= sum;\n }\n else{\n p.push(nums[N-n-i]);\n sum += nums[N-n-i];\n sum -= p.top();\n p.pop();\n m[n-i] -= sum;\n }\n }\n long long ans = 9223372036854775807;\n for(auto it : m){\n ans = min(ans, it.second);\n }\n return ans;\n }\n};" }, { "title": "Reverse String II", "algo_input": "Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.\n\nIf there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.\n\n \nExample 1:\nInput: s = \"abcdefg\", k = 2\nOutput: \"bacdfeg\"\nExample 2:\nInput: s = \"abcd\", k = 2\nOutput: \"bacd\"\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts consists of only lowercase English letters.\n\t1 <= k <= 104\n\n", "solution_py": "class Solution:\n def reverseStr(self, s: str, k: int) -> str:\n a=list(s)\n for i in range(0,len(a),2*k):\n a[i:i+k]=a[i:i+k][::-1]\n print(a)\n return(\"\".join(a))", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {string}\n */\nvar reverseStr = function(s, k) {\n const sArr = s.split('');\n\n let start = 0;\n let end = k - 1;\n\n const swapBlock = (start, end) => {\n while (start < end) {\n [sArr[start], sArr[end]] = [sArr[end], sArr[start]];\n\n start++;\n end--;\n }\n };\n\n while (start < end) {\n swapBlock(start, end);\n\n start = start + (k * 2);\n end = sArr[start + (k-1)] ? start + (k-1) : s.length - 1;\n }\n\n return sArr.join('');\n};", "solution_java": "class Solution {\n public String reverseStr(String s, int k) {\n char[] ch=s.toCharArray();\n int cnt=1,i=0;\n StringBuilder sb=new StringBuilder();\n String ans=\"\";\n if(k>=s.length()){\n sb.append(s);\n sb.reverse();\n return sb.toString();\n }\n for(i=0;i=n) \n j=n-1;\n while(k<(j)){\n swap(s[k],s[j]);\n k++,j--;\n }\n }\n return s;\n }\n};" }, { "title": "Find Substring With Given Hash Value", "algo_input": "The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:\n\n\n\thash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.\n\n\nWhere val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.\n\nYou are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.\n\nThe test cases will be generated such that an answer always exists.\n\nA substring is a contiguous non-empty sequence of characters within a string.\n\n \nExample 1:\n\nInput: s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput: \"ee\"\nExplanation: The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".\n\n\nExample 2:\n\nInput: s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput: \"fbx\"\nExplanation: The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".\n\n\n \nConstraints:\n\n\n\t1 <= k <= s.length <= 2 * 104\n\t1 <= power, modulo <= 109\n\t0 <= hashValue < modulo\n\ts consists of lowercase English letters only.\n\tThe test cases are generated such that an answer always exists.\n\n", "solution_py": "class Solution:\n def subStrHash(self, s: str, power: int, mod: int, k: int, hashValue: int) -> str:\n val = lambda ch : ord(ch) - ord(\"a\") + 1\n hash, res, power_k = 0, 0, pow(power, k, mod)\n for i in reversed(range(len(s))):\n hash = (hash * power + val(s[i])) % mod\n if i < len(s) - k:\n hash = (mod + hash - power_k * val(s[i + k]) % mod) % mod\n res = i if hash == hashValue else res\n return s[res:res + k]", "solution_js": "let arrChar =\"1abcdefghijklmnopqrstuvwxyz\".split(\"\");\nvar subStrHash = function(s, power, modulo, k, hashValue) {\n \n for(let i=0;i= s.length() - k) {\n\t\t\t// (a+b) % modulo = ( (a % modulo) + (b % modulo) ) % modulo;\n\t\t\t// do it for k times from behind\n currentHashValue += ((s.charAt(index--) - 'a' + 1) % modulo * powers[powerIndex--] % modulo) % modulo;\n }\n currentHashValue %= modulo;\n \n int startIndex = 0;\n if (currentHashValue == hashValue) {\n startIndex = s.length() - k;\n }\n \n\t\t// I have pre computed already for k values from behind. so start from (length of S - k - 1)\n\t\t// Let's take an example of \"leetcode\" itself\n\t\t// \"de\" is pre computed\n\t\t// point is to add one character from behind and remove one from end (Sliding from back to first)\n\t\t// Modular Arithmetic for (a-b) % modulo = ( (a % modulo) - (b % modulo) + modulo) % modulo;\n\t\t// keep tracking of the start index if hash value matches. That's it.\n for (int i = s.length() - k - 1; i >= 0; i--) {\n\t\t\t// below line a --> currentHashValue \n\t\t\t// below line b --> (s.charAt(i+k) - 'a' + 1 * powers[k-1])\n currentHashValue = ((currentHashValue % modulo) - (((s.charAt(i+k) - 'a' + 1) * powers[k-1]) % modulo) + modulo) % modulo;\n\t\t\t// we need to multiply a power once for all\n\t\t\t// MULTIPLICATION\n currentHashValue = currentHashValue * power;\n\t\t\t// Modular Arithmetic for (a+b) % modulo is below line\n currentHashValue = (currentHashValue % modulo + (s.charAt(i) - 'a' + 1) % modulo) % modulo;\n \n if (currentHashValue == hashValue) {\n startIndex = i;\n }\n }\n return s.substring(startIndex, startIndex+k);\n }\n \n private long binaryExponentiation(long a, long b, long mod) {\n a %= mod;\n long result = 1;\n while (b > 0) {\n if (b % 2 == 1)\n result = result * a % mod;\n a = a * a % mod;\n b >>= 1;\n }\n return result;\n }\n}", "solution_c": "'''\nclass Solution {\npublic:\n string subStrHash(string s, int power, int modulo, int k, int hashValue) {\n int n=s.size(); \n long long int sum=0;\n long long int p=1;\n\t\t// Intializing a window from end of size k \n for(int i=0;i=k;i--)\n\t\t{ \n\t\t//removing last element from window\n sum-=(s[i]-'a'+1)*(p%modulo); \n\t\t\t\t // dividing by modulo to avoid integer overflow conditions\n sum=sum%modulo; \n\t\t\t\t // muliplying the given string by power\n sum=sum*(power%modulo); \n\t\t\t\t // adding (i-k)th element in the window \n sum+=s[i-k]-'a'+1; \n\t\t\t\t // if sum < 0 then it created problem in modulus thats why making it positive\n while(sum%modulo<0){ \n sum=sum+modulo;\n }\n if(sum%modulo==hashValue){\n res=i-k; // storing the starting window index because we have to return the first string from starting \n }\n }\n return s.substr(res,k);\n }\n};\n'''" }, { "title": "Smallest Missing Genetic Value in Each Subtree", "algo_input": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.\n\nThere are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.\n\nReturn an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.\n\nThe subtree rooted at a node x contains node x and all of its descendant nodes.\n\n \nExample 1:\n\nInput: parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput: [5,1,1,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\n\n\nExample 2:\n\nInput: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput: [7,1,1,4,2,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\n\n\nExample 3:\n\nInput: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput: [1,1,1,1,1,1,1]\nExplanation: The value 1 is missing from all the subtrees.\n\n\n \nConstraints:\n\n\n\tn == parents.length == nums.length\n\t2 <= n <= 105\n\t0 <= parents[i] <= n - 1 for i != 0\n\tparents[0] == -1\n\tparents represents a valid tree.\n\t1 <= nums[i] <= 105\n\tEach nums[i] is distinct.\n\n", "solution_py": "class Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n ans = [1] * len(parents)\n if 1 in nums:\n tree = {}\n for i, x in enumerate(parents):\n tree.setdefault(x, []).append(i)\n\n k = nums.index(1)\n val = 1\n seen = set()\n\n while k != -1:\n stack = [k]\n while stack:\n x = stack.pop()\n seen.add(nums[x])\n for xx in tree.get(x, []):\n if nums[xx] not in seen:\n stack.append(xx)\n seen.add(nums[xx])\n while val in seen: val += 1\n ans[k] = val\n k = parents[k]\n return ans", "solution_js": "var smallestMissingValueSubtree = function(parents, nums) {\n let n=parents.length,next=[...Array(n)].map(d=>[]),used={}\n for(let i=1;i{\n if(used[nums[node]])\n return\n used[nums[node]]=true\n for(let child of next[node])\n dfs(child)\n }\n let cur=nums.indexOf(1),leftAt=1,res=[...Array(n)].map(d=>1)\n while(cur!==-1){\n dfs(cur)\n while(used[leftAt])\n leftAt++\n res[cur]=leftAt\n cur=parents[cur]\n }\n return res\n};", "solution_java": "class Solution {\n public int[] smallestMissingValueSubtree(int[] parents, int[] nums) {\n int n = parents.length;\n int[] res = new int[n];\n for (int i = 0; i < n; i++) {\n res[i] = 1;\n }\n \n int oneIndex = -1;\n for (int i = 0; i < n; i++) {\n if (nums[i] == 1) {\n oneIndex = i;\n break;\n }\n }\n \n // 1 not found\n if (oneIndex == -1) {\n return res;\n }\n \n Map> graph = new HashMap<>();\n for (int i = 1; i < n; i++) {\n Set children = graph.getOrDefault(parents[i], new HashSet());\n children.add(i);\n graph.put(parents[i], children);\n }\n \n Set visited = new HashSet();\n \n int parentIter = oneIndex;\n int miss = 1;\n while (parentIter >= 0) {\n dfs(parentIter, graph, visited, nums);\n while (visited.contains(miss)) {\n miss++;\n }\n res[parentIter] = miss;\n parentIter = parents[parentIter];\n }\n return res;\n }\n \n public void dfs(int ind, Map> graph, Set visited, int []nums) {\n if (!visited.contains(nums[ind])) {\n Set children = graph.getOrDefault(ind, new HashSet());\n \n for (int p : children) {\n dfs(p, graph, visited, nums);\n }\n visited.add(nums[ind]);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n unordered_set visited;\n vector nums ;\n vector> adj;\n\n void dfs(int node){\n for(auto child:adj[node]){\n if(!visited.count(nums[child])){\n visited.insert(nums[child]);\n dfs(child);\n }\n }\n }\n\n vector smallestMissingValueSubtree(vector& parents, vector& nums) {\n int n = parents.size(), missing = 1;\n adj.resize(n);\n vector res;\n this->nums = nums;\n res.resize(n,1);\n\n for(int i=1; i bool:\n if len(s) != len(goal):\n return False\n diffCharactersCount = 0\n diffCharactersInS = []\n diffCharactersInGoal = []\n for i in range(len(s)):\n if s[i] != goal[i]:\n diffCharactersCount += 1\n diffCharactersInS.append(s[i])\n diffCharactersInGoal.append(goal[i])\n if diffCharactersCount == 2:\n # if there are only 2 different characters, then they should be swappable\n if ((diffCharactersInS[0] == diffCharactersInGoal[1]) and (diffCharactersInS[1] == diffCharactersInGoal[0])):\n return True\n return False\n elif diffCharactersCount == 0:\n # if there is atleast one repeating character in the string then its possible for swap\n counts = Counter(s)\n for k,v in counts.items():\n if v > 1:\n return True\n # if different characters count is not 2 or 0, then it's not possible for the strings to be buddy strings\n return False", "solution_js": "var buddyStrings = function(A, B) {\n if(A.length != B.length) return false;\n const diff = [];\n \n for(let i = 0; i < A.length; i++) {\n if(A[i] != B[i]) diff.push(i);\n if(diff.length > 2) return false;\n }\n if(!diff.length) return A.length != [...new Set(A)].length;\n const [i, j] = diff; \n return A[i] == B[j] && B[i] == A[j];\n};", "solution_java": "class Solution {\n public boolean buddyStrings(String s, String goal) {\n char a = '\\u0000', b = '\\u0000';\n char c = '\\u0000', d = '\\u0000';\n int lenS = s.length();\n int lenGoal = goal.length();\n boolean flag = true;\n HashSet hset = new HashSet<>();\n\n if(lenS != lenGoal)\n return false;\n\n if(s.equals(goal)){\n for(int i = 0; i < lenS; i++){\n if(!hset.contains(s.charAt(i))){\n hset.add(s.charAt(i));\n }\n else\n return true;\n }\n return false;\n }\n else{\n for(int i = 0; i < lenS; i++){\n if(s.charAt(i) == goal.charAt(i)){\n continue;\n }\n if(a == '\\u0000'){\n a = s.charAt(i);\n c = goal.charAt(i);\n continue;\n }\n if(b == '\\u0000'){\n b = s.charAt(i);\n d = goal.charAt(i);\n continue;\n }\n return false;\n }\n\n if(a == d && c == b && a != '\\u0000')\n return true;\n\n return false;\n }\n }\n}", "solution_c": "class Solution {\npublic:\n //In case string is duplicated, check if string has any duplicate letters\n bool dupeCase(string s){\n unordered_set letters;\n for(auto it : s){\n if(letters.count(it)){ //Found dupe letter (they can be swapped)\n return true;\n } else {\n letters.insert(it);\n }\n }\n return false; //all letters unique\n }\n \n bool buddyStrings(string s, string goal) {\n //check len\n if(goal.length() != s.length()) return false;\n //If strings are the same, use diff. method\n if(s == goal) return dupeCase(s);\n //Track index of differences \n vector diff;\n for(int i = 0; i < s.length(); i++){\n if(s[i] != goal[i]){ //If diff found\n if(diff.size() > 2){ //If this is third diff, return false\n return false;\n } else { //If not store in diff array\n diff.push_back(i);\n }\n }\n }\n //If only one diff found, return false\n if(diff.size() == 1) return false;\n //else return if swap works\n return (s[diff[0]] == goal[diff[1]] && s[diff[1]] == goal[diff[0]]);\n }\n};" }, { "title": "Minimum Time Difference", "algo_input": "Given a list of 24-hour clock time points in \"HH:MM\" format, return the minimum minutes difference between any two time-points in the list.\n \nExample 1:\nInput: timePoints = [\"23:59\",\"00:00\"]\nOutput: 1\nExample 2:\nInput: timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput: 0\n\n \nConstraints:\n\n\n\t2 <= timePoints.length <= 2 * 104\n\ttimePoints[i] is in the format \"HH:MM\".\n\n", "solution_py": "class Solution:\n\tdef findMinDifference(self, timePoints: List[str]) -> int:\n\t\ttimePoints.sort()\n\n\t\tdef getTimeDiff(timeString1, timeString2):\n\t\t\ttime1 = int(timeString1[:2]) * 60 + int(timeString1[3:])\n\t\t\ttime2 = int(timeString2[:2]) * 60 + int(timeString2[3:])\n\n\t\t\tminDiff = abs(time1 - time2)\n\n\t\t\treturn min(minDiff, 1440 - minDiff)\n\n\t\tresult = getTimeDiff(timePoints[0], timePoints[-1]) # edge case, we need to check minDiff of first and last time after sorting\n\n\t\tfor i in range(len(timePoints)-1):\n\t\t\tcurMin = getTimeDiff(timePoints[i], timePoints[i+1])\n\n\t\t\tif curMin < result:\n\t\t\t\tresult = curMin\n\n\t\treturn result\n\t\t", "solution_js": "var findMinDifference = function(timePoints) {\n const DAY_MINUTES = 24 * 60;\n const set = new Set();\n\n for (let index = 0; index < timePoints.length; index++) {\n const time = timePoints[index];\n const [hours, minutes] = time.split(':');\n const totalMinutes = hours * 60 + +minutes;\n if (set.has(totalMinutes)) return 0;\n set.add(totalMinutes);\n }\n\n const timeMinutes = [...set].sort((a, b) => a - b);\n return timeMinutes.reduce((min, time, index) => {\n const next = timeMinutes[index + 1];\n const diff = next ? next - time : DAY_MINUTES - time + timeMinutes[0];\n return Math.min(min, diff);\n }, Infinity);\n};", "solution_java": "class Solution {\n public int findMinDifference(List timePoints) {\n int N = timePoints.size();\n int[] minutes = new int[N];\n for(int i = 0; i < N; i++){\n int hr = Integer.parseInt(timePoints.get(i).substring(0, 2));\n int min = Integer.parseInt(timePoints.get(i).substring(3, 5));\n minutes[i] = hr * 60 + min;\n }\n Arrays.sort(minutes);\n int res = Integer.MAX_VALUE;\n for(int i = 0; i < N - 1; i++){\n res = Math.min(res, minutes[i + 1] - minutes[i]);\n }\n int b = minutes[0];\n int a = minutes[N - 1];\n return Math.min(res, (b - a + 1440) % 1440);\n }\n}", "solution_c": "class Solution {\npublic:\n int findMinDifference(vector& timePoints) {\n unordered_set st;\n for(auto &i: timePoints)\n {\n if(st.count(i)) return 0;\n st.insert(i);\n }\n int ans = INT_MAX;\n int first = -1,prev = 0; // first variable will take the diffrence of the first time stamp given in the input and 00:00\n int hour = 0, minute = 0;\n while(hour<24)\n {\n minute=0;\n while(minute < 60)\n {\n string hh = to_string(hour), mm = to_string(minute);\n if(hh.size() == 1) hh = '0' + hh;\n if(mm.size() == 1) mm = '0' + mm;\n string p = hh + \":\"+ mm;\n if(st.count(p))\n {\n if(first == -1){first = prev;}\n else\n {\n ans = min(ans,prev);\n }\n prev = 0;\n }\n prev++;\n minute++;\n }\n hour++;\n }\n ans = min(first+prev,ans);\n return ans;\n }\n};" }, { "title": "Decode String", "algo_input": "Given an encoded string, return its decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.\n\nYou may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].\n\nThe test cases are generated so that the length of the output will never exceed 105.\n\n \nExample 1:\n\nInput: s = \"3[a]2[bc]\"\nOutput: \"aaabcbc\"\n\n\nExample 2:\n\nInput: s = \"3[a2[c]]\"\nOutput: \"accaccacc\"\n\n\nExample 3:\n\nInput: s = \"2[abc]3[cd]ef\"\nOutput: \"abcabccdcdcdef\"\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 30\n\ts consists of lowercase English letters, digits, and square brackets '[]'.\n\ts is guaranteed to be a valid input.\n\tAll the integers in s are in the range [1, 300].\n\n", "solution_py": "class Solution:\n def decodeString(self, s):\n it, num, stack = 0, 0, [\"\"]\n while it < len(s):\n if s[it].isdigit():\n num = num * 10 + int(s[it])\n elif s[it] == \"[\":\n stack.append(num)\n num = 0\n stack.append(\"\")\n elif s[it] == \"]\":\n str1 = stack.pop()\n rep = stack.pop()\n str2 = stack.pop()\n stack.append(str2 + str1 * rep)\n else:\n stack[-1] += s[it] \n it += 1 \n return \"\".join(stack)", "solution_js": "var decodeString = function(s) {\n const stack = [];\n\n for (let char of s) {\n if (char === \"]\") {\n let curr = stack.pop();\n let str = '';\n while (curr !== '[') {\n str = curr+ str;\n curr = stack.pop();\n }\n let num = \"\";\n curr = stack.pop();\n while (!isNaN(curr)) {\n num = curr + num;\n curr = stack.pop();\n }\n stack.push(curr);\n for (let i=0; i bb) { // while the next beginning bracket is before the ending bracket\n bb = nbb; // update location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // update location of next beginning bracket\n }\n\n nl = 1; // reset length of n\n while (bb - nl >= 0) { // while there are characters in front of the beginning bracket\n nd = s.charAt(bb - nl); // next digit\n if (nd <= '9' && nd >= '0') { // if next digit is an integer\n n += (int)(nd - '0') * Math.pow(10, nl - 1); // update value of n\n nl++; // increment length of n\n }\n else break; // not an integer\n }\n\n insert = s.substring(bb + 1, eb); // set repeated string\n end = s.substring(eb + 1); // set remainder of string\n s = s.substring(0, bb - nl + 1); // remove everything after the digits\n\n while (n > 0) {\n s += insert; // add repeated string n times\n n--;\n }\n s += end; // add remainder of string\n\n bb = s.indexOf('['); // new location of beginning bracket\n nbb = s.indexOf('[', bb + 1); // new location of next beginning bracket\n eb = s.indexOf(']'); // new location of ending bracket\n }\n return s;\n }\n}", "solution_c": "class Solution {\npublic:\n\n string decodeString(string s) {\n stack st;\n for(int i = 0; i < s.size(); i++){\n if(s[i] != ']') {\n st.push(s[i]);\n }\n else{\n string curr_str = \"\";\n \n while(st.top() != '['){\n curr_str = st.top() + curr_str ;\n st.pop();\n }\n \n st.pop(); // for '['\n string number = \"\";\n \n // for calculating number\n \n while(!st.empty() && isdigit(st.top())){\n number = st.top() + number;\n st.pop();\n }\n int k_time = stoi(number); // convert string to number\n \n while(k_time--){\n for(int p = 0; p < curr_str.size() ; p++)\n st.push(curr_str[p]);\n }\n }\n }\n \n s = \"\";\n while(!st.empty()){\n s = st.top() + s;\n st.pop();\n }\n return s;\n \n }\n};" }, { "title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", "algo_input": "Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.\n\nReturn the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.\n\nA binary matrix is a matrix with all cells equal to 0 or 1 only.\n\nA zero matrix is a matrix with all cells equal to 0.\n\n \nExample 1:\n\nInput: mat = [[0,0],[0,1]]\nOutput: 3\nExplanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n\n\nExample 2:\n\nInput: mat = [[0]]\nOutput: 0\nExplanation: Given matrix is a zero matrix. We do not need to change it.\n\n\nExample 3:\n\nInput: mat = [[1,0,0],[1,0,0]]\nOutput: -1\nExplanation: Given matrix cannot be a zero matrix.\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 3\n\tmat[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution:\n flips = [11, 23, 38, 89, 186, 308, 200, 464, 416]\n \n def minFlips(self, mat: List[List[int]]) -> int:\n mask = self.make_mask(mat)\n check = self.make_mask([[1 for c in r] for r in mat])\n min_steps = -1\n last = 0\n for x in range(2**9):\n x = x & check\n flips = last ^ x\n last = x\n if not flips:\n continue\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n index = (i * 3 + j)\n if 1 << index & flips:\n mask ^= self.flips[index]\n if check & ~mask == check:\n steps = self.count_bits(x & check)\n if min_steps < 0 or steps < min_steps:\n min_steps = steps\n return min_steps\n \n def make_mask(self, mat):\n d = 0\n for i in range(3):\n for j in range(3):\n if i < len(mat) and j < len(mat[0]):\n d |= mat[i][j] << (i * 3 + j)\n return d\n\n def count_bits(self, x):\n count = 0\n i = 1\n while i <= x:\n count += int(bool(x & i))\n i <<= 1\n return count", "solution_js": "// Helper counts how many ones are in the matrix to start with. O(mn)\nvar countOnes = function(mat) {\n let count = 0;\n for (let r = 0; r < mat.length; r++) {\n count += mat[r].reduce((a, b) => a + b);\n }\n return count;\n}\n\n// Helper flips a cell and its neighbors. Returns updated number of ones left in matrix. O(1)\nvar flip = function(mat, r, c, numOnes) {\n const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0], [0, 0]];\n dirs.forEach(el => {\n let newR = r + el[0], newC = c + el[1];\n if (newR >= 0 && newR < mat.length && newC >= 0 && newC < mat[0].length) {\n if (mat[newR][newC] === 0) {\n mat[newR][newC] = 1;\n numOnes++;\n } else {\n mat[newR][newC] = 0;\n numOnes--;\n }\n }\n })\n return numOnes;\n}\n\n// Main function tries every possible combination of cells being flipped using backtracking. O (2^(mn))\nvar minFlips = function(mat) {\n const rows = mat.length, cols = mat[0].length;\n let minFlips = Infinity, numOnes = countOnes(mat);\n \n var backtrackFlip = function(cell, flips) {\n if (numOnes === 0) minFlips = Math.min(minFlips, flips);\n for (let newCell = cell; newCell < rows * cols; newCell++) {\n\t\t\t// Function uses a cell number instead of row / col to keep track of column flips\n\t\t\t// For example, a 2 x 2 grid has cells \"0\", \"1\", \"2\", \"3\" and the line below calculates row / col based on that number\n const r = Math.floor(newCell / cols), c = newCell % cols;\n numOnes = flip(mat, r, c, numOnes);\n backtrackFlip(newCell + 1, flips + 1);\n numOnes = flip(mat, r, c, numOnes);\n }\n }\n \n backtrackFlip(0, 0);\n return minFlips === Infinity ? -1 : minFlips;\n \n};", "solution_java": "class Solution {\n public int minFlips(int[][] mat) {\n int m = mat.length, n = mat[0].length;\n Set visited = new HashSet<>();\n Queue queue = new LinkedList<>();\n int steps = 0;\n \n int initialState = toBinary(mat);\n queue.add(initialState);\n visited.add(initialState);\n \n while (!queue.isEmpty()) {\n int size = queue.size();\n \n for (int i = 0; i < size; i++) {\n int state = queue.poll();\n if (state == 0) return steps;\n int mask = 1;\n\n for (int y = 0; y < m; y++) {\n for (int x = 0; x < n; x++) {\n int nextState = flip(state, x, y, n, m);\n if (!visited.contains(nextState)) {\n visited.add(nextState);\n queue.add(nextState);\n }\n mask = mask << 1;\n }\n }\n }\n steps++;\n }\n return -1;\n }\n \n private int toBinary(int[][] M) {\n int bin = 0;\n for (int y = 0; y < M.length; y++) {\n for (int x = 0; x < M[0].length; x++) {\n bin = (bin << 1) + M[y][x];\n }\n }\n return bin;\n }\n \n private int flip(int state, int x, int y, int n, int m) {\n int flip = 1 << ((y*n) + x);\n flip += (x > 0) ? 1 << ((y*n) + (x-1)) : 0;\n flip += (x < n-1) ? 1 << ((y*n) + (x+1)) : 0;\n flip += (y > 0) ? 1 << (((y-1)*n) + x) : 0;\n flip += (y < m-1) ? 1 << (((y+1)*n) + x) : 0;\n return state ^ flip;\n }\n}", "solution_c": "class Solution {\npublic:\n bool check(string str) {\n for(auto &i: str)\n if(i=='1')\n return false;\n return true;\n }\n int minFlips(vector>& mat) {\n int m = mat.size();\n int n = mat[0].size();\n string str = \"\";\n for(auto &i: mat) {\n for(auto &j: i)\n str+=(j+'0');\n }\n \n unordered_set st;\n queue> q;\n q.push({str,0});\n int steps = 0;\n \n while(q.size()) {\n string top = q.front().first;\n int step = q.front().second;\n if(check(top)) {\n return step;\n }\n \n q.pop();\n steps++;\n for(int i=0; i=0)\n temp[y + (x-1)*n] = !(temp[y + (x-1)*n] - '0') + '0';\n if(y+1=0)\n temp[(y-1) + (x)*n] = !(temp[(y-1) + (x)*n] - '0') + '0';\n \n // cout< List[int]:\n \n def calc(l,r,u,d):\n sc=0\n c1=c2=(l+r)//2\n expand=True\n for row in range(u,d+1):\n if c1==c2:\n sc+=grid[row][c1]\n else:\n sc+=grid[row][c1]+grid[row][c2]\n \n if c1==l:\n expand=False\n \n if expand:\n c1-=1\n c2+=1\n else:\n c1+=1\n c2-=1\n return sc\n \n \n m=len(grid)\n n=len(grid[0])\n heap=[]\n for i in range(m):\n for j in range(n):\n l=r=j\n d=i\n while l>=0 and r<=n-1 and d<=m-1:\n sc=calc(l,r,i,d)\n l-=1\n r+=1\n d+=2\n if len(heap)<3:\n if sc not in heap:\n heapq.heappush(heap,sc)\n else:\n if sc not in heap and sc>heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap,sc)\n \n heap.sort(reverse=True)\n return heap", "solution_js": "var getBiggestThree = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n\n const set = new Set();\n\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n let sum = grid[i][j];\n\n set.add(sum)\n\n let len = 1;\n let row = i;\n let col = j;\n\n while (withinBound(row + 1, col - 1)) {\n ++len;\n ++row;\n --col;\n\n traverse(i, j, row, col, sum, len, 0, \"botRight\");\n sum += grid[row][col];\n }\n }\n }\n\n let max1;\n let max2;\n let max3;\n\n for (const num of set) {\n if (max1 == null || num > max1) {\n max3 = max2;\n max2 = max1;\n max1 = num;\n }\n else if (max2 == null || num > max2) {\n max3 = max2;\n max2 = num;\n }\n else if (max3 == null || num > max3) {\n max3 = num;\n }\n }\n\n const res = [];\n\n if (max1) res[0] = max1;\n if (max2) res[1] = max2;\n if (max3) res[2] = max3;\n\n return res;\n\n function traverse(destRow, destCol, currRow, currCol, totSum, lenSize, currLen, currDir) {\n if (currRow === destRow && currCol === destCol) {\n set.add(totSum);\n return;\n }\n\n totSum += grid[currRow][currCol];\n ++currLen;\n\n if (currDir === \"botRight\") {\n if (currLen < lenSize) {\n if (!withinBound(currRow + 1, currCol + 1)) return;\n\n traverse(destRow, destCol, currRow + 1, currCol + 1, totSum, lenSize, currLen, currDir);\n }\n else if (currLen === lenSize) {\n if (!withinBound(currRow - 1, currCol + 1)) return;\n\n traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, 1, \"topRight\");\n }\n }\n else if (currDir === \"topRight\") {\n if (currLen < lenSize) {\n if (!withinBound(currRow - 1, currCol + 1)) return;\n\n traverse(destRow, destCol, currRow - 1, currCol + 1, totSum, lenSize, currLen, \"topRight\");\n }\n else if (currLen === lenSize) {\n if (!withinBound(currRow - 1, currCol - 1)) return;\n\n traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, 1, \"topLeft\");\n }\n }\n else if (currDir === \"topLeft\") {\n if (!withinBound(currRow - 1, currCol - 1)) return;\n\n traverse(destRow, destCol, currRow - 1, currCol - 1, totSum, lenSize, currLen, \"topLeft\");\n }\n }\n\n function withinBound(row, col) {\n return row >= 0 && col >= 0 && row < m && col < n;\n }\n};", "solution_java": "class Solution {\n public int[] getBiggestThree(int[][] grid) {\n int end = Math.min(grid.length, grid[0].length);\n int maxThree[] = {0,0,0};\n for(int length=0; length= length){\n addToMaxThree(maxThree, getSum(grid, start, start1, length));\n }\n }\n }\n }\n\n /*\n get sum of edges of rhombus abcd\n a\n / \\\n d b\n \\ /\n c\n\n */\n int getSum(int[][] grid, int i, int j, int length){\n if(length == 0){\n return grid[i][j];\n }\n\n int sum = 0;\n // edge ab\n for(int it=0; it<=length; it++){\n sum = sum + grid[i+it][j+it];\n }\n\n // edge ad\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+it][j-it];\n }\n\n // edge dc\n for(int it=1; it<=length; it++){\n sum = sum + grid[i+length+it][j-length+it];\n }\n\n // edge bc\n for(int it=1; it getBiggestThree(vector>& grid) {\n\n int n = grid.size(), m = grid[0].size();\n set s;\n\n // 1x1, 3x3, 5x5\n for (int len = 1; len <= min(m, n); len += 2) {\n for (int i = 0; i + len <= n; i ++) {\n for (int j = 0; j + len <= m; j ++) {\n int d = len / 2;\n if (d == 0) { s.insert(grid[i][j]); }\n else {\n int x = i, y = j + d;\n long long sum = 0;\n for (int k = 0; k < d; k ++) sum += grid[x++][y++];\n for (int k = 0; k < d; k ++) sum += grid[x++][y--];\n for (int k = 0; k < d; k ++) sum += grid[x--][y--];\n for (int k = 0; k < d; k ++) sum += grid[x--][y++];\n s.insert(sum);\n }\n }\n }\n }\n\n if (s.size() < 3)\n return vector(s.rbegin(), s.rend());\n\n return vector(s.rbegin(), next(s.rbegin(), 3));\n }\n};" }, { "title": "Minimum Absolute Sum Difference", "algo_input": "You are given two positive integer arrays nums1 and nums2, both of length n.\n\nThe absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).\n\nYou can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.\n\nReturn the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.\n\n|x| is defined as:\n\n\n\tx if x >= 0, or\n\t-x if x < 0.\n\n\n \nExample 1:\n\nInput: nums1 = [1,7,5], nums2 = [2,3,5]\nOutput: 3\nExplanation: There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\n\n\nExample 2:\n\nInput: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput: 0\nExplanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.\n\n\nExample 3:\n\nInput: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput: 20\nExplanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n\n\n \nConstraints:\n\n\n\tn == nums1.length\n\tn == nums2.length\n\t1 <= n <= 105\n\t1 <= nums1[i], nums2[i] <= 105\n\n", "solution_py": "class Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n diff = []\n sum = 0\n for i in range(n):\n temp = abs(nums1[i]-nums2[i])\n diff.append(temp)\n sum += temp\n nums1.sort()\n best_diff = []\n for i in range(n):\n idx = bisect.bisect_left(nums1, nums2[i])\n if idx != 0 and idx != n:\n best_diff.append(\n min(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n elif idx == 0:\n best_diff.append(abs(nums2[i]-nums1[idx]))\n else:\n best_diff.append(abs(nums2[i]-nums1[idx-1]))\n saved = 0\n for i in range(n):\n saved = max(saved, diff[i]-best_diff[i])\n return (sum-saved) % ((10**9)+(7))", "solution_js": "var minAbsoluteSumDiff = function(nums1, nums2) {\n const MOD = 1e9 + 7;\n const n = nums1.length;\n\n const origDiffs = [];\n let diffSum = 0;\n\n for (let i = 0; i < n; i++) {\n const num1 = nums1[i];\n const num2 = nums2[i];\n\n const currDiff = Math.abs(num1 - num2);\n\n origDiffs[i] = currDiff;\n diffSum += currDiff;\n }\n\n nums1.sort((a, b) => a - b);\n\n let minDiffSum = diffSum;\n\n for (let i = 0; i < n; i++) {\n const origDiff = origDiffs[i];\n\n const num2 = nums2[i];\n\n let left = 0;\n let right = n - 1;\n\n let bestDiff = origDiff;\n\n while (left <= right) {\n const mid = (left + right) >> 1;\n const num1 = nums1[mid];\n\n const candDiff = num1 - num2;\n\n if (Math.abs(candDiff) < bestDiff) {\n bestDiff = Math.abs(candDiff);\n if (bestDiff === 0) break;\n }\n\n if (candDiff < 0) left = mid + 1;\n else right = mid - 1;\n }\n\n const replacedDiffSum = (diffSum - origDiff) + bestDiff;\n\n minDiffSum = Math.min(minDiffSum, replacedDiffSum);\n }\n\n return minDiffSum % MOD;\n};", "solution_java": "class Solution {\n public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {\n int mod = (int)1e9+7;\n\n // Sorted copy of nums1 to use for binary search\n int[] snums1 = nums1.clone();\n Arrays.sort(snums1);\n \n int maxDiff = 0; // maximum difference between original and new absolute diff\n int pos = 0; // where the maximum difference occurs\n int newn1 = 0; // nums1 value to copy to nums1[pos]\n\n // For each array position i from 0 to n-1, find up to two elements\n // in nums1 that are closest to nums2[i] (one on each side of nums2[i]).\n // Calculate a new absolute difference for each of these elements.\n for (int i=0; i Integer.MIN_VALUE) {\n // If a valid element exists, calculate a new absolute difference\n // at the current position, and calculate how much smaller this is\n // than the current absolute difference. If the result is better\n // than what we have seen so far, update the maximum difference and\n // save the data for the current position.\n int newDiff = Math.abs(floor - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = floor;\n maxDiff = diff;\n }\n }\n \n // Find the smallest element in nums1 that is greater than or equal to\n // the current element in nums2, if such an element exists.\n int ceiling = arrayCeiling(snums1, n2);\n if (ceiling < Integer.MAX_VALUE) {\n // Same as above\n int newDiff = Math.abs(ceiling - n2);\n int diff = origDiff - newDiff;\n if (diff > maxDiff) {\n pos = i;\n newn1 = ceiling;\n maxDiff = diff;\n }\n }\n }\n\n // If we found a replacement value, overwrite the original value.\n if (newn1 > 0) {\n nums1[pos] = newn1;\n }\n \n // Calculate the absolute sum difference with the replaced value.\n int sum = 0;\n for (int i=0; i= val) {\n min = arr[mid];\n hi = mid-1;\n } else {\n lo = mid+1;\n }\n }\n \n return min;\n }\n}", "solution_c": "class Solution {\npublic:\n int minAbsoluteSumDiff(vector& nums1, vector& nums2) {\n long sum=0, minSum;\n vector nums=nums1;\n int n=nums.size();\n\t // Calculate the current sum of differences.\n for(int i=0;inums2[i]) {\n h=m;\n } else {\n l=m+1;\n }\n dist=min(dist, abs(nums2[i]-nums[m]));\n }\n dist=min(dist, abs(nums2[i]-nums[l]));\n minSum = min(minSum, sum - abs(nums1[i]-nums2[i]) + dist);\n }\n \n return minSum % 1000000007;\n }\n};" }, { "title": "Permutation Sequence", "algo_input": "The set [1, 2, 3, ..., n] contains a total of n! unique permutations.\n\nBy listing and labeling all of the permutations in order, we get the following sequence for n = 3:\n\n\n\t\"123\"\n\t\"132\"\n\t\"213\"\n\t\"231\"\n\t\"312\"\n\t\"321\"\n\n\nGiven n and k, return the kth permutation sequence.\n\n \nExample 1:\nInput: n = 3, k = 3\nOutput: \"213\"\nExample 2:\nInput: n = 4, k = 9\nOutput: \"2314\"\nExample 3:\nInput: n = 3, k = 1\nOutput: \"123\"\n\n \nConstraints:\n\n\n\t1 <= n <= 9\n\t1 <= k <= n!\n\n", "solution_py": " class Solution:\n def nextPermutation(self, nums: List[int]):\n n = len(nums)\n high = n-1\n low = -1\n for i in range(n-1, 0, -1):\n if nums[i] > nums[i-1]:\n low = i-1\n break\n if low == -1:\n nums[low+1:] = reversed(nums[low+1:])\n return\n for i in range(n-1, low, -1):\n if nums[low] < nums[i]:\n nums[low], nums[i] = nums[i], nums[low]\n break\n nums[low+1:] = reversed(nums[low+1:])\n return nums\n\n def getPermutation(self, n: int, k: int) -> str:\n s = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"]\n s = s[:n]\n if k==1:\n return ''.join(s)\n dic = {1:1,2:2,3:6,4:24,5:120,6:720,7:5040,8:40320,9:362880} \n if k==dic[n]:\n return ''.join(s)[::-1]\n x = 0\n while k>dic[n-1]:\n k -= dic[n-1]\n x += 1\n y=[]\n y.append(s[x])\n for i in range(n):\n if i==x:\n continue\n y.append(s[i])\n while k!=1:\n self.nextPermutation(y)\n k-= 1\n y = ''.join(y)\n return y", "solution_js": "const dfs = (path, visited, result, numbers, limit) => {\n // return if we already reached the permutation needed\n if(result.length === limit) {\n return;\n }\n \n // commit the result\n if(path.length === numbers.length) {\n result.push(path.join(''))\n return;\n }\n \n // easier to reason and less prone to miss the -1 offset of normal for loop\n for(const [index, number] of numbers.entries()) {\n if(visited[index]) continue;\n \n path.push(number);\n visited[index] = true;\n dfs(path, visited, result, numbers);\n path.pop();\n visited[index] = false;\n }\n}\n\nvar getPermutation = function(n, k) {\n const numbers = Array.from({length: n}, (_, i) => i + 1);\n let visitedNumbers = Array.from(numbers, () => false);\n let result = [];\n dfs([], visitedNumbers, result, numbers, k);\n return result[k - 1];\n};", "solution_java": "class Solution {\n public String getPermutation(int n, int k) {\n int fact = 1;\n List nums = new ArrayList<>();\n for(int i = 1; i numbers;\n for(int i=1;i Optional[TreeNode]:\n arr = []\n while head:\n arr.append(head.val)\n head = head.next\n def dfs(left, right):\n if left > right: return\n m = (left + right)//2\n return TreeNode(arr[m], dfs(left, m-1), dfs(m+1, right))\n return dfs(0, len(arr)-1)", "solution_js": "var sortedListToBST = function(head) {\n if(!head) return null;\n if(!head.next) return new TreeNode(head.val);\n \n let fast = head, slow = head, prev = head;\n while(fast && fast.next) {\n prev = slow;\n slow = slow.next;\n fast = fast.next.next;\n }\n \n const root = new TreeNode(slow.val);\n prev.next = null;\n \n const newHead = slow.next;\n slow.next = null;\n \n root.left = sortedListToBST(head);\n root.right = sortedListToBST(newHead);\n \n return root;\n};", "solution_java": "class Solution {\n \n public TreeNode sortedListToBST(ListNode head) {\n \n ListNode tmp = head;\n ArrayList treelist = new ArrayList<>();\n \n while(tmp != null) {\n treelist.add(tmp.val);\n tmp = tmp.next;\n }\n \n return createTree(treelist, 0, treelist.size()-1);\n }\n \n public TreeNode createTree(ArrayList treelist, int start, int end) {\n \n if(start > end)\n return null;\n \n int mid = start + (end-start)/2;\n \n TreeNode node = new TreeNode(treelist.get(mid));//getNode(treelist.get(mid));\n \n node.left = createTree(treelist, start, mid-1);\n node.right = createTree(treelist, mid+1, end);\n return node;\n }\n}", "solution_c": "class Solution {\npublic:\n typedef vector::iterator vecIt;\n TreeNode* buildTree(vector& listToVec, vecIt start, vecIt end)\n {\n if (start >= end)\n return NULL;\n vecIt midIt = start + (end - start) / 2;\n TreeNode* newNode = new TreeNode(*midIt);\n newNode->left = buildTree(listToVec, start, midIt);\n newNode->right = buildTree(listToVec, midIt + 1, end);\n return (newNode);\n }\n TreeNode* sortedListToBST(ListNode* head) {\n vector listToVec;\n while (head)\n {\n listToVec.push_back(head->val);\n head = head->next;\n }\n return (buildTree(listToVec, listToVec.begin(), listToVec.end()));\n }\n};" }, { "title": "Minimum Size Subarray Sum", "algo_input": "Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.\n\n \nExample 1:\n\nInput: target = 7, nums = [2,3,1,2,4,3]\nOutput: 2\nExplanation: The subarray [4,3] has the minimal length under the problem constraint.\n\n\nExample 2:\n\nInput: target = 4, nums = [1,4,4]\nOutput: 1\n\n\nExample 3:\n\nInput: target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= target <= 109\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 104\n\n\n \nFollow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).", "solution_py": "class Solution:\n def minSubArrayLen(self, target, nums):\n\t\t# Init left pointer and answer\n l, ans = 0, len(nums) + 1\n\t\t# Init sum of subarray\n s = 0 \n\t\t# Iterate through all numbers as right subarray \n for r in range(len(nums)):\n\t\t\t# Add right number to sum\n s += nums[r]\n\t\t\t# Check for subarray greater than or equal to target\n while s >= target:\n\t\t\t\t# Calculate new min\n ans = min(ans, r - l + 1)\n\t\t\t\t# Remove current left nubmer from sum\n s -= nums[l]\n\t\t\t\t# Move left index up one\n l += 1\n\t\t# No solution\n if ans == len(nums) + 1:\n return 0\n\t\t# Solution\n return ans ", "solution_js": "/**\n * @param {number} target\n * @param {number[]} nums\n * @return {number}\n */\nvar minSubArrayLen = function(target, nums) {\n let indexStartPosition = 0;\n let sum = 0;\n let tempcounter = 0;\n let counter = Infinity;\n\n for(var indexI=0; indexI= target) {\n sum = sum - nums[indexStartPosition];\n indexStartPosition = indexStartPosition + 1;\n counter = Math.min(counter, tempcounter);\n tempcounter--;\n }\n\n }\n\n return counter === Infinity ? 0 : counter;\n};", "solution_java": "class Solution {\n public int minSubArrayLen(int target, int[] nums) {\n int left = 0;\n int n = nums.length;\n int sum = 0;\n int minCount = Integer.MAX_VALUE;\n for(int i = 0;i= target){\n minCount = Math.min(minCount, i-left+1);\n sum -= nums[left++];\n } \n }\n return minCount == Integer.MAX_VALUE?0:minCount;\n }\n}", "solution_c": "class Solution {\npublic:\n int minSubArrayLen(int target, vector& nums) {\n int m=INT_MAX,s=0,l=0;\n for(int i=0;i=target)\n m=min(m,i-l+1);\n while(s>=target)\n {\n m=min(m,i-l+1);\n s-=nums[l++];\n }\n }\n if(m==INT_MAX)\n m=0;\n return m;\n }\n};" }, { "title": "Wiggle Subsequence", "algo_input": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.\n\n\n\tFor example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.\n\tIn contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.\n\n\nA subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.\n\nGiven an integer array nums, return the length of the longest wiggle subsequence of nums.\n\n \nExample 1:\n\nInput: nums = [1,7,4,9,2,5]\nOutput: 6\nExplanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n\n\nExample 2:\n\nInput: nums = [1,17,5,10,13,15,10,5,16,8]\nOutput: 7\nExplanation: There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,6,7,8,9]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t0 <= nums[i] <= 1000\n\n\n \nFollow up: Could you solve this in O(n) time?\n", "solution_py": "#####################################################################################################################\n# Problem: Wiggle Subsequence\n# Solution : Dynamic Programming\n# Time Complexity : O(n) \n# Space Complexity : O(1)\n#####################################################################################################################\n\nclass Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n \n positive, negative = 1, 1\n \n if len(nums) < 2:\n return len(nums)\n \n for i in range(1, len(nums)):\n if nums[i] > nums[i - 1]:\n positive = negative + 1\n elif nums[i] < nums[i - 1]:\n negative = positive + 1\n \n return max(positive, negative)", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar wiggleMaxLength = function(nums) {\n //two pass\n //assume we start with positive or start with negative\n //choose the longest of the two\n return Math.max(helper(nums,true),helper(nums,false))\n};\n\nconst helper = (nums, start) =>{\n let l = 0\n let r = 1\n let res = nums.length\n let sign = start\n while(r < nums.length){\n //if sign are what we expected, just flip the sign\n if((sign && nums[r] > nums[l]) || (!sign && nums[r] < nums[l])){\n sign = !sign\n }\n //if sign aren't what we expected then we \"remove\" one\n //if we want positive then we remove the bigger number to give us a better chance of getting positive\n //if we want negative we remove the smaller number go give us a chance of getting a negative\n // want negative but nums[r] - nums[l] = positive => remove nums[l] \n // want positive but nums[r] - nums[l] = negative => remove nums[l]\n //it just so happens that the number we want to remove will always be nums[l], so we don't have to do anything special\n else{\n res--\n }\n l++\n r++\n }\n return res\n}", "solution_java": "class Solution {\n int n;\n int dp[][][];\n public int wiggleMaxLength(int[] nums) {\n n = nums.length;\n dp = new int[n][1005][2];\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int pos = f(0 , 0 , nums , -1);\n for(int i = 0; i < n; i++){\n for(int j = 0; j < 1005; j++){\n Arrays.fill(dp[i][j] , -1);\n }\n }\n int neg = f(0 , 1 , nums , 1001);\n return Math.max(pos , neg);\n }\n int f(int i , int posPre , int a[] , int prev){\n if(i == n) return 0;\n if(dp[i][prev + 1][posPre] != -1) return dp[i][prev + 1][posPre];\n if(posPre == 0){\n int not = f(i + 1 , 0 , a , prev);\n int take = 0;\n if(a[i] - prev > 0){\n take = f(i + 1 , 1 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n else{\n int not = f(i + 1 , 1 , a , prev);\n int take = 0;\n if(a[i] - prev < 0){\n take = f(i + 1 , 0 , a , a[i]) + 1;\n }\n return dp[i][prev + 1][posPre] = Math.max(not , take);\n }\n }\n}", "solution_c": "class Solution {\npublic:\n int wiggleMaxLength(vector& nums) {\n vector> dp(2, vector(nums.size(),0));\n int ans = 1, high, low;\n dp[0][0] = dp[1][0] = 1;\n for(int i=1; inums[j]) low = max(low, dp[1][j]);\n else if(nums[i] int:\n nums=sorted(nums,reverse=True)\n l=len(nums)\n for i in range(l-2):\n if nums[i]a-b);\n const result=[];\n \n for(let i=0;isorted[i+2])&&(sorted[i+2]+sorted[i+1]>sorted[i])&&(sorted[i]+sorted[i+2]>sorted[i+1])){\n \n result.push(sorted[i]+sorted[i+1]+sorted[i+2]);\n \n }\n }\n if(result.length!==0){\n \n return Math.max(...result); \n \n }else{\n \n return 0;\n \n }\n};", "solution_java": "class Solution {\n public int largestPerimeter(int[] nums) {\n Arrays.sort(nums);\n\n for(int i = nums.length - 3; i >= 0; i--) {\n if(nums[i] + nums[i + 1] > nums[i + 2])\n return nums[i] + nums[i + 1] + nums[i + 2];\n }\n return 0;\n }\n}", "solution_c": "class Solution {\npublic:\n int largestPerimeter(vector& nums) {\n\t// sort the elements \n sort(nums.begin(),nums.end());\n\t\t// iterate in everse order to get maximum perimeter\n for (int i=nums.size()-2; i>=1 ; i--){\n\t\t//Triangle is formed if sum of two sides is greater than third side\n if (nums[i]+nums[i-1] >nums[i+1])return (nums[i]+nums[i+1]+nums[i-1]); // return perimeter which is sum of three sides\n }\n return 0; // when no triangle possible it will come out of loop so return 0 here\n \n }\n};" }, { "title": "Check if All A's Appears Before All B's", "algo_input": "Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.\n\n \nExample 1:\n\nInput: s = \"aaabbb\"\nOutput: true\nExplanation:\nThe 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.\n\n\nExample 2:\n\nInput: s = \"abab\"\nOutput: false\nExplanation:\nThere is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.\n\n\nExample 3:\n\nInput: s = \"bbb\"\nOutput: true\nExplanation:\nThere are no 'a's, hence, every 'a' appears before every 'b' and we return true.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts[i] is either 'a' or 'b'.\n\n", "solution_py": "class Solution:\n def checkString(self, s: str) -> bool:\n if \"ba\" in s:\n return False\n else:\n return True", "solution_js": "var checkString = function(s) {\n \n // a cannot come after b\n let violation = \"ba\";\n \n return s.indexOf(violation, 0) == -1;\n};", "solution_java": "class Solution {\n public boolean checkString(String s) {\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == 'b'){\n for(int j = i+1; j < s.length(); j++){\n if(s.charAt(j) == 'a'){\n return false;\n }\n }\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool checkString(string s) {\n\t\tfor(int i = 1; i < s.size(); i++){\n\t\t\tif(s[i - 1] == 'b' && s[i] == 'a'){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};" }, { "title": "Validate Binary Search Tree", "algo_input": "Given the root of a binary tree, determine if it is a valid binary search tree (BST).\n\nA valid BST is defined as follows:\n\n\n\tThe left subtree of a node contains only nodes with keys less than the node's key.\n\tThe right subtree of a node contains only nodes with keys greater than 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 = [2,1,3]\nOutput: true\n\n\nExample 2:\n\nInput: root = [5,1,4,null,null,3,6]\nOutput: false\nExplanation: The root node's value is 5 but its right child's value is 4.\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-231 <= Node.val <= 231 - 1\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 isValidBST(self, root: Optional[TreeNode]) -> bool:\n\n def valid(node,left,right):\n if not node: # checking node is none\n return True\n if not (node.val>left and node.val 0) {\n const {node: currentNode, lowerLimit, upperLimit} = nodesToCheck.pop()\n \n if (currentNode.val <= lowerLimit || currentNode.val >= upperLimit) {\n return false\n }\n \n if (currentNode.left) {\n nodesToCheck.push({\n node: currentNode.left,\n lowerLimit,\n upperLimit: currentNode.val\n })\n }\n \n if (currentNode.right) {\n nodesToCheck.push({\n node: currentNode.right,\n lowerLimit: currentNode.val,\n upperLimit\n })\n }\n }\n \n return true\n};", "solution_java": "class Solution {\n public boolean isValidBST(TreeNode root) {\n return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);\n }\n \n public boolean dfs(TreeNode root, int min, int max) {\n if (root.val < min || root.val > max || (root.val == Integer.MIN_VALUE && root.left != null) || (root.val == Integer.MAX_VALUE && root.right != null)) return false;\n boolean leftRight = true;\n if (root.left == null && root.right == null) return true;\n if (root.left != null) {\n leftRight = dfs(root.left, min, root.val - 1);\n }\n if (root.right != null) {\n leftRight = dfs(root.right, root.val + 1, max) && leftRight;\n }\n return leftRight;\n }\n}", "solution_c": "// We know inorder traversal of BST is always sorted, so we are just finding inorder traversal and check whether it is in sorted manner or not, but only using const space using prev pointer.\nclass Solution {\npublic:\n TreeNode* prev;\n Solution(){\n prev = NULL;\n }\n bool isValidBST(TreeNode* root) {\n if (root == NULL)\n return true;\n bool a = isValidBST(root->left);\n if (!a)\n return false;\n if (prev != NULL)\n {\n if (prev->val >= root->val)\n return false;\n }\n prev = root;\n return isValidBST(root->right);\n }\n};" }, { "title": "Basic Calculator II", "algo_input": "Given a string s which represents an expression, evaluate this expression and return its value. \n\nThe integer division should truncate toward zero.\n\nYou may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].\n\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n\n \nExample 1:\nInput: s = \"3+2*2\"\nOutput: 7\nExample 2:\nInput: s = \" 3/2 \"\nOutput: 1\nExample 3:\nInput: s = \" 3+5 / 2 \"\nOutput: 5\n\n \nConstraints:\n\n\n\t1 <= s.length <= 3 * 105\n\ts consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.\n\ts represents a valid expression.\n\tAll the integers in the expression are non-negative integers in the range [0, 231 - 1].\n\tThe answer is guaranteed to fit in a 32-bit integer.\n\n", "solution_py": "class Solution:\n def calculate(self, s: str) -> int:\n stack = []\n currentNumber = 0\n operator = '+'\n operations = '+-/*'\n for i in range(len(s)):\n ch = s[i]\n if ch.isdigit():\n currentNumber = currentNumber * 10 + int(ch)\n\n if ch in operations or i == len(s) - 1:\n if operator == '+':\n stack.append(currentNumber)\n\n elif operator == '-':\n stack.append(-currentNumber)\n\n elif operator == '*':\n stack.append(stack.pop() * currentNumber)\n\n elif operator == '/':\n stack.append(int(stack.pop()/currentNumber))\n\n currentNumber =0\n operator = ch\n\n return sum(stack)", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar calculate = function(s) {\n const n = s.length;\n let currNum = 0, lastNum = 0, res = 0;\n let op = '+';\n \n for (let i = 0; i < n; i++) {\n let currChar = s[i];\n \n if (currChar !== \" \" && !isNaN(Number(currChar))) {\n currNum = currNum * 10 + Number(currChar);\n }\n \n if (isNaN(Number(currChar)) && currChar !== \" \" || i === n - 1) {\n if (op === '+' || op === '-') {\n res += lastNum;\n lastNum = (op === '+' ? currNum : -currNum);\n } else if (op === '*') {\n lastNum *= currNum;\n } else if (op === '/') {\n lastNum = Math.floor(Math.abs(lastNum) / currNum) * (lastNum < 0 ? -1 : 1);\n }\n \n op = currChar;\n currNum = 0;\n }\n }\n \n res += lastNum;\n return res;\n};", "solution_java": "class Solution {\n public int calculate(String s) {\n if(s==null ||s.length()==0)return 0;\n Stack st = new Stack<>();\n int curr=0;\n char op = '+';\n char [] ch = s.toCharArray();\n for(int i=0;i nums;\n stack ops;\n int n = 0;\n for(int i = 0; i < s.size(); ++i){\n if(s[i] >= '0' && s[i] <= '9'){\n string t(1, s[i]);\n n = n*10 + stoi(t);\n }else if( s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/'){\n nums.push(n);\n n = 0;\n if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){\n int n2 = nums.top(); nums.pop();\n int n1 = nums.top(); nums.pop();\n if(ops.top() == '*') nums.push(n1*n2);\n else nums.push(n1/n2);\n ops.pop();\n }\n ops.push(s[i]);\n }\n }\n nums.push(n);\n if(!ops.empty() && (ops.top() == '*' || ops.top() == '/') ){\n int n2 = nums.top(); nums.pop();\n int n1 = nums.top(); nums.pop();\n if(ops.top() == '*') nums.push(n1*n2);\n else nums.push(n1/n2);\n ops.pop();\n }\n stack tnums;\n stack tops;\n while(!nums.empty()){ tnums.push(nums.top()); nums.pop();}\n while(!ops.empty()) { tops.push(ops.top()); ops.pop(); }\n \n while(!tops.empty()){ //cout< {\n if (node) {\n res.push(node.val);\n\n for (let i = 0; i < node.children.length; i++) {\n getNodeVal(node.children[i]);\n }\n }\n };\n\n getNodeVal(root);\n\n return res;\n}", "solution_js": "var preorder = function(root) {\n return [root.val].concat(root.children.map( (c)=>c ? preorder(c) : [] ).flat() );\n};", "solution_java": "class Solution {\n public List preorder(Node root) {\n if (root == null) return new ArrayList();\n \n Stack stk = new Stack();\n ArrayList arr = new ArrayList();\n stk.push(root);\n Node ref;\n while(!stk.empty()) {\n ref = stk.pop();\n // System.out.println(ref.val);\n arr.add(ref.val);\n for(int i=ref.children.size() - 1;i>=0;i--) {\n stk.push(ref.children.get(i));\n }\n }\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector preorder(Node* root) {\n vectorans;\n stackst;\n st.push(root);\n while(!st.empty()){\n auto frnt=st.top();\n st.pop();\n ans.push_back(frnt->val);\n for(int i=frnt->children.size()-1;i>=0;i--){\n st.push(frnt->children[i]);\n }\n }\n return ans;\n }\n};" }, { "title": "Minimum Height Trees", "algo_input": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.\n\nGiven a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h))  are called minimum height trees (MHTs).\n\nReturn a list of all MHTs' root labels. You can return the answer in any order.\n\nThe height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.\n\n \nExample 1:\n\nInput: n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput: [1]\nExplanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\n\n\nExample 2:\n\nInput: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput: [3,4]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 2 * 104\n\tedges.length == n - 1\n\t0 <= ai, bi < n\n\tai != bi\n\tAll the pairs (ai, bi) are distinct.\n\tThe given input is guaranteed to be a tree and there will be no repeated edges.\n\n", "solution_py": "class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n==0:\n return []\n if n==1:return [0]\n adj=[[] for i in range (n)]\n degree=[0]*n\n for i in edges:\n adj[i[0]].append(i[1])\n adj[i[1]].append(i[0])\n degree[i[0]]+=1\n degree[i[1]]+=1\n \n print(adj)\n q=[]\n for i in range(n):\n if degree[i]==1:\n q.append(i)\n \n while n>2:\n size=len(q)\n n-=size\n while size>0:\n v=q.pop(0)\n for i in adj[v]:\n degree[i]-=1\n if degree[i]==1:\n q.append(i)\n size-=1\n return q\n \n \n ", "solution_js": "var findMinHeightTrees = function(n, edges) {\n \n //edge case\n if(n <=0) return [];\n if(n === 1) return [0]\n \n \n let graph ={}\n let indegree = Array(n).fill(0)\n let leaves = []\n // build graph\n \n for(let [v,e] of edges){\n //as this is undirected graph we will build indegree for both e and v\n if(!(v in graph)) graph[v] = [];\n if(!(e in graph)) graph[e] = [];\n graph[v].push(e)\n graph[e].push(v)\n indegree[v]++\n indegree[e]++\n }\n \n \n // get all nodes with indegree 1\n for(let i =0; i 2){\n let size = leaves.length\n // as we are removing nodes from our total\n total -= size;\n \n for(let i =0 ; i findMinHeightTrees(int n, int[][] edges) {\n if(edges.length == 0) {\n List al = new ArrayList<>();\n al.add(0);\n return al;\n }\n HashMap> map = new HashMap<>(); // map == graph\n int [] degree = new int[n];\n for(int [] edge : edges){\n int src = edge[0];\n int dest = edge[1];\n map.putIfAbsent(src, new HashSet<>());\n map.get(src).add(dest);\n map.putIfAbsent(dest, new HashSet<>());\n map.get(dest).add(src);\n degree[src]++;\n degree[dest]++;\n }\n Queue q = new ArrayDeque<>();\n for(int i = 0; i < degree.length; i++){\n if(degree[i] == 1){\n q.offer(i);\n }\n }\n int count = n;\n while(count > 2){\n int size = q.size();\n count -= size;\n while(size-- > 0){\n Integer src = q.poll();\n\n for(Integer connection : map.get(src)){\n degree[connection]--;\n if(degree[connection] == 1){\n q.offer(connection);\n }\n }\n }\n }\n return new ArrayList<>(q);\n }\n}", "solution_c": "class Solution {\npublic:\n int getheight(vector a[],int sv,int n)\n {\n int lvl = 0;\n vector vis(n,0);\n queue q;\n q.push(sv);\n vis[sv] = 0;\n while(q.size())\n {\n int sz = q.size();\n lvl++;\n while(sz--)\n {\n int curr = q.front();\n q.pop();\n vis[curr] = 1;\n \n for(auto it:a[curr])\n {\n if(vis[it]==0)\n {\n q.push(it);\n }\n }\n }\n }\n return lvl;\n }\n vector findMinHeightTrees(int n, vector>& edges) {\n vector a[n];\n vector indegree(n,0);\n for(auto it:edges)\n {\n a[it[0]].push_back(it[1]);\n a[it[1]].push_back(it[0]);\n indegree[it[0]]++;\n indegree[it[1]]++;\n }\n \n //cutting leafs whose indegree is 1\n queue q;\n vector ans;\n for(int i = 0;i> mp;\n// for(int i = 0;i int:\n import numpy as np\n \n matrix = np.array(matrix, dtype=np.int32)\n \n M,N = matrix.shape\n \n ret = float(\"-inf\")\n \n CUM = np.zeros((M,N), dtype=np.int32)\n for shift_r in range(M):\n CUM[:M-shift_r] += matrix[shift_r:]\n \n _CUM = np.zeros((M-shift_r,N), dtype=np.int32)\n for shift_c in range(N):\n _CUM[:, :N-shift_c] += CUM[:M-shift_r,shift_c:]\n tmp = _CUM[(_CUM<=k) & (_CUM>ret)]\n if tmp.size:\n ret = tmp.max()\n if ret == k:\n return ret\n \n return ret\n\n'''", "solution_js": "/**\n * @param {number[][]} matrix\n * @param {number} k\n * @return {number}\n */\nvar maxSumSubmatrix = function(matrix, k) {\n if (!matrix.length) return 0;\n\n let n = matrix.length, m = matrix[0].length;\n let sum = new Array(n + 1).fill(0).map(a => new Array(m + 1).fill(0));\n let ans = -Infinity;\n\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n sum[i][j] = matrix[i-1][j-1] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1];\n for(let x = 1; x <= i; ++x) {\n for(let y = 1; y <= j; ++y) {\n let s = rangeSum(sum, x, y, i, j);\n if (s <= k) {\n ans = Math.max(s, ans);\n }\n }\n }\n }\n }\n return ans;\n}\n\nconst rangeSum = (sum, x1, y1, x2, y2) => {\n return sum[x2][y2] - sum[x1-1][y2] - sum[x2][y1-1] + sum[x1-1][y1-1];\n}", "solution_java": "class Solution {\n public int maxSumSubmatrix(int[][] matrix, int tar) {\n int n=matrix.length,m=matrix[0].length,i,j,k,l,dp[][] = new int[n][m],val,max=Integer.MIN_VALUE,target=tar;\n for(i=0;i0) dp[i][j]+=dp[i][j-1];\n }\n }\n for(i=0;i0) dp[i][j]+=dp[i-1][j];\n }\n }\n for(i=0;i=0 && (j-1)>=0) val += dp[i-1][j-1];\n if((i-1)>=0) val=val-dp[i-1][l];\n if((j-1)>=0) val=val-dp[k][j-1];\n if(val>max && val<=target) max=val;\n }\n }\n }\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n\n // function for finding maximum subarray having sum less than k\n\n int find_max(vector& arr, int k)\n {\n int n = arr.size();\n\n int maxi = INT_MIN;\n\n // curr_sum will store cumulative sum\n\n int curr_sum = 0;\n\n // set will store the prefix sum of array\n\n set s;\n\n // put 0 into set, if curr_sum == k, (curr_sum - k) will be zero\n\n s.insert(0);\n\n for(int i = 0; i < n; i++)\n {\n // calculate cumulative sum\n\n curr_sum += arr[i];\n\n // find the prefix sum in set having sum == curr_sum - k\n\n auto it = s.lower_bound(curr_sum - k);\n\n // if prefix sum is present, update the maxi\n\n if(it != s.end())\n {\n maxi = max(maxi, curr_sum - *it);\n }\n\n // insert prefix sum into set\n\n s.insert(curr_sum);\n }\n\n return maxi;\n }\n\n int maxSumSubmatrix(vector>& matrix, int k) {\n\n int n = matrix.size();\n\n int m = matrix[0].size();\n\n int maxi = INT_MIN;\n\n // fix the position two two rows and take cumulative sum of columns between two fixed rows\n\n for(int start_row = 0; start_row < n; start_row++)\n {\n vector col_array(m, 0);\n\n for(int end_row = start_row; end_row < n; end_row++)\n {\n // take cumulative sum of columns between two fixed rows\n\n for(int col = 0; col < m; col++)\n {\n col_array[col] += matrix[end_row][col];\n }\n\n // find maximum subarray having sum less than equal to k\n\n int curr_max = find_max(col_array, k);\n\n // update the maximum sum\n\n maxi = max(maxi, curr_max);\n }\n }\n\n return maxi;\n }\n};" }, { "title": "Minimum Number of Flips to Make the Binary String Alternating", "algo_input": "You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:\n\n\n\tType-1: Remove the character at the start of the string s and append it to the end of the string.\n\tType-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.\n\n\nReturn the minimum number of type-2 operations you need to perform such that s becomes alternating.\n\nThe string is called alternating if no two adjacent characters are equal.\n\n\n\tFor example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n\n\n \nExample 1:\n\nInput: s = \"111000\"\nOutput: 2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".\n\n\nExample 2:\n\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating.\n\n\nExample 3:\n\nInput: s = \"1110\"\nOutput: 1\nExplanation: Use the second operation on the second element to make s = \"1010\".\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 minFlips(self, s: str) -> int:\n prev = 0\n start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n odd = len(s)%2\n for val in s:\n val = int(val)\n if val == prev:\n if odd:\n start_0_odd = min(start_0_odd, start_1)\n start_1_odd += 1\n start_1 += 1\n else:\n if odd:\n start_1_odd = min(start_1_odd, start_0)\n start_0_odd += 1\n start_0 += 1\n prev = 1 - prev\n return min([start_1, start_0, start_1_odd, start_0_odd])", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minFlips = function(s) {\n let length = s.length-1\n let flipMap = {\n '1': '0',\n '0': '1'\n }\n s = s + s\n let alt1 = '1'\n let alt2 = '0'\n let left = 0\n let right = 0\n let diff1 = 0\n let diff2 = 0\n let min = Infinity\n\n while (right < s.length) {\n if (right > 0) {\n alt1 = flipMap[alt1]\n alt2 = flipMap[alt2]\n }\n\n let current = s[right]\n if (current !== alt1) diff1++\n if (current !== alt2) diff2++\n if (right-left === length) {\n min = Math.min(diff1, diff2, min)\n if ((length+1)%2 === 0) {\n if (s[left] !== flipMap[alt1]) diff1--\n if (s[left] !== flipMap[alt2]) diff2--\n } else {\n if (s[left] !== alt1) diff1--\n if (s[left] !== alt2) diff2--\n }\n left++\n }\n right++\n }\n return min\n};", "solution_java": "class Solution {\n public int minFlips(String s) {\n /*\n * Sliding Window Approach\n */\n \n \n int n = s.length();\n \n int mininumFlip = Integer.MAX_VALUE;\n \n int misMatchCount = 0;\n for(int i = 0; i < (2 * n); i++){\n \n int r = i % n;\n \n //add mis watch count in current window\n if((s.charAt(r) - '0') != (i % 2 == 0 ? 1 : 0)) misMatchCount++;\n \n //remove mismatch count which are not relvent for current window\n if(i >= n && (s.charAt(r) - '0') != (r % 2 == 0 ? 1 : 0)) misMatchCount--;\n \n \n //misMatchCount : when valid binary string start from 1\n //n - misMatchCount : when valid binary string start from 0\n if(i >= n - 1) mininumFlip = Math.min(mininumFlip, Math.min(misMatchCount, n - misMatchCount));\n }\n \n return mininumFlip;\n }\n}", "solution_c": "class Solution {\npublic:\n int minFlips(string s)\n {\n int n = s.size();\n string ss = s+s;\n string s1, s2;\n int ans = INT_MAX;\n for(int i=0; i=n-1)\n {\n if(i!=n-1 && s1[i-n]!=ss[i-n]) ans1--;\n if(i!=n-1 && s2[i-n]!=ss[i-n]) ans2--;\n ans = min({ans,ans1,ans2});\n }\n }\n return ans;\n }\n};" }, { "title": "Range Sum of Sorted Subarray Sums", "algo_input": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.\n\nReturn the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput: 13 \nExplanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. \n\n\nExample 2:\n\nInput: nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput: 6\nExplanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput: 50\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 100\n\t1 <= left <= right <= n * (n + 1) / 2\n\n", "solution_py": "from itertools import accumulate\n\nclass Solution:\n def rangeSum(self, nums, n, left, right):\n acc = []\n\n for i in range(n):\n acc.extend(accumulate(nums[i:]))\n\n acc.sort()\n\n return sum(acc[left - 1:right]) % (10**9 + 7)", "solution_js": "var rangeSum = function(nums, n, left, right) {\n const sums = [];\n \n for (let i = 0; i < nums.length; i++) {\n let sum = 0;\n \n for (let j = i; j < nums.length; j++) {\n sum += nums[j];\n sums.push(sum);\n }\n }\n \n sums.sort((a, b) => a - b);\n \n let ans = 0;\n \n for (let i = left - 1; i < right; i++) {\n ans += sums[i];\n }\n \n return ans % 1000000007;\n};", "solution_java": "class Solution {\n private static int mod=(int)1e9+7;\n public int rangeSum(int[] nums, int n, int left, int right) {\n \n PriorityQueue pq=new PriorityQueue<>((n1,n2)->n1[1]-n2[1]);\n \n for(int i=0;i=left){\n ans=(ans+k[1])%mod;\n }\n if(k[0]+1& nums, int n, int left, int right) \n {\n const int m= 1e9+7; // To return ans % m\n int ans=0; // Final Answer\n int k=1; // For 1 based indexing\n int size= (n*(n+1))/2; // We can form n(n+1)/2 subarrays for an array of size n\n vector subsum(size+1); \n for(int i=0;i List[str]:\n \n \n hashmap1 = {}\n hashmap2 = {}\n common = {}\n for i in range(len(list1)):\n \n hashmap1[list1[i]] = i \n \n \n for j in range(len(list2)):\n hashmap2[list2[j]] = j \n \n \n \n for i in hashmap1:\n \n if i in hashmap2:\n print(1)\n common[i] = hashmap1[i] + hashmap2[i]\n \n \n common = list(common.items())\n \n answer =[]\n minimum = float(\"inf\")\n \n for i in range(0,len(common)):\n \n if common[i][1] < minimum:\n minimum = common[i][1]\n \n for i in range(len(common)):\n \n if common[i][1] == minimum:\n answer.append(common[i][0])\n \n return answer\n \n \n ", "solution_js": "var findRestaurant = function(list1, list2) {\n let obj ={}\n for(let i =0; i l1 = Arrays.asList(list1);\n int least = Integer.MAX_VALUE;\n List returnArray = new ArrayList<>();\n Map map = new HashMap<>();\n\n for (int i = 0; i < list2.length; i++) {\n if (l1.contains(list2[i])) {\n map.put(list2[i], l1.indexOf(list2[i]) + i);\n }\n }\n for (Map.Entry entry: map.entrySet()){ \n if (entry.getValue() <= least) least = entry.getValue();\n }\n for (Map.Entry entry: map.entrySet()){ \n if (entry.getValue() == least) returnArray.add(entry.getKey());\n }\n \n if (returnArray.size() > 1) return returnArray.toArray(String[]::new);\n return new String[]{returnArray.get(0)};\n }\n}", "solution_c": "class Solution {\npublic:\n vector findRestaurant(vector& list1, vector& list2) {\n vectorvc;\n unordered_mapumap,umap1;\n \n for(int i=0;ik)\n {vc.clear();\n min=k;\n vc.push_back(j.first);\n }\n else if(k==min)\n {\n vc.push_back(j.first);\n }\n \n }\n }\n}\n \n \n return vc;\n}\n};" }, { "title": "Closest Divisors", "algo_input": "Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.\n\nReturn the two integers in any order.\n\n \nExample 1:\n\nInput: num = 8\nOutput: [3,3]\nExplanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\n\n\nExample 2:\n\nInput: num = 123\nOutput: [5,25]\n\n\nExample 3:\n\nInput: num = 999\nOutput: [40,25]\n\n\n \nConstraints:\n\n\n\t1 <= num <= 10^9\n\n", "solution_py": "class Solution:\n\tdef closestDivisors(self, num: int) -> List[int]:\n\t\tfor i in range(int((num+2) ** (0.5)), 0, -1): \n\t\t\tif not (num+1) % i: return [i, (num+1)//i] \n\t\t\tif not (num+2) % i: return [i, (num+2)//i] \n\t\treturn []", "solution_js": "/**\n * @param {number} num\n * @return {number[]}\n */\nvar closestDivisors = function(num) {\n const n1 = num + 1;\n const n2 = num + 2;\n\n let minDiff = Infinity;\n let result = [];\n for(let i = Math.floor(Math.sqrt(n2)); i >= 1; i--) {\n if(n1 % i === 0) {\n const diff = Math.abs(i - (n1 / i));\n if(diff < minDiff) {\n minDiff = diff;\n result = [i, n1 / i]\n }\n }\n\n if(n2 % i === 0) {\n const diff = Math.abs(i - (n2 / i));\n if(diff < minDiff) {\n minDiff = diff;\n result = [i, n2 / i]\n }\n }\n }\n\n return result;\n};", "solution_java": "class Solution {\n public int[] closestDivisors(int num) {\n int ans[]=new int[2];\n double a=Math.sqrt(num+1);\n double b=Math.sqrt(num+2);\n if(num==1){\n ans[0]=1;\n ans[1]=2;\n return ans;\n }\n else if(a%1==0){\n ans[0]=(int)a;\n ans[1]=(int)b;\n return ans;\n }\n else if(b%1==0){\n ans[0]=(int)b;\n ans[1]=(int)b;\n return ans;\n }\n else{\n int m=(int)Math.sqrt(num);\n int diff1=Integer.MAX_VALUE;\n int y=0,z=0,w=0,f=0;\n for(int i=2;i<=m;i++){\n if((num+1)%i==0){\n y=i;\n z=(num+1)/y;\n int r=Math.abs(y-z);\n if(r findnumbers(int num)\n\t{\n\t\tint m=sqrt(num);\n\t\twhile(num%m!=0)\n\t\t{\n\t\t\tm--;\n\t\t}\n\t\treturn {num/m,m};\n\t}\n\tvector closestDivisors(int num) \n\t{\n\t\tvector ans1=findnumbers(num+1);\n\t\tvector ans2=findnumbers(num+2);\n\t\tif(abs(ans1[0]-ans1[1]) int:\n n = len(s)\n dp = [[0 for x in range(n)] for x in range(n)]\n for i in range(n): dp[i][i] = 1 # Single length strings are palindrome\n for chainLength in range(2, n+1):\n for i in range(0, n-chainLength+1): # Discarding the lower triangle\n j = i + chainLength - 1\n if s[i] == s[j]: \n if chainLength == 2: dp[i][j] = 2\n else: dp[i][j] = dp[i+1][j-1] + 2\n else: dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return dp[0][n-1]", "solution_js": "var longestPalindromeSubseq = function(s) {\n const { length } = s;\n const dp = Array(length).fill('').map(() => Array(length).fill(0));\n\n for (let start = 0; start < length; start++) {\n const str = s[start];\n dp[start][start] = 1;\n\n for (let end = start - 1; end >= 0; end--) {\n dp[start][end] = str === s[end]\n ? dp[start - 1][end + 1] + 2\n : Math.max(dp[start - 1][end], dp[start][end + 1])\n }\n }\n return dp[length - 1][0];\n};", "solution_java": "class Solution {\n public int longestPalindromeSubseq(String s) {\n \tStringBuilder sb = new StringBuilder(s);\n \t sb.reverse();\n \t String s2 = sb.toString();\n return longestCommonSubsequence(s,s2);\n }\n public int longestCommonSubsequence(String text1, String text2) {\n int [][]dp = new int[text1.length()+1][text2.length()+1]; \n for(int i= text1.length()-1;i>=0;i--){\n for(int j = text2.length()-1;j>=0;j--){\n char ch1 = text1.charAt(i);\n char ch2 = text2.charAt(j);\n if(ch1==ch2) // diagnal\n dp[i][j]= 1+dp[i+1][j+1];\n else// right,down considering not matchning char from s1 and skipping s2 \n //considering not matchning char from s2 and skipping s1\n dp[i][j] = Math.max(dp[i][j+1],dp[i+1][j]);\n \n }\n }\n return dp[0][0];\n }\n}", "solution_c": "class Solution {\npublic:\n int longestPalindromeSubseq(string s) {\n int n = s.size();\n int dp[n][n];\n memset(dp, 0, sizeof(dp));\n for(int i = 0; i < n; i++){\n dp[i][i] = 1;\n }\n int res = 1;\n for(int j = 1; j < n; j++){\n for(int r = 0, c = j ; r < n && c < n; r++, c++){\n if(s[r] == s[c]){\n dp[r][c] = 2+dp[r+1][c-1];\n }\n else{\n dp[r][c] = max(dp[r][c-1],dp[r+1][c]);\n }\n }\n }\n return dp[0][n-1];\n }\n};" }, { "title": "Complement of Base 10 Integer", "algo_input": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\n\n\n\tFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n\n\nGiven an integer n, return its complement.\n\n \nExample 1:\n\nInput: n = 5\nOutput: 2\nExplanation: 5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.\n\n\nExample 2:\n\nInput: n = 7\nOutput: 0\nExplanation: 7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.\n\n\nExample 3:\n\nInput: n = 10\nOutput: 5\nExplanation: 10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.\n\n\n \nConstraints:\n\n\n\t0 <= n < 109\n\n\n \nNote: This question is the same as 476: https://leetcode.com/problems/number-complement/\n", "solution_py": "class Solution:\n def bitwiseComplement(self, n: int) -> int:\n cnt=0\n ans=0\n if n==0:\n return 1\n while n>0:\n if n&1:\n cnt+=1\n else:\n ans =ans +(2**cnt)\n cnt+=1\n n=n>>1\n return ans", "solution_js": "var bitwiseComplement = function(n) {\n let xor = 0b1;\n let copy = Math.floor(n / 2);\n while (copy > 0) {\n xor = (xor << 1) + 1\n copy = Math.floor(copy / 2);\n }\n \n return n ^ xor;\n};", "solution_java": "class Solution {\n public int bitwiseComplement(int n) {\n String bin = Integer.toBinaryString(n);\n String res = \"\";\n for(char c :bin.toCharArray())\n {\n if( c == '1')\n res += \"0\";\n else\n res += \"1\";\n }\n return Integer.parseInt(res, 2);\n }\n}", "solution_c": "class Solution {\npublic:\n int bitwiseComplement(int num) {\n\t\t //base case\n if(num == 0) return 1;\n unsigned mask = ~0;\n while( mask & num ) mask = mask << 1;\n return ~num ^ mask;\n }\n};" }, { "title": "Longest Subsequence Repeated k Times", "algo_input": "You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\nA subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.\n\n\n\tFor example, \"bba\" is repeated 2 times in the string \"bababcba\", because the string \"bbabba\", constructed by concatenating \"bba\" 2 times, is a subsequence of the string \"bababcba\".\n\n\nReturn the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.\n\n \nExample 1:\n\nInput: s = \"letsleetcode\", k = 2\nOutput: \"let\"\nExplanation: There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.\n\n\nExample 2:\n\nInput: s = \"bb\", k = 2\nOutput: \"b\"\nExplanation: The longest subsequence repeated 2 times is \"b\".\n\n\nExample 3:\n\nInput: s = \"ab\", k = 2\nOutput: \"\"\nExplanation: There is no subsequence repeated 2 times. Empty string is returned.\n\n\n \nConstraints:\n\n\n\tn == s.length\n\t2 <= n, k <= 2000\n\t2 <= n < k * 8\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n n = len(s)\n max_chunk_sz = n // k\n \n d = collections.Counter(s)\n chars = sorted([c for c in d if d[c] >= k], reverse=True)\n if not chars:\n return ''\n \n old_cand = chars\n for m in range(2, max_chunk_sz+1):\n new_cand = []\n for t in self.get_next_level(old_cand, chars):\n if self.find(s, t*k):\n new_cand.append(t)\n \n if len(new_cand) == 0:\n break\n old_cand = new_cand\n return old_cand[0]\n \n def get_next_level(self, cand, chars):\n for s in cand:\n for ch in chars:\n yield s + ch\n \n def find(self, s, t):\n # find subsequence t in s\n j = 0\n for i in range(len(s)):\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n return True\n return False", "solution_js": "// Idea comes from:\n// https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1471930/Python-Answer-is-not-so-long-explained\n\nvar longestSubsequenceRepeatedK = function(s, k) {\n const freq = {};\n for (const c of s) {\n if (!freq[c]) freq[c] = 0;\n freq[c]++;\n }\n\n // Find hot string\n let hot = \"\";\n for (const [c, cnt] of Object.entries(freq)) {\n const repeat = Math.floor(cnt / k);\n hot += c.repeat(repeat);\n }\n\n // Find all subset and permutation of hot string\n let targets = new Set();\n const subsets = getSubset(hot);\n for (const subset of subsets) {\n const permutations = getPermutation(subset);\n for (const per of permutations) targets.add(per);\n }\n\n // Sort targets by length and lexico\n targets = [...targets].sort((a, b) => {\n const delta = b.length - a.length;\n if (delta) return delta;\n return b.localeCompare(a);\n });\n\n // Filter s and check subsequence\n s = [...s].filter(c => hot.includes(c)).join(\"\");\n for (const tar of targets) {\n if (isSubsequence(s, tar.repeat(k))) return tar;\n }\n\n return \"\";\n};\n\nfunction getSubset(str) {\n const res = [\"\"];\n for (const c of str) {\n res.push(...res.map((curStr) => curStr + c));\n }\n return [...new Set(res)];\n};\n\nfunction getPermutation(str) {\n let res = [\"\"];\n for (const c of str) {\n const resT = [];\n for (const cur of res) {\n for (let i = 0; i <= cur.length; i++) {\n const curT = cur.substring(0, i) + c + cur.substring(i);\n resT.push(curT);\n }\n }\n res = resT;\n }\n return [...new Set(res)];\n};\n\nfunction isSubsequence(s, t) {\n let i = 0;\n for (let j = 0; j < s.length; j++) {\n if (t[i] === s[j]) {\n i++;\n if (i === t.length) return true;\n }\n }\n return false;\n}", "solution_java": "class Solution {\n char[] A;\n public String longestSubsequenceRepeatedK(String s, int k) {\n A = s.toCharArray();\n Queue queue = new ArrayDeque<>();\n queue.offer(\"\");\n String ans = \"\";\n int[] count = new int[26];\n BitSet bit = new BitSet();\n for (char ch : A) if (++count[ch-'a'] >= k){\n bit.set(ch-'a');\n }\n while(!queue.isEmpty()){\n String sb = queue.poll();\n for (int i = bit.nextSetBit(0); i >= 0; i = bit.nextSetBit(i+1)){\n String res = sb+(char)(i+'a');\n if (check(k, res)){\n ans = res;\n queue.offer(res);\n }\n }\n }\n return ans;\n }\n\n private boolean check(int k, String s){\n int cnt = 0;\n for (char ch : A){\n if (s.charAt(cnt%s.length()) == ch && ++cnt >= k * s.length()){\n return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n int Alpha=26;\n bool find(string &s,string &p,int k)\n {\n int j=0;\n int n=s.size();\n int count=0;\n for(int i=0;iq;\n q.push(\"\");\n string ans=\"\";\n while(q.size())\n {\n auto temp=q.front();\n q.pop();\n for(int i=0;i bool:\n if k > len(s):\n return False\n h = Counter(s)\n countOdd = 0\n for value in h.values():\n if value % 2:\n countOdd += 1\n if countOdd > k:\n return False\n return True", "solution_js": "var canConstruct = function(s, k) {\n if(s.length < k) return false;\n // all even all even\n // all even max k odd\n const freq = {};\n for(let c of s) {\n freq[c] = (freq[c] || 0) + 1;\n }\n\n let oddCount = 0;\n const freqOfNums = Object.values(freq);\n for(let cnt of freqOfNums) {\n if(cnt & 1) oddCount++;\n }\n\n return oddCount <= k;\n};", "solution_java": "class Solution {\n public boolean canConstruct(String s, int k) {\n if(k==s.length())\n {\n return true;\n }\n else if(k>s.length())\n {\n return false;\n }\n Map map=new HashMap();\n for(int i=0;iele:map.entrySet())\n {\n if((ele.getValue()%2)==1)\n {\n odd++;\n }\n }\n return (odd<=k);\n }\n}", "solution_c": "class Solution {\npublic:\n bool canConstruct(string s, int k) {\n if(s.size() < k) return false;\n \n unordered_map m;\n for(char c : s) m[c]++;\n \n int oddFr = 0;\n for(auto i : m) if(i.second % 2) oddFr++;\n \n return oddFr <= k;\n }\n};" }, { "title": "Find Closest Number to Zero", "algo_input": "Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.\n \nExample 1:\n\nInput: nums = [-4,-2,1,4,8]\nOutput: 1\nExplanation:\nThe distance from -4 to 0 is |-4| = 4.\nThe distance from -2 to 0 is |-2| = 2.\nThe distance from 1 to 0 is |1| = 1.\nThe distance from 4 to 0 is |4| = 4.\nThe distance from 8 to 0 is |8| = 8.\nThus, the closest number to 0 in the array is 1.\n\n\nExample 2:\n\nInput: nums = [2,-1,1]\nOutput: 1\nExplanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 1000\n\t-105 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n \n def findClosestNumber1(self, nums: List[int]) -> int:\n return min(nums, key=lambda x: (abs(x), -x))\n \n def findClosestNumber2(self, nums: List[int]) -> int:\n return min(nums, key=lambda x: abs(x - .1))\n \n def findClosestNumber3(self, nums: List[int]) -> int:\n return max((-abs(x), x) for x in nums)[1]\n \n def findClosestNumber4(self, nums: List[int]) -> int:\n return -min(zip(map(abs, nums), map(neg, nums)))[1]\n\n def findClosestNumber5(self, nums: List[int]) -> int:\n a = min(map(abs, nums))\n return a if a in nums else -a\n\n def findClosestNumber6(self, nums: List[int]) -> int:\n a = abs(min(nums, key=abs))\n return a if a in nums else -a\n\n def findClosestNumber7(self, nums: List[int]) -> int:\n x = min(nums, key=abs)\n return x if x >= 0 or -x not in nums else -x\n \n def findClosestNumber8(self, nums: List[int]) -> int:\n return min(sorted(nums, reverse=True), key=abs)\n \n def findClosestNumber9(self, nums: List[int]) -> int: \n a = abs(nums[0])\n for x in nums:\n if x < 0:\n x = -x\n if x < a:\n a = x\n return a if a in nums else -a\n \n def findClosestNumberA(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < 0:\n if x > neg:\n neg = x\n elif x < pos:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberB(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if x < pos and neg < x:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberC(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x and x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumberD(self, nums: List[int]) -> int: \n pos = 999999\n neg = -pos\n for x in nums:\n if neg < x < pos:\n if x < 0:\n neg = x\n else:\n pos = x\n return pos if pos <= -neg else neg\n \n def findClosestNumber(self, nums: List[int], timess=defaultdict(lambda: [0] * 10), testcase=[0]) -> int:\n name = 'findClosestNumber'\n solutions = [getattr(self, s)\n for s in dir(self)\n if s.startswith(name)\n and s != name]\n expect = dummy = object()\n from time import perf_counter as time\n for i in range(10):\n shuffle(solutions)\n for solution in solutions:\n start = time()\n result = solution(nums)\n end = time()\n if expect is dummy:\n expect = result\n assert result == expect\n timess[solution.__name__][i] += end - start\n testcase[0] += 1\n if testcase[0] == 224:\n for name, times in sorted(timess.items(), key=lambda nt: sorted(nt[1])):\n print(name, *(f'{t*1e3:6.2f} ms' for t in sorted(times)[:3]))\n return\n return result\n\t\t", "solution_js": "//Solution 1\nvar findClosestNumber = function(nums) {\n \n let pos = Infinity;\n let neg = -Infinity;\n \n for(let i = 0; i < nums.length; i++) {\n \n if( nums[i] > 0 ){\n if( pos > nums[i] ) \n pos = nums[i]; \n } else {\n if( neg < nums[i] )\n neg = nums[i];\n } \n }\n \n if( -neg < pos ) {\n return neg;\n }\n \n return pos; \n};\n\n//Solution 2\nvar findClosestNumber = function(nums) {\n \n let result = nums[0];\n \n for(let i=1; imod ) { \n result = nums[i]\n }\n \n if( Math.abs(result) == mod ) {\n if( result Math.abs(n)) {\n min = Math.abs(n);\n closest_num = n;\n } else if(min == Math.abs(n) && closest_num < n) {\n closest_num = n;\n }\n }\n return closest_num;\n }\n}", "solution_c": "class Solution {\npublic:\n int findClosestNumber(vector& nums) {\n// setting the ans to maximum value of int\n int ans = INT_MAX ;\n for(int i : nums){\n // checking if each value of nums is less than the max value\n if(abs(i) < abs(ans)){\n ans = i ; //check for the lesser value\n }\n else if(abs(i) == abs(ans)){\n ans = max (ans,i) ; // return the maximum in cases there are multiple answers\n }\n }\n return ans ;\n }\n};" }, { "title": "Minimum Skips to Arrive at Meeting On Time", "algo_input": "You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.\n\nAfter you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.\n\n\n\tFor example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.\n\n\nHowever, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.\n\n\n\tFor example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.\n\n\nReturn the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.\n\n \nExample 1:\n\nInput: dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput: 1\nExplanation:\nWithout skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\n\n\nExample 2:\n\nInput: dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput: 2\nExplanation:\nWithout skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\n\n\nExample 3:\n\nInput: dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput: -1\nExplanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n\n\n \nConstraints:\n\n\n\tn == dist.length\n\t1 <= n <= 1000\n\t1 <= dist[i] <= 105\n\t1 <= speed <= 106\n\t1 <= hoursBefore <= 107\n\n", "solution_py": "from math import *\nclass Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n n=len(dist)\n\t\t# Error Range 10^-9 can be ignored in ceil, so we will subtract this value before taking ceil \n e=1e-9\n mat=[[0 for i in range(n)]for j in range(n)]\n mat[0][0]=dist[0]/speed\n\t\t# Initialization \n\t\t# Values where 0 skips are considered\n for i in range(1,n):\n mat[i][0]=ceil(mat[i-1][0]-e)+dist[i]/speed\n for i in range(1,n):\n for j in range(1,i):\n mat[i][j]=min(ceil(mat[i-1][j]-e),mat[i-1][j-1])+dist[i]/speed\n mat[i][i]=mat[i-1][i-1]+dist[i]/speed\n for i in range(n):\n if mat[-1][i]<=hoursBefore:\n return i\n return -1", "solution_js": "var minSkips = function(dist, speed, hoursBefore) {\n\n // calculates the time needed to rest\n const getRestTime = (timeFinished) => {\n if (timeFinished === Infinity) return 0;\n return (speed - (timeFinished % speed)) % speed;\n }\n\n // dp is a n x n matrix with\n // dp[destinationIndex][numRestsSkipped] = timeTaken\n //\n // destinationIndex: the index of the destination being observed\n // numRestsSkipped: number of rests taken\n // timeTaken: minimum time taken to travel to destination taking numRests number of rests\n const dp = [...dist].map(() => new Array(dist.length).fill(Infinity));\n\n // start with the first stop\n dp[0][0] = dist[0] + getRestTime(dist[0]) // took a rest at the first destination\n dp[0][1] = dist[0]; // did not take a rest at the first destination\n\n for (let distIdx = 1; distIdx < dist.length; distIdx++) {\n const distance = dist[distIdx];\n let timeToDestWithoutrest = dp[distIdx - 1][0] + distance;\n dp[distIdx][0] = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);\n for (let numRestsSkipped = 1; numRestsSkipped <= distIdx + 1; numRestsSkipped++) {\n // calculate the time if taking a rest here\n timeToDestWithoutrest = dp[distIdx - 1][numRestsSkipped] + distance;\n const didRestTimeToDest = timeToDestWithoutrest + getRestTime(timeToDestWithoutrest);\n\n // calculate the time without resting here\n const didntRestTimeToDest = dp[distIdx - 1][numRestsSkipped - 1] + distance\n\n // store the best time in the dp\n dp[distIdx][numRestsSkipped] = Math.min(dp[distIdx][numRestsSkipped],\n didRestTimeToDest,\n didntRestTimeToDest);\n }\n }\n\n // find the minimum number of rests visiting all the destinations\n const speedHours = speed * hoursBefore;\n for (let numRests = 0; numRests < dist.length; numRests++) {\n if (dp[dist.length - 1][numRests] <= speedHours) {\n return numRests;\n }\n }\n return -1;\n};", "solution_java": "class Solution {\n public int minSkips(int[] dist, int speed, int hoursBefore) {\n int N = dist.length, INF = (int)1e9;\n int[] dp = new int[N];\n Arrays.fill(dp, INF);\n dp[0]=0; // before we start, we have a time of 0 for 0 cost\n for (int i = 0 ; i= 0; j--){ // j (cost) is at most i (num of element-1) so we start from there.\n dp[j]=Math.min(j==0?INF:dp[j-1]+dist[i], ceil(dp[j], speed)+dist[i]);\n }\n }\n for (int i = 0; i < N; i++){ // find the min cost (i) such that the min time is no greater than hoursBefore\n if (ceil(dp[i],speed)/speed<=hoursBefore){\n return i;\n }\n }\n return -1;\n }\n\n private int ceil(int n, int s){\n return n+(s-n%s)%s;\n }\n}", "solution_c": "class Solution {\npublic:\n vectorD;\n long long s, last;\n long long memo[1010][1010];\n long long dfs_with_minimum_time_with_k_skip(int idx, int k) {\n if (idx < 0 ) return 0;\n long long &ret = memo[idx][k];\n if (ret != -1 ) return ret;\n long long d = dfs_with_minimum_time_with_k_skip(idx - 1, k) + D[idx];\n if (d % s) d = ((d/s) + 1)*s;\n ret = d;\n if (k > 0 ) ret = min(ret, dfs_with_minimum_time_with_k_skip(idx - 1, k - 1) + D[idx]);\n return ret;\n }\n int minSkips(vector& dist, int speed, int hoursBefore) {\n int n = dist.size();\n D = dist, s = speed;\n int lo = 0, hi = n;\n long long d = 0, H = hoursBefore;\n H *=s;\n last = dist[n-1];\n for (int dd : dist) d += dd;\n memset(memo, -1, sizeof(memo));\n if (d /s > hoursBefore) return -1;\n while (lo < hi) {\n int mid = (lo + hi) / 2;\n long long h = dfs_with_minimum_time_with_k_skip(n-2, mid) + last; // we should start from second last since it is not required to rest on last road\n if (h <= H ) hi = mid;\n else lo = mid + 1;\n }\n return lo == D.size() ? -1 : lo;\n\n }\n};" }, { "title": "Most Common Word", "algo_input": "Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.\n\nThe words in paragraph are case-insensitive and the answer should be returned in lowercase.\n\n \nExample 1:\n\nInput: paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\", banned = [\"hit\"]\nOutput: \"ball\"\nExplanation: \n\"hit\" occurs 3 times, but it is a banned word.\n\"ball\" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as \"ball,\"), \nand that \"hit\" isn't the answer even though it occurs more because it is banned.\n\n\nExample 2:\n\nInput: paragraph = \"a.\", banned = []\nOutput: \"a\"\n\n\n \nConstraints:\n\n\n\t1 <= paragraph.length <= 1000\n\tparagraph consists of English letters, space ' ', or one of the symbols: \"!?',;.\".\n\t0 <= banned.length <= 100\n\t1 <= banned[i].length <= 10\n\tbanned[i] consists of only lowercase English letters.\n\n", "solution_py": "class Solution:\n import string\n from collections import Counter\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n #sunday morning hangover solution haha\n \n #calling this twice seems unnecesary but whatevs\n #replace \",\" with \" \" (apparently translate() is much quicker than replace)\n para = paragraph.translate(str.maketrans(\",\",\" \"))\n #strip out rest of punctuation and make it lower case\n para = para.translate(str.maketrans(' ', ' ', string.punctuation)).lower()\n #split on the sapces\n para = para.split()\n #staple counter function\n para_count = Counter(para)\n #loop thru banned words, if they're in para_count pop the off\n for word in banned:\n if word in para_count:\n para_count.pop(word)\n #return val from most common\n return para_count.most_common(1)[0][0]", "solution_js": "var mostCommonWord = function(paragraph, banned) {\n\tparagraph = new Map(Object.entries(\n\tparagraph\n\t\t.toLowerCase()\n\t\t.match(/\\b[a-z]+\\b/gi)\n\t\t.reduce((acc, cur) => ((acc[cur] = (acc[cur] || 0) + 1), acc), {}))\n\t\t.sort((a, b) => b[1] - a[1])\n\t);\n\tfor (let i = 0; i < banned.length; i++) paragraph.delete(banned[i]);\n\treturn paragraph.entries().next().value[0];\n};", "solution_java": "class Solution {\n public String mostCommonWord(String paragraph, String[] banned) {\n\n HashMap hm = new HashMap<>();\n String[] words = paragraph.replaceAll(\"[!?',;.]\",\" \").toLowerCase().split(\"\\\\s+\");\n for(int i=0; i& banned) {\n string temp;\n vector words;\n for(char c:paragraph){\n if(isalpha(c) && !isspace(c)) temp+=tolower(c);\n else{\n if(temp.length()) words.push_back(temp);\n temp=\"\";\n }\n }\n if(temp.length()) words.push_back(temp);\n \n map mp;\n for(string i:words) mp[i]++;\n for(string i:banned) mp[i]=0;\n string ans;\n int maxUsedFreq=0;\n for(auto i:mp){\n if(i.second>maxUsedFreq){ \n ans=i.first;\n maxUsedFreq=i.second;\n }\n }\n return ans;\n }\n};" }, { "title": "Teemo Attacking", "algo_input": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.\n\nYou are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.\n\nReturn the total number of seconds that Ashe is poisoned.\n\n \nExample 1:\n\nInput: timeSeries = [1,4], duration = 2\nOutput: 4\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\n\n\nExample 2:\n\nInput: timeSeries = [1,2], duration = 2\nOutput: 3\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.\n\n \nConstraints:\n\n\n\t1 <= timeSeries.length <= 104\n\t0 <= timeSeries[i], duration <= 107\n\ttimeSeries is sorted in non-decreasing order.\n\n", "solution_py": "class Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n \n \"\"\"\n timeDur = (timeSeries[0], timeSeries[0] + duration - 1)\n i = 1\n total = 0\n while i < len(timeSeries):\n if timeSeries[i] > timeDur[1]:\n total += (timeDur[1] - timeDur[0] + 1)\n else:\n total += (timeSeries[i] - timeDur[0])\n timeDur = (timeSeries[i], timeSeries[i] + duration - 1)\n i += 1\n total += (timeDur[1] - timeDur[0] + 1)\n return total\n \n \"\"\"\n # Between two interval, Ashe can be poisoned only for max duration time,\n # if time differece is less than duranton, then we that value\n total = 0\n for i in range(len(timeSeries)-1):\n total += min(duration, timeSeries[i+1] - timeSeries[i])\n return total + duration\n ", "solution_js": "var findPoisonedDuration = function(timeSeries, duration) {\n let totalTime=duration\n\n for(let i=0;i+1duration ? duration : diff\n }\n return totalTime\n\n};", "solution_java": "// Teemo Attacking\n// https://leetcode.com/problems/teemo-attacking/\n\nclass Solution {\n public int findPoisonedDuration(int[] timeSeries, int duration) {\n int sum = 0;\n for (int i = 0; i < timeSeries.length; i++) {\n if (i == 0) {\n sum += duration;\n } else {\n sum += Math.min(duration, timeSeries[i] - timeSeries[i - 1]);\n }\n }\n return sum; \n }\n}", "solution_c": "class Solution {\npublic:\n int findPoisonedDuration(vector& timeSeries, int duration) {\n int ans=0;\n int n=timeSeries.size();\n for(int i=0;i bool:\n def dfs(node, depth):\n if self.ans or not node: return 0\n if node.val == x or node.val == y: return depth\n l = dfs(node.left, depth+1)\n r = dfs(node.right, depth+1)\n if not (l and r): return l or r\n if l == r and l != depth + 1: self.ans = True\n return 0\n \n dfs(root, 0)\n return self.ans", "solution_js": "var isCousins = function(root, x, y) {\n let xHeight = 1;\n let xParent = null;\n let yHeight = 1;\n let yParent = null;\n \n const helper = (node, depth, parent) => {\n if(node === null)\n return null;\n \n helper(node.left, depth + 1, node);\n helper(node.right, depth + 1, node);\n \n let val = node.val;\n \n if(val === x) {\n xHeight = depth;\n xParent = parent;\n }\n \n if(val === y) {\n yHeight = depth;\n yParent = parent;\n }\n }\n \n helper(root, 0);\n \n return xHeight === yHeight && xParent !== yParent ? true : false;\n};", "solution_java": "class Solution {\n public boolean isCousins(TreeNode root, int x, int y) {\n Set parentSet = new HashSet<>();\n Queue q = new LinkedList<>();\n q.add(root);\n\n while (!q.isEmpty()) {\n int len = q.size();\n\n for (int i = 0; i < len; i++) {\n TreeNode parent = q.remove();\n\n for (TreeNode child : new TreeNode[]{parent.left, parent.right}) {\n if(child != null) {\n q.add(child);\n if (child.val == x || child.val == y)\n parentSet.add(parent);\n }\n }\n }\n if (parentSet.size() > 0)\n return parentSet.size() == 2; //if same parent -> set size wil be 1\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isCousins(TreeNode* root, int x, int y) {\n if(root -> left == NULL || root -> right == NULL) return false;\n //to store node with parent\n queue > q;\n //push root\n q.push({root, NULL});\n //push NULL for level seperation\n q.push({NULL, NULL});\n //boolean val to know if we found x or y yet during traversal of tree\n pair foundx = {false, NULL}, foundy = {false, NULL};\n \n //start the level order traversal\n while(!q.empty()){\n TreeNode* top = q.front().first;\n TreeNode* parent = q.front().second;\n q.pop();\n \n //when a level is completely traversed\n if(top == NULL){\n //if we found both x and y and if their parent are not same we found cousins\n if(foundx.first && foundy.first && foundx.second != foundy.second) return true;\n //if one of them found when other not, or when both were found and their parent were equal\n if(foundx.first || foundy.first) return false;\n //push another NULL for further level seperation, if there are any.\n if(!q.empty()) q.push({NULL, NULL});\n }\n else{\n //find x and y\n if(top -> val == x) foundx = {true, parent};\n if(top -> val == y) foundy = {true, parent};\n \n //push current node's childs with parent as current node.\n if(top -> left) q.push({top -> left, top});\n if(top -> right) q.push({top -> right, top});\n }\n }\n return false;\n }\n};" }, { "title": "Decrease Elements To Make Array Zigzag", "algo_input": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.\n\nAn array A is a zigzag array if either:\n\n\n\tEvery even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...\n\tOR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...\n\n\nReturn the minimum number of moves to transform the given array nums into a zigzag array.\n\n \nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: We can decrease 2 to 0 or 3 to 1.\n\n\nExample 2:\n\nInput: nums = [9,6,1,6,2]\nOutput: 4\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 1000\n\n", "solution_py": "class Solution:\n def solve(self,arr,n,x):\n idx = 1\n ans = 0\n while idx < n:\n if idx == 0: idx += 1\n if idx % 2 == x:\n if arr[idx-1] >= arr[idx]:\n ans += arr[idx-1] - arr[idx] + 1\n arr[idx-1] = arr[idx] - 1\n idx = idx-1\n else:\n idx = idx+1\n else:\n if arr[idx-1] <= arr[idx]:\n ans += arr[idx] - arr[idx - 1] + 1\n arr[idx] = arr[idx-1] - 1\n idx += 1 \n return ans\n \n def movesToMakeZigzag(self, nums: List[int]) -> int:\n ans1 = self.solve([x for x in nums],len(nums),0)\n ans2 = self.solve([x for x in nums],len(nums),1)\n return min(ans1,ans2)", "solution_js": "var movesToMakeZigzag = function(nums) {\n const n = nums.length;\n\n let lastEvenRight = Number.MIN_SAFE_INTEGER;\n let evenMoves = 0;\n\n let lastOddRight = nums[0];\n let oddMoves = 0;\n\n for (let i = 0; i < n; i++) {\n const currNum = nums[i];\n const nextNum = i < n - 1 ? nums[i + 1] : Number.MIN_SAFE_INTEGER;\n\n if (i % 2 === 0) {\n if (lastEvenRight >= currNum) evenMoves += lastEvenRight - currNum + 1;\n\n if (currNum <= nextNum) {\n evenMoves += nextNum - currNum + 1;\n }\n\n lastEvenRight = Math.min(currNum - 1, nextNum);\n }\n else {\n if (lastOddRight >= currNum) oddMoves += lastOddRight - currNum + 1;\n\n if (currNum <= nextNum) {\n oddMoves += nextNum - currNum + 1;\n }\n\n lastOddRight = Math.min(currNum - 1, nextNum);\n }\n }\n\n return Math.min(oddMoves, evenMoves);\n};", "solution_java": "class Solution {\n /*\n firstly, check elements in odd indices are greater than its neighbours.\n if not, decrease its neigbours and update the cost.\n \n do same thing for even indices, because there can be two combinations as indicated in question.\n */\n \n private int calculateCost(int[] nums, int start){\n int res = 0;\n int n = nums.length;\n int[] arr = Arrays.copyOf(nums, nums.length); // nums array will be modified, so copy it.\n \n for(int i=start;i= cur){\n res += prev-cur +1;\n arr[i-1] = cur-1;\n } \n \n if(next >= cur){\n res += next-cur +1;\n arr[i+1] = cur-1;\n }\n }\n return res;\n }\n \n public int movesToMakeZigzag(int[] nums) {\n return Math.min(calculateCost(nums, 0), calculateCost(nums,1));\n }\n}", "solution_c": "class Solution {\npublic:\n int movesToMakeZigzag(vector& nums) {\n int oddSum = 0, evenSum = 0;\n int n = nums.size();\n for(int i=0; i int:\n self.res=root.val\n def solving(root):\n if not root:\n return 0\n current=root.val\n sleft,sright=float('-inf'),float('-inf')\n if root.left:\n sleft=solving(root.left)\n if(sleft>=0):\n current+=sleft\n if root.right:\n sright=solving(root.right)\n if(sright>=0):\n current+=sright\n if(current>self.res):\n self.res=current\n return max(root.val, root.val+sleft, root.val+sright)\n solving(root)\n return self.res", "solution_js": "var maxPathSum = function(root) {\n let res = -Infinity;\n function solve(root){\n if(!root){\n return 0;\n }\n \n let left = solve(root.left);\n let right = solve(root.right);\n //ignore the values with negative sum\n let leftVal = Math.max(left, 0);\n let rightVal = Math.max(right,0);\n \n let localMax = leftVal + rightVal + root.val;\n res = Math.max(localMax,res);\n return Math.max(leftVal, rightVal) + root.val;\n \n }\n solve(root);\n return res;\n \n};", "solution_java": "class Solution {\n\n int[] ans = new int[1];\n public int maxPathSum(TreeNode root) {\n ans[0]=root.val; //Handle edge case\n dfs(root);\n return ans[0];\n }\n\n public int dfs(TreeNode root){\n\n if(root==null)\n return 0;\n\n int left=Math.max(0,dfs(root.left)); //Check on the left subtree and if returned negative take 0\n int right=Math.max(0,dfs(root.right)); //Check on the right subtree and if returned negative take 0\n\n int maxInTheNode=root.val+left+right; //Calculating the max while including the root its left and right child.\n ans[0]=Math.max(ans[0],maxInTheNode); //Keeping max globally\n\n return root.val+Math.max(left,right); //Since only one split is allowed returning the one split that returns max value\n }\n}", "solution_c": "class Solution {\npublic:\n int rec(TreeNode* root,int& res ){\n if(root==nullptr) return 0;\n // maximum value from left\n int l = rec(root->left,res);\n //maximum value from right\n int r = rec(root->right,res);\n\n //check if path can go through this node ,if yes upadte the result value\n res = max(res,root->val+l+r);\n\n // return the maximum non-negative path value\n return max({l+root->val,r+root->val,0});\n }\n int maxPathSum(TreeNode* root) {\n int res = INT_MIN;\n int x = rec(root,res);\n return res;\n }\n};" }, { "title": "Max Chunks To Make Sorted II", "algo_input": "You are given an integer array arr.\n\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\n\nReturn the largest number of chunks we can make to sort the array.\n\n \nExample 1:\n\nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n\n\nExample 2:\n\nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 2000\n\t0 <= arr[i] <= 108\n\n", "solution_py": "class Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n sortedArr = sorted(arr)\n\n posMap = defaultdict(list)\n for i in range(len(sortedArr)):\n posMap[sortedArr[i]].append(i) # keep track the right sortedArr[i] position\n\n idx = len(arr) - 1\n cnt = 0\n for i in range(len(arr) - 1, -1, -1):\n idx = min(idx, posMap[arr[i]][-1]) # the smallest position need to move arr[i] to correct position\n posMap[arr[i]].pop()\n if i == idx:\n cnt += 1\n idx -= 1\n return cnt", "solution_js": "var maxChunksToSorted = function(arr) {\n var rmin = new Array(arr.length).fill(0);\n rmin[arr.length] = Number.MAX_SAFE_INTEGER;\n \n for(var i=arr.length-1; i>=0; i--) {\n rmin[i] = Math.min(arr[i], rmin[i+1]);\n }\n \n var lmax = Number.MIN_SAFE_INTEGER;\n var count = 0;\n \n for(var i=0; i. 0 1 2 3 4 5 6 7\n\nInput --> 30 , 10 , 20 , 40 , 60 , 50 , 75 , 70\n <------------> <--> <-------> <------->\nLeft Max --> 30 , 30 , 30 , 40 , 60 , 60 , 75 , 75\n\nRight Min --> 10 , 10 , 20 , 40 , 50 , 50 , 70 , 70 , Integer.max\n\n1. At pos 2 , left_max 30 is smaller than right_min 40 at pos 3\n2. That means , all the elements in the right side of 30 are bigger than all the elements of left side of 30 , including 30\n3. Hence we can break it at pos 2 into a chunk and sort this whole sub-array( 0 - 2 )\n\n*/\n\nclass Solution {\n\n public int maxChunksToSorted(int[] arr) {\n\n // 1. Generate Right min\n\n int[] min_from_right = new int[arr.length+1] ;\n min_from_right[arr.length] = Integer.MAX_VALUE ;\n\n for(int i=arr.length-1 ; i>=0 ; i--){\n min_from_right[i] = Math.min(arr[i] , min_from_right[i+1]);\n }\n\n // 2. Generate Left Max and Count chunks\n int chunk_count = 0 ;\n int max_cur = Integer.MIN_VALUE ;\n\n for(int i=0 ; i& nums) : nodes(nums.size() + 1, 0) {\n for (int i = 0; i < nums.size(); ++i) {\n update(i + 1, nums[i]);\n }\n }\n\n void update(int idx, int val) {\n for (int i = idx; i < nodes.size(); i += i & -i) {\n nodes[i] += val;\n }\n }\n\n int query(int idx) {\n int ans = 0;\n for (int i = idx; i > 0; i -= i & -i) {\n ans += nodes[i];\n }\n return ans;\n }\n\n private:\n vector nodes;\n};\n\nclass Solution {\n public:\n int maxChunksToSorted(vector& arr) {\n int n = arr.size();\n BIT bit(n);\n unordered_map h;\n vector sorted = arr;\n sort(sorted.begin(), sorted.end());\n for (int i = 0; i < n; ++i) {\n if (i == 0 || sorted[i - 1] != sorted[i]) h[sorted[i]] = i + 1;\n }\n\n int ans = 0;\n for (int i = 0; i < n; ++i) {\n bit.update(h[arr[i]], 1);\n ++h[arr[i]];\n if (bit.query(i + 1) == i + 1) ans += 1;\n }\n return ans;\n }\n};" }, { "title": "Largest Divisible Subset", "algo_input": "Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:\n\n\n\tanswer[i] % answer[j] == 0, or\n\tanswer[j] % answer[i] == 0\n\n\nIf there are multiple solutions, return any of them.\n\n \nExample 1:\n\nInput: nums = [1,2,3]\nOutput: [1,2]\nExplanation: [1,3] is also accepted.\n\n\nExample 2:\n\nInput: nums = [1,2,4,8]\nOutput: [1,2,4,8]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 2 * 109\n\tAll the integers in nums are unique.\n\n", "solution_py": "class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n nums.sort()\n n = len(nums)\n dp = [1 for i in range(n)]\n hashh = [i for i in range(n)]\n ans_ind = 0\n \n for i in range(1, n):\n for j in range(0,i):\n if nums[i]%nums[j] == 0 and dp[j]+1 > dp[i]: \n dp[i] = dp[j]+1\n hashh[i] = j\n \n # print(dp)\n # print(hashh)\n out = []\n maxi = dp[0]\n \n for i in range(len(nums)):\n if dp[i] > maxi:\n ans_ind = i\n maxi = dp[i]\n \n while(hashh[ans_ind]!=ans_ind):\n out.append(nums[ans_ind])\n ans_ind = hashh[ans_ind]\n out.append(nums[ans_ind])\n return(out)\n \n \n ", "solution_js": "/** https://leetcode.com/problems/largest-divisible-subset/\n * @param {number[]} nums\n * @return {number[]}\n */\nvar largestDivisibleSubset = function(nums) {\n // Memo\n this.memo = new Map();\n \n // Sort the array so we can do dynamic programming from last number\n // We want to start from last number because it will be the largest number, the largest number will yield the largest subset because it can be divided many times\n nums.sort((a, b) => a - b);\n \n let out = [];\n \n // Perform dynamic programming on every numbers start from the last number\n for (let i = nums.length - 1; i >= 0; i--) {\n let curr = dp(nums, i);\n \n // Update the subset output if the current subset is larger\n if (curr.length > out.length) {\n out = curr;\n }\n }\n \n return out;\n};\n\nvar dp = function(nums, currIdx) {\n // Return from memo\n if (this.memo.has(currIdx) === true) {\n return this.memo.get(currIdx);\n }\n \n let currSubset = [];\n \n // Look up all numbers before `currIdx`\n for (let i = currIdx - 1; i >= 0; i--) {\n // Check if the number at `currIdx` can be divided by number at `i`\n if (nums[currIdx] % nums[i] === 0) {\n // If they can be divided, perform dynamic programming on `i` to get the subset at `i`\n let prevSubset = dp(nums, i);\n \n // If the subset at `i` is longer than current subset, update current subset\n if (prevSubset.length > currSubset.length) {\n currSubset = prevSubset;\n }\n }\n }\n \n // Create the output which include number at `currIdx`\n let out = [...currSubset, nums[currIdx]];\n \n // Set memo\n this.memo.set(currIdx, out);\n \n return out;\n};", "solution_java": "class Solution {\n public List largestDivisibleSubset(int[] nums) {\n Arrays.sort(nums);\n int N = nums.length;\n List ans =new ArrayList();\n int []dp =new int[N];\n Arrays.fill(dp,1);\n int []hash =new int[N];\n for(int i=0;idp[i]){\n dp[i] = dp[j]+1;\n hash[i] = j;\n }\n if(dp[i] > maxi){\n maxi = dp[i];\n lastindex = i;\n }\n }\n }//for ends\n ans.add(nums[lastindex]);\n while(hash[lastindex] != lastindex){\n lastindex = hash[lastindex];\n ans.add(nums[lastindex]);\n }\n return ans;\n }\n\n}", "solution_c": "class Solution {\npublic:\n vector largestDivisibleSubset(vector& nums) {\n \n int n = nums.size();\n sort(nums.begin(), nums.end());\n \n vector ans; \n for(int i = 0; i < n; i++)\n { \n vector tmp;\n tmp.push_back(nums[i]);\n \n // Checking the prev one\n int j = i - 1;\n while(j >= 0)\n {\n if(tmp.back() % nums[j] == 0)\n tmp.push_back(nums[j]);\n \n j--;\n }\n \n // Reversing the order to make it in increasing order\n reverse(tmp.begin(), tmp.end());\n \n // Checking the forward one\n j = i + 1;\n while(j < n)\n {\n if(nums[j] % tmp.back() == 0)\n tmp.push_back(nums[j]);\n \n j++;\n }\n \n // updating the ans\n if(ans.size() < tmp.size())\n ans = tmp;\n }\n \n return ans; \n }\n};" }, { "title": "House Robber II", "algo_input": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.\n\n \nExample 1:\n\nInput: nums = [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.\n\n\nExample 2:\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t0 <= nums[i] <= 1000\n\n", "solution_py": "class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 1:\n return nums[0]\n def helper(nums):\n one, two = 0, 0\n for i in nums:\n temp = max(i + one, two)\n one = two\n two = temp\n return two\n \n return max(helper(nums[:-1]), helper(nums[1:]))", "solution_js": "var rob = function(nums) {\n\n let dp = []\n dp[0] = [0,0]\n dp[1] = [nums[0],0]\n\n for(let i=2; i<=nums.length;i++){\n let val = nums[i-1]\n\n let rob = dp[i-2][0] + val\n let dont = dp[i-1][0]\n let noFirst = dp[i-2][1] + val\n\n let best = (rob>=dont)?rob:dont\n\n if(dp[i-1][1]>noFirst) noFirst=dp[i-1][1]\n\n if(i!=nums.length){\n dp[i] = [best,noFirst]\n }else{\n dp[i] = [dont,noFirst]\n }\n\n }\n return (dp[nums.length][0]>=dp[nums.length][1]) ? dp[nums.length][0]:dp[nums.length][1]\n\n};", "solution_java": "class Solution {\n public int rob(int[] nums) {\n if(nums.length==1){\n return nums[0];\n }\n int[] t = new int[nums.length];\n for(int i = 0 ; i < t.length;i++){\n t[i] = -1;\n }\n int[] k = new int[nums.length];\n for(int i = 0 ; i < k.length;i++){\n k[i] = -1;\n }\n return Math.max(helper(nums,0,0,t),helper(nums,1,1,k));\n }\n static int helper(int[] nums, int i,int start , int[] t){\n if(start==0 && i==nums.length-2){\n return nums[i];\n }\n if(start==1 && i==nums.length-1){\n return nums[i];\n }\n if(start==0 && i>=nums.length-1){\n return 0;\n }\n if(start==1 && i>=nums.length){\n return 0;\n }\n if(t[i] != -1){\n return t[i];\n }\n int pick = nums[i]+helper(nums,i+2,start,t);\n int notpick = helper(nums,i+1,start,t);\n t[i] = Math.max(pick,notpick);\n return t[i];\n }\n}", "solution_c": "class Solution {\npublic:\n int rob(vector& nums) \n {\n int n = nums.size(); \n if(n == 1)\n {\n return nums[0];\n }\n //dp[n][2][1]\n vector>> dp(n+1, vector>(2, vector(2, -1)));\n \n int maxm = 0;\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < 2; j++)\n {\n for(int k = 0; k < 2; k++)\n {\n maxm = max(maxm, dp_fun(dp, i, j, k, nums));\n }\n }\n }\n \n return maxm;\n \n }\n \n int dp_fun(vector>> &dp, int ind, int num, int last, vector &ar)\n {\n int n = ar.size();\n if(dp[ind][num][last] == -1)\n {\n if(ind == 0)\n {\n if(last == 1)\n {\n dp[ind][num][last] = 0;\n }\n else \n {\n if(num == 1)\n {\n dp[ind][num][last] = ar[ind];\n }\n else \n {\n dp[ind][num][last] = 0;\n }\n }\n }\n else if (ind == n-1)\n {\n if(num == 0)\n {\n dp[ind][num][last] = 0;\n }\n else \n {\n if(last == 0)\n {\n dp[ind][num][last] = dp_fun(dp, ind-1, 1, 0, ar); \n }\n else \n {\n dp[ind][num][last] = ar[ind] + dp_fun(dp, ind-1, 0, 1, ar);\n }\n }\n }\n else \n {\n if(num == 1)\n {\n dp[ind][num][last] = max(ar[ind] + dp_fun(dp, ind-1, 0, last, ar), dp_fun(dp, ind-1, 1, last, ar));\n }\n else \n {\n dp[ind][num][last] = dp_fun(dp, ind-1, 1, last, ar);\n }\n }\n }\n return dp[ind][num][last];\n }\n};" }, { "title": "Largest Triangle Area", "algo_input": "Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.\n\n \nExample 1:\n\nInput: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput: 2.00000\nExplanation: The five points are shown in the above figure. The red triangle is the largest.\n\n\nExample 2:\n\nInput: points = [[1,0],[0,0],[0,1]]\nOutput: 0.50000\n\n\n \nConstraints:\n\n\n\t3 <= points.length <= 50\n\t-50 <= xi, yi <= 50\n\tAll the given points are unique.\n\n", "solution_py": "from itertools import combinations\nclass Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n maxA = 0\n for p1, p2, p3 in combinations(points, 3):\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n A=(1/2) * abs(x1*(y2 - y3) + x2*(y3 - y1)+ x3*(y1 - y2))\n if A > maxA: maxA = A\n return maxA", "solution_js": "var largestTriangleArea = function(points) {\n const n = points.length;\n let maxArea = 0;\n \n for (let i = 0; i < n; i++) {\n for (let j = i + 1; j < n; j++) {\n for (k = j + 1; k < n; k++) {\n const area = calcArea(points[i], points[j], points[k]);\n maxArea = Math.max(maxArea, area);\n }\n }\n }\n\n return maxArea;\n};\n\n\nfunction calcArea(coordA, coordB, coordC){\n const [xCoordA, yCoordA] = coordA;\n const [xCoordB, yCoordB] = coordB;\n const [xCoordC, yCoordC] = coordC;\n \n const sideA = xCoordA * (yCoordB - yCoordC);\n const sideB = xCoordB * (yCoordC - yCoordA);\n const sideC = xCoordC * (yCoordA - yCoordB);\n \n return Math.abs((sideA + sideB + sideC) / 2);\n}", "solution_java": "class Solution {\n public double largestTriangleArea(int[][] points) {\n double ans = 0;\n int n = points.length;\n for(int i=0;i>& points) {\n double ans = 0.00000;\n for(int i = 0; i str:\n \"\"\" O(N)TS \"\"\"\n x, y, p = 0, 0, 1\n for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n g = i.group()\n if g == '=':\n p = -1\n elif g[-1] == 'x':\n x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n else:\n y += -p * int(g)\n\n if x == 0 == y:\n return 'Infinite solutions'\n elif x == 0:\n return \"No solution\"\n return f'x={y // x}'", "solution_js": " def solveEquation(self, equation: str) -> str:\n \"\"\" O(N)TS \"\"\"\n x, y, p = 0, 0, 1\n for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n g = i.group()\n if g == '=':\n p = -1\n elif g[-1] == 'x':\n x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n else:\n y += -p * int(g)\n\n if x == 0 == y:\n return 'Infinite solutions'\n elif x == 0:\n return \"No solution\"\n return f'x={y // x}'", "solution_java": "class Solution {\n public int[] simplifyEqn(String eqn){\n int prevSign = 1;\n int sumX = 0;\n int sumNums = 0;\n for(int i=0;i str:\n \"\"\" O(N)TS \"\"\"\n x, y, p = 0, 0, 1\n for i in re.finditer(r\"=|[+-]?\\d*x|[+-]?\\d+\", equation):\n g = i.group()\n if g == '=':\n p = -1\n elif g[-1] == 'x':\n x += p * int(g.replace('x', '1' if len(g) == 1 or not g[-2].isdigit() else ''))\n else:\n y += -p * int(g)\n\n if x == 0 == y:\n return 'Infinite solutions'\n elif x == 0:\n return \"No solution\"\n return f'x={y // x}'" }, { "title": "Random Point in Non-overlapping Rectangles", "algo_input": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.\n\nAny integer point inside the space covered by one of the given rectangles should be equally likely to be returned.\n\nNote that an integer point is a point that has integer coordinates.\n\nImplement the Solution class:\n\n\n\tSolution(int[][] rects) Initializes the object with the given rectangles rects.\n\tint[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.\n\n\n \nExample 1:\n\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\nOutput\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\nExplanation\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n\n\n \nConstraints:\n\n\n\t1 <= rects.length <= 100\n\trects[i].length == 4\n\t-109 <= ai < xi <= 109\n\t-109 <= bi < yi <= 109\n\txi - ai <= 2000\n\tyi - bi <= 2000\n\tAll the rectangles do not overlap.\n\tAt most 104 calls will be made to pick.\n\n", "solution_py": "class Solution:\n \"\"\"\n 1 <= rects.length <= 100\n rects[i].length == 4\n -10^9 <= ai < xi <= 10^9\n -10^9 <= bi < yi <= 10^9\n xi - ai <= 2000\n yi - bi <= 2000\n All the rectangles do not overlap.\n At most 10^4 calls will be made to pick.\n \"\"\"\n\n def __init__(self, rects: List[List[int]]):\n self.rects = rects\n self.n_range = list(range(len(self.rects)))\n self.weights = [(x[2] - x[0] + 1) * (x[3] - x[1] + 1) for x in rects]\n\n def pick(self) -> List[int]:\n rect = self.rects[choices(self.n_range, self.weights, k=1)[0]]\n return [randint(rect[0], rect[2]), randint(rect[1], rect[3])]\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(rects)\n# param_1 = obj.pick()", "solution_js": "/**\n /**\n * @param {number[][]} rects\n */\nvar Solution = function(rects) {\n this.rects = rects;\n this.map = {};\n this.sum = 0;\n // we put in the map the number of points that belong to each rect\n for(let i in rects) {\n const rect = rects[i];\n // the number of points can be picked in this rectangle\n this.sum += (rect[2] - rect[0] + 1) * (rect[3] - rect[1] + 1);\n this.map[this.sum] = i;\n }\n this.keys = Object.keys(this.map);\n};\n\n/**\n * @return {number[]}\n */\nSolution.prototype.pick = function() {\n // random point pick between [1, this.sum]\n const randomPointPick = Math.floor(Math.random() * this.sum) + 1;\n \n // we look for the randomPointPick in the keys of the map\n let pointInMap;\n // the keys exists in map\n if(this.map[randomPointPick]) pointInMap = randomPointPick;\n // the key is the first in the map (we do this check before doing binary search because its out of boundery)\n else if(randomPointPick < this.keys[0]) pointInMap = this.keys[0];\n let high = this.keys.length;\n let low = 1;\n // binary search to find the closest key that bigger than randomPointPick\n while(low <= high && !pointInMap) {\n const mid = Math.floor((low + (high-low)/2));\n if(randomPointPick > this.keys[mid-1] && randomPointPick < this.keys[mid]) {\n pointInMap = this.keys[mid];\n break;\n } else if (randomPointPick > this.keys[mid]){\n low = mid+1;\n } else {\n high = mid-1;\n }\n }\n \n // we have the point, now we can get which rect belong to that point\n const pointInRects = this.map[pointInMap];\n const chosen = this.rects[pointInRects];\n const rightX = chosen[2];\n const leftX = chosen[0];\n const topY = chosen[3];\n const bottomY = chosen[1];\n const pickX = Math.floor(Math.random() * (rightX-leftX+1)) + leftX;\n const pickY = Math.floor(Math.random() * (topY-bottomY+1)) + bottomY;\n return [pickX, pickY]\n};\n\n/** \n * Your Solution object will be instantiated and called as such:\n * var obj = new Solution(rects)\n * var param_1 = obj.pick()\n */", "solution_java": "class Solution {\n \n int[][] rects;\n TreeMap weightedRectIndex = new TreeMap<>();\n int nPoints = 0;\n \n Random rng = new Random();\n\n public Solution(int[][] rects) {\n this.rects = rects;\n int index = 0;\n for (int[] rect : rects) {\n\t\t // inserts cumulative weight key pointing to rectangle index\n weightedRectIndex.put(nPoints, index++);\n nPoints += width(rect) * height(rect);\n }\n }\n \n public int[] pick() {\n\t // generates random point within total weight\n int point = rng.nextInt(nPoints);\n\t\t// finds appropriate rectangle\n var entry = weightedRectIndex.floorEntry(point);\n\t\t// find point within the current rectangle\n int rectPoint = point - entry.getKey();\n int[] rect = rects[entry.getValue()];\n return new int[]{\n rect[0] + rectPoint % width(rect), \n rect[1] + rectPoint / width(rect)};\n }\n \n private int width(int[] rect) {\n return rect[2] - rect[0] + 1;\n }\n \n private int height(int[] rect) {\n return rect[3] - rect[1] + 1;\n }\n}", "solution_c": "class Solution {\npublic:\n vector prefix_sum;\n vector> rects_vec;\n int total = 0;\n \n Solution(vector>& rects) {\n int cur = 0;\n for (int i = 0; i < rects.size(); ++i) {\n cur += (rects[i][2] - rects[i][0] + 1) * (rects[i][3] - rects[i][1] + 1);\n prefix_sum.push_back(cur);\n }\n rects_vec = rects;\n total = cur;\n }\n \n vector pick() {\n int l = 0, r = prefix_sum.size() - 1, mid = 0;\n int rand_num = rand();\n int target = (rand_num % total) + 1;\n\t\t\n while (l <= r) {\n mid = l + (r - l) / 2;\n if (prefix_sum[mid] < target) l = mid + 1;\n else r = mid - 1;\n }\n \n return {rand_num % (rects_vec[l][2] - rects_vec[l][0] + 1) + rects_vec[l][0],\n rand_num % (rects_vec[l][3] - rects_vec[l][1] + 1) + rects_vec[l][1]};\n }\n};" }, { "title": "Shortest Path in Binary Matrix", "algo_input": "Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.\n\nA clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:\n\n\n\tAll the visited cells of the path are 0.\n\tAll the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).\n\n\nThe length of a clear path is the number of visited cells of this path.\n\n \nExample 1:\n\nInput: grid = [[0,1],[1,0]]\nOutput: 2\n\n\nExample 2:\n\nInput: grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput: 4\n\n\nExample 3:\n\nInput: grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput: -1\n\n\n \nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 <= n <= 100\n\tgrid[i][j] is 0 or 1\n\n", "solution_py": "'''\nfrom collections import deque\nclass Solution:\n\tdef shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n\t\tL=len(grid)\n\t\tdef generate_next_state(i,j):\n\t\t\treturn [(i+1,j),(i-1,j),(i,j+1),(i,j-1),(i+1,j-1),(i+1,j+1),(i-1,j-1),(i-1,j+1)]\n\t\tdef valid_state(states):\n\t\t\tres=[]\n\t\t\tfor (i,j) in states:\n\t\t\t\tif i>L-1:continue\n\t\t\t\tif i<0:continue\n\t\t\t\tif j<0:continue\n\t\t\t\tif j>L-1:continue\n\t\t\t\tif grid[i][j]==0:\n\t\t\t\t\tres.append((i,j))\n\t\t\treturn res\n\t\tqueue=deque([(0,0)])\n\t\tres=1\n\t\twhile queue:\n\t\t\tfor _ in range(len(queue)):\n\t\t\t\ti,j=queue.popleft()\n\t\t\t\tval=grid[i][j]\n\t\t\t\tgrid[i][j]=1\n\t\t\t\tif not val:\n\t\t\t\t\tif i==L-1 and j==L-1:\n\t\t\t\t\t\treturn res\n\n\t\t\t\t\tnext_state=valid_state(generate_next_state(i,j))\n\t\t\t\t\tfor (ki,kj) in next_state:\n\t\t\t\t\t\tqueue.append((ki,kj))\n\t\t\tres+=1\n\t\treturn -1\n \n \n \n \n'''", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar shortestPathBinaryMatrix = function(grid) {\n const n = grid.length\n const directions = [\n [-1, 0], [-1, 1], [0, 1], [1, 1],\n [1, 0], [1, -1], [0, -1], [-1, -1]\n ]\n const visited = []\n const distance = []\n const predecessor = []\n const queue = []\n\n for (let i = 0; i < n; i++ ) {\n visited.push(Array.from({length: n}, (v, i) => false))\n distance.push(Array.from({length: n}, (v, i) => 9999))\n predecessor.push(Array.from({length: n}, (v, i) => null))\n }\n\n const startIndex = [0, 0]\n if(grid[startIndex[0]][startIndex[1]] !== 0) {\n return -1\n }\n\n queue.push(startIndex)\n distance[startIndex[0]][startIndex[1]] = 1\n\n while(queue.length > 0) {\n const current = queue.shift()\n visited[current[0]][current[1]] = true\n\n if (current[0] === n-1 && current[1] === n-1) {\n break\n }\n\n directions.forEach(dir => {\n const x = current[0] + dir[0]\n const y = current[1] + dir[1]\n\n if (x < 0 || y < 0 || x >= n || y >= n) {\n return\n }\n\n if (\n grid[x][y] === 0 &&\n visited[x][y] === false &&\n distance[x][y] > distance[current[0]][current[1]] + 1\n ) {\n distance[x][y] = distance[current[0]][current[1]] + 1\n predecessor[x][y] = current\n queue.push([x, y])\n }\n })\n }\n\n console.log(distance)\n console.log(visited)\n console.log(predecessor)\n\n return distance[n-1][n-1] >= 999 ?\n -1 : distance[n-1][n-1]\n};", "solution_java": "class Solution {\n public int shortestPathBinaryMatrix(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n \n boolean [][] visited = new boolean [m][n];\n \n int [] up = {0, 0, 1, -1, 1, 1, -1, -1};\n int [] down = {-1, 1, 0, 0, -1, 1, -1, 1};\n \n /*\n if top-left is 1 or bottom-right is 1\n we will return -1\n */\n if(grid[0][0] == 1 || grid[m-1][n-1] == 1)\n return -1;\n \n ArrayDeque q = new ArrayDeque<>();\n /*\n we will add top-left to the deque\n ans steps as 1\n */\n q.add(new int[]{0,0,1}); \n \n while(q.size() > 0){\n int [] tmp = q.removeFirst();\n int x = tmp[0];\n int y = tmp[1];\n int steps = tmp[2];\n visited[x][y] = true;\n \n if(x == m-1 && y == n-1)\n return steps;\n \n for(int i = 0; i < 8; i++){\n int x_new = x + up[i];\n int y_new = y + down[i];\n /*\n we will traverse level wise using bfs\n and those which can be directly reach via\n current level will be considered as the same\n level and we will return the level of \n bottom-right as result\n */\n if(x_new >= 0 && x_new < m && y_new >= 0 && y_new < n){\n if(visited[x_new][y_new] == false && grid[x_new][y_new] == 0){\n q.add(new int[]{x_new,y_new,steps+1});\n visited[x_new][y_new] = true;\n }\n }\n }\n }\n \n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int shortestPathBinaryMatrix(vector>& grid) {\n int m = grid.size(),n = grid[0].size();\n if(grid[0][0]!=0 || grid[m-1][n-1]!=0) return -1;\n vector> dist(m,vector(n,INT_MAX));\n int ans = INT_MAX;\n queue> q;\n dist[0][0]=1;\n q.push({0,0});\n \n int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1}};\n while(!q.empty()){\n auto curr = q.front();\n q.pop();\n for(int i = 0;i<8;i++){\n int newi = curr.first + dir[i][0];\n int newj = curr.second + dir[i][1];\n if(newi>=0 && newi=0 && newjdist[curr.first][curr.second]+1){\n dist[newi][newj] = dist[curr.first][curr.second]+1;\n q.push({newi,newj});\n }\n }\n }\n }\n \n return dist[m-1][n-1]==INT_MAX?-1:dist[m-1][n-1]; \n }\n};" }, { "title": "Spiral Matrix IV", "algo_input": "You are given two integers m and n, which represent the dimensions of a matrix.\n\nYou are also given the head of a linked list of integers.\n\nGenerate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.\n\nReturn the generated matrix.\n\n \nExample 1:\n\nInput: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation: The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.\n\n\nExample 2:\n\nInput: m = 1, n = 4, head = [0,1,2]\nOutput: [[0,1,2,-1]]\nExplanation: The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.\n\n \nConstraints:\n\n\n\t1 <= m, n <= 105\n\t1 <= m * n <= 105\n\tThe number of nodes in the list is in the range [1, m * n].\n\t0 <= Node.val <= 1000\n\n", "solution_py": "class Solution:\n def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n num = m * n\n res = [[-1 for j in range(n)] for i in range(m)]\n x, y = 0, 0\n dx, dy = 1, 0\n while head:\n res[y][x] = head.val\n if x + dx < 0 or x + dx >= n or y + dy < 0 or y + dy >= m or res[y+dy][x+dx] != -1:\n dx, dy = -dy, dx\n x = x + dx\n y = y + dy\n head = head.next\n return res", "solution_js": " var spiralMatrix = function(m, n, head) {\n var matrix = new Array(m).fill().map(()=> new Array(n).fill(-1))\n var row=0, col=0;\n var direction=\"right\";\n while(head)\n {\n matrix[row][col]=head.val;\n if(direction==\"right\")\n {\n if(col+1 == n || matrix[row][col+1] != -1)\n {\n direction=\"down\"\n row++;\n }\n else\n col++\n }\n else if(direction==\"down\")\n {\n if(row+1 == m || matrix[row+1][col] != -1)\n {\n direction=\"left\"\n col--;\n }\n else\n row++\n }\n else if(direction==\"left\")\n {\n if(col == 0 || matrix[row][col-1] != -1)\n {\n direction=\"up\"\n row--;\n }\n else\n col--\n }\n else if(direction==\"up\")\n {\n if(row == 0 || matrix[row-1][col] != -1)\n {\n direction=\"right\"\n col++;\n }\n else\n row--\n }\n head = head.next;\n }\n return matrix;\n};", "solution_java": "class Solution {\n public int[][] spiralMatrix(int m, int n, ListNode head) {\n int[][] ans=new int[m][n];\n for(int[] arr:ans){\n Arrays.fill(arr,-1);\n }\n \n int rowBegin=0;\n int rowEnd=m-1;\n int columnBegin=0;\n int columnEnd=n-1;\n ListNode cur=head;\n \n \n while(rowBegin<=rowEnd && columnBegin<=columnEnd && cur!=null){\n \n for(int i=columnBegin;i<=columnEnd && cur!=null;i++){\n if(cur!=null){\n ans[rowBegin][i]=cur.val;\n }\n \n cur=cur.next;\n \n \n }\n rowBegin++;\n for(int i=rowBegin;i<=rowEnd && cur!=null;i++){\n if(cur!=null){\n ans[i][columnEnd]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n columnEnd--;\n if(rowBegin<=rowEnd){\n for(int i=columnEnd;i>=columnBegin && cur!=null;i--){\n if(cur!=null){\n ans[rowEnd][i]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n rowEnd--;\n if(columnBegin<=columnEnd){\n for(int i=rowEnd;i>=rowBegin && cur!=null;i--){\n if(cur!=null){\n ans[i][columnBegin]=cur.val;\n }\n \n cur=cur.next;\n \n\n }\n \n }\n columnBegin++;\n \n }\n return ans;\n \n }\n}", "solution_c": "class Solution {\npublic:\n vector> spiralMatrix(int n, int m, ListNode* head) \n {\n\t\t// Create a matrix of n x m with values filled with -1.\n vector> spiral(n, vector(m, -1));\n int i = 0, j = 0;\n\t\t// Traverse the matrix in spiral form, and update with the values present in the head list.\n\t\t// If head reacher NULL pointer break out from the loop, and return the spiral matrix.\n while (head != NULL)\n {\n if (j < m)\n {\n while (head != NULL && j < m && spiral[i][j] == -1)\n {\n spiral[i][j] = head->val;\n head = head->next;\n j++;\n }\n if (head == NULL)\n break;\n i++;\n j--;\n }\n if (i < n)\n {\n while (head != NULL && i < n && spiral[i][j] == -1)\n {\n spiral[i][j] = head->val;\n head = head->next;\n i++;\n }\n i--;\n j--;\n }\n if (j >= 0)\n {\n while (head != NULL && j >= 0 && spiral[i][j] == -1)\n {\n spiral[i][j] = head->val;\n head = head->next;\n j--;\n }\n j++;\n i--;\n }\n if (i >= 0)\n {\n while (head != NULL && i >= 0 && spiral[i][j] == -1)\n {\n spiral[i][j] = head->val;\n head = head->next;\n i--;\n }\n i++;\n j++;\n }\n n--;\n m++;\n }\n\t\t// Rest values are itself -1.\n return spiral;\n }\n};" }, { "title": "Reverse Words in a String", "algo_input": "Given an input string s, reverse the order of the words.\n\nA word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.\n\nReturn a string of the words in reverse order concatenated by a single space.\n\nNote that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.\n\n \nExample 1:\n\nInput: s = \"the sky is blue\"\nOutput: \"blue is sky the\"\n\n\nExample 2:\n\nInput: s = \" hello world \"\nOutput: \"world hello\"\nExplanation: Your reversed string should not contain leading or trailing spaces.\n\n\nExample 3:\n\nInput: s = \"a good example\"\nOutput: \"example good a\"\nExplanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\ts contains English letters (upper-case and lower-case), digits, and spaces ' '.\n\tThere is at least one word in s.\n\n\n \nFollow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?\n", "solution_py": "class Solution:\n def split(self, s: str, delimiter=\" \") -> List[str]:\n start, end = 0, 0\n\n res = []\n for ch in s:\n if ch == delimiter:\n if start == end:\n start += 1\n else:\n res.append(s[start:end])\n start = end + 1\n \n end += 1\n \n if start != end:\n res.append(s[start:end])\n\n return res\n\n def reverse_list(self, ll: List[str]) -> List[str]:\n l, r = 0, len(ll) - 1\n\n while l < r:\n ll[l], ll[r] = ll[r], ll[l]\n l += 1\n r -= 1\n \n return ll\n\n def reverseWords(self, s: str) -> str:\n\n # split first\n splitted_str_list = self.split(s)\n\n # reverse splitted list\n reversed_str_list = self.reverse_list(splitted_str_list)\n\n # join an return\n return \" \".join(reversed_str_list)", "solution_js": "var reverseWords = function(s) {\n return s.split(\" \").filter(i => i).reverse().join(\" \");\n};", "solution_java": "class Solution {\n public String reverseWords(String s) {\n String[] arr = s.replaceAll(\"\\\\s{2,}\", \" \").split(\" \"); \n // splitting based on while spaces by replaceing spaces by single gap \n int n = arr.length;\n String temp = \"\";\n for(int i =0;i=s.length())\n break;\n\n int j=i+1;\n\n while(j int:\n \n def check(m):\n i = j = 0\n remove = set(removable[:m+1])\n while i < len(s) and j < len(p):\n if i in remove:\n i += 1\n continue\n if s[i] == p[j]:\n i += 1\n j += 1\n else:\n i += 1\n \n return j == len(p)\n \n \n # search interval is [lo, hi)\n lo, hi = 0, len(removable)+1\n \n while lo < hi:\n mid = (lo + hi) // 2\n if check(mid):\n lo = mid + 1\n else:\n hi = mid\n \n return lo if lo < len(removable) else lo-1", "solution_js": "var maximumRemovals = function(s, p, removable) {\n let arr = s.split('');\n \n const stillFunctions = (k) => {\n let result = [...arr];\n for(let i = 0; i < k; i++) {\n result[removable[i]] = '';\n }\n\n const isSubset = () => {\n let idx = 0;\n for(let c = 0; c < p.length; c++) {\n if(idx > result.length) return false;\n const next = result.indexOf(p[c], idx);\n if(next === -1) {\n return false;\n }\n idx = next + 1;\n }\n return true;\n }\n \n return isSubset();\n }\n\n let left = 0;\n let right = removable.length;\n \n while(left < right) {\n // Need to round up the midpoint since we are returning operation LENGTH i.e. ops+1\n const mid = Math.ceil((left+right) / 2);\n if(!stillFunctions(mid)) {\n right = mid -1;\n } else {\n left = mid;\n }\n }\n return left;\n};", "solution_java": "class Solution {\n public int maximumRemovals(String s, String p, int[] removable) {\n int left = 0, right = removable.length;\n\n while (left < right) {\n int middle = (right + left + 1) / 2;\n String afterRemoval = remove(s, removable, middle);\n if (isSubsequence(p, afterRemoval, p.length(), afterRemoval.length()))\n left = middle;\n else\n right = middle - 1;\n }\n\n return left;\n }\n\n private String remove(String s, int[] removable, int k) {\n char[] symbols = s.toCharArray();\n for (int i = 0; i < k; i++) {\n symbols[removable[i]] = Character.MIN_VALUE;\n }\n return String.valueOf(symbols);\n }\n\n private boolean isSubsequence(String subSequence, String word, int subSequenceChar, int wordChar) {\n if (subSequenceChar == 0) return true;\n if (wordChar == 0) return false;\n\n if (subSequence.charAt(subSequenceChar - 1) == word.charAt(wordChar - 1))\n return isSubsequence(subSequence, word, subSequenceChar - 1, wordChar - 1);\n\n return isSubsequence(subSequence, word, subSequenceChar, wordChar - 1);\n }\n}", "solution_c": "class Solution {\npublic:\n bool isSubSequence(string str1, string str2){\n int j = 0,m=str1.size(),n=str2.size();\n for (int i = 0; i < n && j < m; i++)\n if (str1[j] == str2[i])\n j++;\n return (j == m);\n }\n int maximumRemovals(string s, string p, vector& removable) {\n string copy=s;\n int left = 0, right =removable.size();\n while (left <= right) {\n int mid = (left+right)/2;\n for(int i=0;i int:\n if n == 1:\n return 3\n if n==2:\n return 8\n \"\"\"\n Keep track of last 2 digits\n ways to get ll = last combinations ending with p,l (l,l not allowed)\n ways to get lp = last combinations ending with l,p + p,l\n and so on\n \n finally account for adding A by the usual loop.\n \"\"\"\n \n combos_l_l = 1\n combos_l_p = 1\n combos_p_l = 1\n combos_p_p = 1\n\n MOD = 1000000007\n \n f = [0]*(n+1)\n f[0] = 1\n f[1] = 2\n f[2] = 4\n for i in range(2, n):\n combos_l_l_new = combos_p_l\n combos_l_p_new = combos_l_l + combos_p_l\n combos_p_l_new = combos_l_p + combos_p_p \n combos_p_p_new = combos_l_p + combos_p_p\n \n combos_l_l, combos_l_p, combos_p_l, combos_p_p = combos_l_l_new%MOD, combos_l_p_new%MOD, combos_p_l_new%MOD, combos_p_p_new %MOD\n \n f[i+1] = (combos_l_l + combos_l_p + combos_p_l + combos_p_p)%MOD\n \n\n total = f[-1]\n # print(f)\n for i in range(1,n+1):\n total += (f[i-1]*f[n-i]) \n \n return ( total ) % (MOD)\n ", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar checkRecord = function(n) {\n /**\n * P(n) = A(n - 1) + P(n - 1) + L(n - 1), n ≥ 2.\n * L(n) = A(n - 1) + P(n - 1) + A(n - 2) + P(n - 2), n ≥ 3.\n * A(n) = A(n - 1) + A(n - 2) + A(n - 3), n ≥ 4.\n */\n const m = 1000000007;\n const P = Array(n);\n const A = Array(n);\n const L = Array(n);\n A[0] = 1;\n L[0] = 1;\n P[0] = 1;\n A[1] = 2;\n A[2] = 4;\n L[1] = 3;\n for (let i = 1; i < n; i++) {\n P[i] = (A[i - 1] + L[i - 1] + P[i - 1]) % m;\n if (i >= 3) A[i] = (A[i - 1] + A[i - 2] + A[i - 3]) % m;\n if (i >= 2) L[i] = (A[i - 1] + P[i - 1] + A[i - 2] + P[i - 2]) % m;\n }\n return (P[n - 1] + A[n - 1] + L[n - 1]) % m;\n};", "solution_java": "class Solution {\n int mod=1000000000+7;\n public int checkRecord(int n) {\n int[][][] cache=new int[n+1][2][3];\n for(int i=0; i<=n; i++){\n for(int j=0; j<2; j++){\n for(int k=0; k<3; k++)cache[i][j][k]=-1;\n }\n }\n return populate(n, 0, 1, 2, cache);\n }\n public int populate(int n, int ptr, int aCount, int lCount, int[][][] cache){\n if(ptr>=n)return 1;\n if(cache[ptr][aCount][lCount]!=-1)return cache[ptr][aCount][lCount];\n long count=0;\n // Late\n if(lCount>0){\n count=populate(n, ptr+1, aCount, lCount-1, cache)%mod;\n }\n // Present\n count=(count+populate(n, ptr+1, aCount, 2, cache))%mod;\n // Absent\n if(aCount==1)count=(count+populate(n, ptr+1, aCount-1, 2, cache))%mod;\n cache[ptr][aCount][lCount]=(int)(count%mod);\n return cache[ptr][aCount][lCount];\n }\n}", "solution_c": "class Solution {\npublic:\n int mod = 1e9+7;\n int dp[100001][10][10];\n int recur(int abs,int late,int n){\n if(abs > 1){\n return 0;\n }\n if(late >= 3){\n return 0;\n }\n if(n == 0){\n return 1;\n \n }\n if(dp[n][late][abs] != -1) return dp[n][late][abs];\n \n int ans = 0;\n ans = (ans%mod + recur(abs+1,0,n-1)%mod)%mod;\n \n ans = (ans%mod + recur(abs,late+1,n-1)%mod)%mod;\n \n ans = (ans%mod + recur(abs,0,n-1)%mod)%mod;\n //This dp is running from n to 0 and is cut off if\n //absent is greater than 1 or late of consecutive is greater than\n //equal to 3.\n //Here in the first recursion i.e line 19 & line 23 late is made 0\n //to signify that the consecutive lates are stopped.***\n\n return dp[n][late][abs] = ans;\n }\n int checkRecord(int n) {\n for(int i=0;i<=100000;i++){\n for(int j=0;j<10;j++){\n for(int k=0;k<10;k++){\n dp[i][j][k] = -1;\n }\n }\n }\n return recur(0,0,n);\n }\n};" }, { "title": "Design HashSet", "algo_input": "Design a HashSet without using any built-in hash table libraries.\n\nImplement MyHashSet class:\n\n\n\tvoid add(key) Inserts the value key into the HashSet.\n\tbool contains(key) Returns whether the value key exists in the HashSet or not.\n\tvoid remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.\n\n\n \nExample 1:\n\nInput\n[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\nOutput\n[null, null, null, true, false, null, true, null, false]\n\nExplanation\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)\n\n \nConstraints:\n\n\n\t0 <= key <= 106\n\tAt most 104 calls will be made to add, remove, and contains.\n\n", "solution_py": "class MyHashSet:\n\n def __init__(self):\n self.hash_list = [0]*10000000\n\n def add(self, key: int) -> None:\n self.hash_list[key]+=1\n\n def remove(self, key: int) -> None:\n self.hash_list[key] = 0\n\n def contains(self, key: int) -> bool:\n if self.hash_list[key] > 0:\n return True\n return False", "solution_js": "var MyHashSet = function() {\n \n // Really you should just \n // Make your own object, but instead\n // we have attached ourself to the \n // `this` object which then becomes our hashmap.\n \n // What you should instead do is this:\n // this.hash_map = {}\n // And then update our following functions\n};\n\nMyHashSet.prototype.add = function(key) {\n \n // Constant Time\n // Linear Space | To the size of the input key\n // You can access objects using array notation\n\n this[key] = null;\n};\n\nMyHashSet.prototype.remove = function(key) {\n \n // Constant Time\n // Constant Space\n // You can access objects using array notation\n // Here we use the delete keyword.\n\n delete this[key]\n};\n\nMyHashSet.prototype.contains = function(key) {\n \n // Constant Time\n // Constant Space\n // This just asks if the property exists\n\n return this.hasOwnProperty(key)\n};", "solution_java": "class MyHashSet {\n\tArrayList> list;\n\tint size = 100;\n\n\tpublic MyHashSet() {\n\t\tlist = new ArrayList<>(size);\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tlist.add(new LinkedList());\n\t\t}\n\t}\n\n\tpublic int hash(int key) {\n\t\treturn key % list.size();\n\t}\n\n\tpublic int search(int key) {\n\t\tint i = hash(key);\n\n\t\tLinkedList temp = list.get(i);\n\t\tint ans = -1;\n\n\t\tfor (int j = 0; j < temp.size(); j++) {\n\t\t\tif (key == temp.get(j)) {\n\t\t\t\treturn j;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n\t}\n\n\tpublic void add(int key) {\n\t\tif (search(key) == -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).add(key);\n\t\t}\n\t}\n\n\tpublic void remove(int key) {\n\t\tif (search(key) != -1) {\n\t\t\tint i = hash(key);\n\t\t\tlist.get(i).remove(Integer.valueOf(key));\n\t\t}\n\t}\n\n\tpublic boolean contains(int key) {\n\t\treturn search(key) != -1;\n\t}\n}", "solution_c": "class MyHashSet {\n vector v;\npublic:\n MyHashSet() {\n\n }\n\n void add(int key) {\n auto it = find(v.begin(), v.end(), key);\n if(it == v.end()){\n v.push_back(key);\n }\n\n }\n\n void remove(int key) {\n auto it = find(v.begin(), v.end(), key);\n if(it != v.end()){\n v.erase(it);\n }\n }\n\n bool contains(int key) {\n return find(v.begin(), v.end(), key) != v.end();\n }\n};" }, { "title": "Minimum Sum of Four Digit Number After Splitting Digits", "algo_input": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.\n\n\n\tFor example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].\n\n\nReturn the minimum possible sum of new1 and new2.\n\n \nExample 1:\n\nInput: num = 2932\nOutput: 52\nExplanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\n\n\nExample 2:\n\nInput: num = 4009\nOutput: 13\nExplanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n\n\n \nConstraints:\n\n\n\t1000 <= num <= 9999\n\n", "solution_py": "class Solution:\n def minimumSum(self, num: int) -> int:\n s=list(str(num))\n s.sort()\n return int(s[0]+s[2])+int(s[1]+s[3])", "solution_js": "var minimumSum = function(num) {\n let numbers = []\n for(let i = 0; i<4; i++){\n numbers.push(~~num % 10)\n num /= 10\n }\n const sorted = numbers.sort((a,b) => b - a)\n return sorted[0] + sorted[1] + (10 *( sorted[2] + sorted[3]))\n};", "solution_java": "class Solution\n{\n public int minimumSum(int num)\n {\n int[] dig = new int[4]; // For each digit\n int cur = 0;\n while(num > 0) // Getting each digit\n {\n dig[cur++] = num % 10;\n num /= 10;\n }\n Arrays.sort(dig); // Ascending order\n int num1 = dig[0] * 10 + dig[2]; // 1st and 3rd digit\n int num2 = dig[1] * 10 + dig[3]; // 2nd and 4th digit\n return num1 + num2;\n }\n}", "solution_c": "class Solution{\npublic:\n int minimumSum(int num){\n string s = to_string(num);\n sort(s.begin(), s.end());\n int res = (s[0] - '0' + s[1] - '0') * 10 + s[2] - '0' + s[3] - '0';\n return res;\n }\n};" }, { "title": "Can Make Arithmetic Progression From Sequence", "algo_input": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.\n\nGiven an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.\n\n \nExample 1:\n\nInput: arr = [3,5,1]\nOutput: true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.\n\n\nExample 2:\n\nInput: arr = [1,2,4]\nOutput: false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.\n\n\n \nConstraints:\n\n\n\t2 <= arr.length <= 1000\n\t-106 <= arr[i] <= 106\n\n", "solution_py": "class Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n check = arr[0] - arr[1]\n for i in range(len(arr)-1):\n if arr[i] - arr[i+1] != check:\n return False\n return True", "solution_js": "var canMakeArithmeticProgression = function(arr) {\n arr.sort(function(a,b){return a-b});\n var dif = arr[1] - arr[0];\n for(var i=2;i& arr) {\n sort(arr.begin() , arr.end());\n int diff = arr[1] - arr[0];\n for(int i=1;i int:\n # T.C = O(n) S.C = O(1)\n actualsum = 0\n currentsum = 0\n i = 1\n for num in nums:\n currentsum += num\n actualsum += i\n i += 1\n \n return actualsum - currentsum", "solution_js": "var missingNumber = function(nums) {\n return ((1 + nums.length)*nums.length/2) - nums.reduce((a,b) => a+b)\n};", "solution_java": "// Approach 1: Find diff\n\nclass Solution {\n public int missingNumber(int[] nums) {\n int n = nums.length;\n int expectedSum = (n * (n + 1)) / 2;\n for (int num : nums)\n expectedSum -= num;\n return expectedSum;\n }\n}\n\n// Approach 2: XOR\nclass Solution {\n public int missingNumber(int[] nums) {\n int xor1 = 0;\n for (int i = 1; i <= nums.length; i++)\n xor1 = xor1 ^ i;\n\n int xor2 = 0;\n for (int num : nums)\n xor2 = xor2 ^ num;\n return xor1 ^ xor2;\n }\n}\n\n// Approach 3: Cyclic sort\nclass Solution {\n public int missingNumber(int[] nums) {\n \n int i = 0;\n while (i < nums.length) {\n\n if (nums[i] != i && nums[i] < nums.length)\n swap(i, nums[i], nums);\n else\n i += 1;\n }\n \n for (int j = 0; j < nums.length; j++) {\n if (nums[j] != j)\n return j;\n }\n return nums.length;\n }\n \n private void swap(int i, int j, int[] nums) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}", "solution_c": "class Solution {\npublic:\n int missingNumber(vector& nums) {\n int n=nums.size();\n long sum=n*(n+1)/2;\n long temp=0;\n for(int i=0;i List[List[int]]:\n # Purpose: find the cells that allow rain flow into the ocean\n # Method: DFS\n # Intuition: start from each border, check cell and neb, if OK, append to res\n \n # init: res, vis (pac, atl), ROW, COL\n res = []\n pac = set()\n atl = set()\n ROW = len(heights)\n COL = len(heights[0])\n\n # top and bottom row\n for col in range(COL):\n self.dfs(0, col, pac, heights[0][col], heights)\n self.dfs(ROW-1, col, atl, heights[ROW-1][col], heights)\n\n # left and right col\n for row in range(ROW):\n self.dfs(row, 0, pac, heights[row][0], heights)\n self.dfs(row, COL-1, atl, heights[row][COL-1], heights)\n\n # append to res\n for row in range(ROW):\n for col in range(COL):\n if (row, col) in pac and (row, col) in atl:\n res.append([row, col])\n\n # return\n return res\n\n \n def dfs(self, row, col, vis, prev, heights):\n # hard-code definition\n try:\n cur = heights[row][col]\n except:\n pass\n\n # inbound, unvisited, increase from ocean\n if (0<=row= prev) \\\n and ((row, col) not in vis):\n\n # add to visited \n vis.add((row, col))\n\n # check nebs\n self.dfs(row+1, col, vis, cur, heights)\n self.dfs(row-1, col, vis, cur, heights)\n self.dfs(row, col+1, vis, cur, heights)\n self.dfs(row, col-1, vis, cur, heights)", "solution_js": "`/**\n * @param {number[][]} heights\n * @return {number[][]}\n */\nvar pacificAtlantic = function(heights) {\n let atlantic = new Set();\n let pacific = new Set();\n let rows = heights.length;\n let cols = heights[0].length;\n\n for (let c = 0; c < cols; c++) {\n explore(heights, 0, c, pacific, heights[0][c]); // dfs from top row\n explore(heights, rows - 1, c, atlantic, heights[rows - 1][c]); // dfs from bottom row\n }\n\n for (let r = 0; r < rows; r++) {\n explore(heights, r, 0, pacific, heights[r][0]); // dfs from left most column\n explore(heights, r, cols - 1, atlantic, heights[r][cols - 1]); // dfs from right most column\n }\n\n // check if water can flow to both atlantic and pacific ocean.\n let res = [];\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n let pos = r + ',' + c;\n if (atlantic.has(pos) && pacific.has(pos)) {\n res.push([r, c]);\n }\n }\n }\n\n return res;\n};\n\nfunction explore(heights, r, c, visited, prevHeight) {\n let rowInbound = 0 <= r && r < heights.length;\n let colInbound = 0 <= c && c < heights[0].length;\n if (!rowInbound || !colInbound) return;\n\n // height must be higher than prev height. water can only flow downwards not upwards. duh.\n // if it's the first value then it's just the same value so it's not less than so it will not return.\n if (heights[r][c] < prevHeight) return;\n\n let pos = r + ',' + c;\n if (visited.has(pos)) return;\n visited.add(pos)\n\n explore(heights, r + 1, c, visited, heights[r][c]) // below\n explore(heights, r - 1, c, visited, heights[r][c]) // above\n explore(heights, r, c + 1, visited, heights[r][c]) // right\n explore(heights, r, c - 1, visited, heights[r][c]) // left\n}`", "solution_java": "class Solution {\n public List> pacificAtlantic(int[][] heights) {\n if (heights == null) return null;\n if (heights.length == 0) return null;\n if (heights[0].length == 0) return null;\n\n /** */\n boolean [][] po = new boolean[heights.length][heights[0].length];\n boolean [][] ao = new boolean[heights.length][heights[0].length];\n\n for (int i = 0; i < heights[0].length; i ++) {\n dfs(heights, i, 0, 0, po); // top\n dfs(heights, i, heights.length - 1, 0, ao); // bottom\n }\n\n for (int i = 0; i < heights.length; i ++) {\n dfs(heights, 0, i, 0, po); // left\n dfs(heights, heights[0].length - 1, i, 0, ao); // right\n }\n\n List> ans = new ArrayList<>();\n for (int i = 0; i < heights.length; i ++) {\n for (int j = 0; j < heights[i].length; j ++) {\n if (ao[i][j] && po[i][j]) {\n ArrayList ar = new ArrayList<>();\n ar.add(i);\n ar.add(j);\n ans.add(ar);\n }\n }\n }\n\n return ans;\n }\n\n private void dfs(int[][] heights, int x, int y, int h, boolean[][] v) {\n if (x < 0 || y < 0 || x >= heights[0].length || y >= heights.length) return;\n if (v[y][x] || heights[y][x] < h) return;\n v[y][x] = true;\n /** left */\n dfs(heights, x - 1, y, heights[y][x], v);\n\n /** right */\n dfs(heights, x + 1, y, heights[y][x], v);\n\n /** up */\n dfs(heights, x, y - 1, heights[y][x], v);\n\n /** down */\n dfs(heights, x, y + 1, heights[y][x], v);\n }\n}", "solution_c": "class Solution {\npublic:\n void dfs(vector>& heights,vector>&v,int i,int j)\n {\n int m=heights.size();\n int n=heights[0].size();\n v[i][j]=true;\n if(i-1>=0&&v[i-1][j]!=true&&heights[i-1][j]>=heights[i][j])\n {\n dfs(heights,v,i-1,j);\n }\n if(i+1=heights[i][j])\n {\n dfs(heights,v,i+1,j);\n }\n if(j-1>=0&&v[i][j-1]!=true&&heights[i][j-1]>=heights[i][j])\n {\n dfs(heights,v,i,j-1);\n }\n if(j+1=heights[i][j])\n {\n dfs(heights,v,i,j+1);\n }\n }\n vector> pacificAtlantic(vector>& heights) {\n int m=heights.size();\n vector>ans;\n if(m==0)\n {\n return ans;\n }\n int n=heights[0].size();\n if(n==0)\n {\n return ans;\n }\n vector>pa(m,vector(n));\n vector>at(m,vector(n));\n for(int i=0;ip;\n for(int j=0;j bool:\n d = Counter(num)\n for i in range(len(num)):\n if int(num[i])!=d.get(str(i), 0):\n return False\n return True", "solution_js": "var digitCount = function(num) { \n const res = [...num].filter((element, index) => {\n const reg = new RegExp(index, \"g\");\n const count = (num.match(reg) || []).length;\n \n return Number(element) === count\n })\n \n return res.length === num.length \n};", "solution_java": "class Solution {\n public boolean digitCount(String num) {\n int[] freqArr = new int[10]; // n = 10 given in constraints;\n \n \n for(char ch : num.toCharArray()){\n freqArr[ch-'0']++;\n }\n \n for(int i=0;i mpp;\n int n= num.length();\n for(auto it:num){\n int x = it - '0';\n mpp[x]++; // Store the frequency of the char as a number\n }\n for(int i=0;i str:\n # Store the alphabets and the numerics from the string in a seperat arrays\n alpha = []\n num = []\n # Initiate a res variable to store the resultant string\n res = ''\n \n for i in s:\n if i.isalpha():\n alpha.append(i)\n else:\n num.append(i)\n \n # It's not possible to create a permutation if the absolute difference b/w len(alpha) and len(num) > 1.\n if abs(len(alpha)-len(num)) > 1: return ''\n \n # Use Zip to create list of tuples.\n # For ex:- if alpha = ['a','b'] and num = ['1', '2'] then,\n # zip(alpha, num) = [('a', '1'), ('b', '2')]\n for ch, n in zip(alpha, num):\n res += (ch+n)\n \n if len(alpha) > len(num):\n res += alpha[-1]\n if len(num) > len(alpha):\n res = num[-1] + res\n \n return res", "solution_js": "var reformat = function(s) {\n let letter=[], digit=[];\n for(let i=0; i=0 && s[i]<=9? digit.push(s[i]): letter.push(s[i]);\n }\n\t// impossible to reformat\n if(Math.abs(letter.length-digit.length)>=2){return \"\"}\n \n let i=0, output=\"\";\n while(i ch = new ArrayList<>();\n List d = new ArrayList<>();\n \n for(char c : s.toCharArray()){\n if(c >= 'a' && c <= 'z')ch.add(c);\n else d.add(c);\n }\n \n if(Math.abs(d.size() - ch.size()) > 1) return \"\";\n \n StringBuilder str = new StringBuilder();\n \n for(int i = 0; i < s.length(); i++){\n \n if(!ch.isEmpty() || !d.isEmpty()){\n if(ch.size() > d.size())\n str.append(appender(ch,d));\n else \n str.append(appender(d,ch));\n }\n else{\n break;\n }\n }\n \n return new String(str);\n \n }\n \n public String appender(List first,List second){\n \n StringBuilder str = new StringBuilder();\n \n if(!first.isEmpty()){\n str.append(first.get(0));\n first.remove(0);\n }\n if(!second.isEmpty()){\n str.append(second.get(0));\n second.remove(0);\n }\n \n return new String(str);\n }\n}", "solution_c": "class Solution {\npublic:\n string reformat(string s) {\n string dg,al;\n for(auto&i:s)isdigit(i)?dg+=i:al+=i;\n if(abs((int)size(dg)-(int)size(al))>1) return \"\";\n int i=0,j=0,k=0;\n string ans(size(s),' ');\n bool cdg=size(dg)>size(al);\n while(k int:\n \n count = maxCount = 0\n \n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n else:\n maxCount = max(count, maxCount)\n count = 0\n \n return max(count, maxCount)", "solution_js": "var findMaxConsecutiveOnes = function(nums) {\n let count =0\n let max =0\n for(let i=0; inew_max){\n new_max = max;\n }\n max = 0;\n }\n }\n if(max& nums)\n {\n int curr_count = 0;\n int max_count = 0;\n int i = 0;\n while(i < nums.size())\n {\n if(nums[i] == 1)\n {\n curr_count += 1;\n if(max_count < curr_count)\n max_count = curr_count; \n }\n \n else\n curr_count = 0;\n i++;\n }\n return max_count;\n }\n};" }, { "title": "Monotonic Array", "algo_input": "An array is monotonic if it is either monotone increasing or monotone decreasing.\n\nAn array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].\n\nGiven an integer array nums, return true if the given array is monotonic, or false otherwise.\n\n \nExample 1:\n\nInput: nums = [1,2,2,3]\nOutput: true\n\n\nExample 2:\n\nInput: nums = [6,5,4,4]\nOutput: true\n\n\nExample 3:\n\nInput: nums = [1,3,2]\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-105 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] >= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n counter = 0\n for i in range(len(nums) - 1):\n if nums[i] <= nums[i + 1]:\n counter += 1\n if counter == len(nums) - 1:\n return True\n return False", "solution_js": "var isMonotonic = function(nums) {\n let increasingCount = 0;\n let decreasingCount = 0;\n for(let i = 1; i < nums.length; i++){\n if(nums[i] > nums[i-1]){\n increasingCount++;\n }else if(nums[i] < nums[i-1]){\n decreasingCount++;\n }\n }\n \n return !(increasingCount && decreasingCount);\n};", "solution_java": "class Solution {\n public boolean isMonotonic(int[] nums) {\n if(nums[0]=nums[i+1])) return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isMonotonic(vector& nums) {\n auto i = find_if_not(begin(nums), end(nums), [&](int a) {return a == nums.front();});\n auto j = find_if_not(rbegin(nums), rend(nums), [&](int a) {return a == nums.back();});\n return is_sorted(--i, end(nums)) or is_sorted(--j, rend(nums));\n }\n};" }, { "title": "Maximum Ascending Subarray Sum", "algo_input": "Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.\n\nA subarray is defined as a contiguous sequence of numbers in an array.\n\nA subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.\n\n \nExample 1:\n\nInput: nums = [10,20,30,5,10,50]\nOutput: 65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n\n\nExample 2:\n\nInput: nums = [10,20,30,40,50]\nOutput: 150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n\n\nExample 3:\n\nInput: nums = [12,17,15,13,10,11,12]\nOutput: 33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t1 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n count=nums[0]\n final=nums[0]\n for i in range(1,len(nums)):\n if nums[i]>nums[i-1]:\n count+=nums[i]\n else:\n count=nums[i]\n final=max(final,count)\n return final", "solution_js": "var maxAscendingSum = function(nums) {\n const subarray = nums.reduce((acc, curr, index) => {\n curr > nums[index - 1] ? acc[acc.length - 1] += curr : acc.push(curr);\n return acc;\n }, []);\n\n return Math.max(...subarray);\n};", "solution_java": "class Solution {\n public int maxAscendingSum(int[] nums) {\n int res = nums[0],temp = nums[0];\n for(int i = 1;i nums[i-1])\n temp+=nums[i];\n else\n temp = nums[i];\n res = Math.max(res,temp);\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxAscendingSum(vector& nums) {\n int max_sum = nums[0], curr = nums[0];\n for (int i = 1; i < nums.size(); i++) {\n if (nums[i-1] < nums[i]) {\n curr += nums[i];\n }\n else {\n max_sum = max(max_sum, curr);\n curr = nums[i];\n }\n }\n return max(max_sum, curr);\n }\n};" }, { "title": "Maximum Trailing Zeros in a Cornered Path", "algo_input": "You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.\n\nA cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.\n\nThe product of a path is defined as the product of all the values in the path.\n\nReturn the maximum number of trailing zeros in the product of a cornered path found in grid.\n\nNote:\n\n\n\tHorizontal movement means moving in either the left or right direction.\n\tVertical movement means moving in either the up or down direction.\n\n\n \nExample 1:\n\nInput: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput: 3\nExplanation: The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.\n\n\nExample 2:\n\nInput: grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput: 0\nExplanation: The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 105\n\t1 <= m * n <= 105\n\t1 <= grid[i][j] <= 1000\n\n", "solution_py": "import numpy as np\n\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n A = np.array(grid)\n def cumdivs(d):\n D = sum(A % d**i == 0 for i in range(1, 10))\n return D.cumsum(0) + D.cumsum(1) - D\n return max(np.minimum(cumdivs(2), cumdivs(5)).max()\n for _ in range(4)\n if [A := np.rot90(A)])", "solution_js": "var maxTrailingZeros = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n\n const postfixCols = [];\n\n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n const num = grid[i][j];\n\n if (postfixCols[j] == null) postfixCols[j] = { 2: 0, 5: 0 };\n\n postfixCols[j][\"2\"] += getCount(num, 2);\n postfixCols[j][\"5\"] += getCount(num, 5);\n }\n }\n\n const prefixCols = [];\n\n for (let j = 0; j < n; ++j) {\n prefixCols[j] = { 0: 0, 2: 0, 5: 0 };\n }\n\n let maxZeros = 0;\n\n for (let i = 0; i < m; ++i) {\n const postfixRow = { 0: 0, 2: 0, 5: 0 };\n\n for (let j = n - 1; j >= 0; --j) {\n const num = grid[i][j];\n\n postfixRow[\"2\"] += getCount(num, 2);\n postfixRow[\"5\"] += getCount(num, 5);\n }\n\n let prefixRow = { 0: 0, 2: 0, 5: 0 };\n\n for (let j = 0; j < n; ++j) {\n const num = grid[i][j];\n\n const twoCount = getCount(num, 2);\n const fiveCount = getCount(num, 5);\n\n postfixRow[\"2\"] -= twoCount;\n postfixCols[j][\"2\"] -= twoCount;\n\n postfixRow[\"5\"] -= fiveCount;\n postfixCols[j][\"5\"] -= fiveCount;\n\n // down-right => prefixCol + postfixRow\n const downRight = calculateTrailingZeros(prefixCols[j], postfixRow, num);\n // down-left => prefixCol + prefixRow\n const downLeft = calculateTrailingZeros(prefixCols[j], prefixRow, num);\n // up-right => postfixCols + postfixRow\n const upRight = calculateTrailingZeros(postfixCols[j], postfixRow, num);\n // up-left => postfixCols + prefixRow\n const upLeft = calculateTrailingZeros(postfixCols[j], prefixRow, num);\n\n maxZeros = Math.max(maxZeros, downRight, downLeft, upRight, upLeft);\n\n prefixRow[\"2\"] += twoCount;\n prefixCols[j][\"2\"] += twoCount;\n\n prefixRow[\"5\"] += fiveCount;\n prefixCols[j][\"5\"] += fiveCount;\n }\n }\n\n return maxZeros;\n\n function calculateTrailingZeros(col, row, currNum) {\n let twosCount = 0;\n let fivesCount = 0;\n let zerosCount = 0;\n\n twosCount = row[\"2\"] + col[\"2\"];\n fivesCount = row[\"5\"] + col[\"5\"];\n\n twosCount += getCount(currNum, 2);\n fivesCount += getCount(currNum, 5);\n return Math.min(twosCount, fivesCount);\n }\n\n function getCount(num, divisor) {\n let count = 0;\n\n while (num % divisor === 0) {\n ++count;\n num /= divisor;\n }\n\n return count;\n }\n};", "solution_java": "class Solution {\n public int maxTrailingZeros(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n int[][][] dph = new int[m][n][3];\n int[][][] dpv = new int[m][n][3];\n int hmax0 = 0;\n int vmax0 = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int curr = grid[i][j];\n int two = 0;\n int five = 0;\n if (j >= 1) {\n two = dph[i][j-1][1];\n five = dph[i][j-1][2];\n }\n while (curr > 0 && curr % 2 == 0) {\n two++;\n curr /= 2;\n }\n while (curr > 0 && curr % 5 == 0) {\n five++;\n curr /= 5;\n }\n dph[i][j][1] = two;\n dph[i][j][2] = five;\n dph[i][j][0] = Math.min(dph[i][j][1], dph[i][j][2]);\n }\n hmax0 = Math.max(hmax0, dph[i][n-1][0]);\n }\n \n for (int j = 0; j < n; j++) {\n for (int i = 0; i < m; i++) {\n int curr = grid[i][j];\n int two = 0;\n int five = 0;\n if (i >= 1) {\n two = dpv[i-1][j][1];\n five = dpv[i-1][j][2];\n }\n while (curr > 0 && curr % 2 == 0) {\n two++;\n curr /= 2;\n }\n while (curr > 0 && curr % 5 == 0) {\n five++;\n curr /= 5;\n }\n dpv[i][j][1] = two;\n dpv[i][j][2] = five;\n dpv[i][j][0] = Math.min(dpv[i][j][1], dpv[i][j][2]);\n }\n vmax0 = Math.max(vmax0, dpv[m-1][j][0]);\n }\n\t\t\n int res = Math.max(vmax0, hmax0);\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int otwo = dph[i][j][1];\n int ofive = dph[i][j][2];\n \n int res1 = 0;\n if (i >= 1) {\n int ntwo = otwo + dpv[i-1][j][1];\n int nfive = ofive + dpv[i-1][j][2];\n res1 = Math.min(ntwo, nfive);\n }\n \n int res2 = 0;\n if (i < m - 1) {\n int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];\n int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];\n res2 = Math.min(ntwo, nfive);\n }\n res = Math.max(res, res1);\n res = Math.max(res, res2);\n }\n\t\t\t\n\t\t\tfor (int j = n - 1; j >= 0; j--) {\n int otwo = 0;\n int ofive = 0;\n if (j >= 1) {\n otwo = dph[i][n-1][1] - dph[i][j-1][1];\n ofive = dph[i][n-1][2] - dph[i][j-1][2];\n } else {\n otwo = dph[i][n-1][1];\n ofive = dph[i][n-1][2];\n }\n \n int res1 = 0;\n if (i >= 1) {\n int ntwo = otwo + dpv[i-1][j][1];\n int nfive = ofive + dpv[i-1][j][2];\n res1 = Math.min(ntwo, nfive);\n }\n \n int res2 = 0;\n if (i < m - 1) {\n int ntwo = otwo + dpv[m-1][j][1] - dpv[i][j][1];\n int nfive = ofive + dpv[m-1][j][2] - dpv[i][j][2];\n res2 = Math.min(ntwo, nfive);\n }\n \n res = Math.max(res, res1);\n res = Math.max(res, res2);\n }\n }\n\t\t\n return res;\n }\n}", "solution_c": "array operator+(const array &l, const array &r) { return { l[0] + r[0], l[1] + r[1] }; }\narray operator-(const array &l, const array &r) { return { l[0] - r[0], l[1] - r[1] }; }\nint pairs(const array &p) { return min(p[0], p[1]); }\n\nclass Solution {\npublic:\nint factors(int i, int f) {\n return i % f ? 0 : 1 + factors(i / f, f);\n}\nint maxTrailingZeros(vector>& grid) {\n int m = grid.size(), n = grid[0].size(), res = 0;\n vector>> h(m, vector>(n + 1)), v(m + 1, vector>(n));\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n array f25 = { factors(grid[i][j], 2), factors(grid[i][j], 5) };\n v[i + 1][j] = v[i][j] + f25;\n h[i][j + 1] = h[i][j] + f25;\n }\n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j) {\n auto v1 = v[i + 1][j], v2 = v[m][j] - v[i][j];\n auto h1 = h[i][j], h2 = h[i][n] - h[i][j + 1];\n res = max({res, pairs(v1 + h1), pairs(v1 + h2), pairs(v2 + h1), pairs(v2 + h2)});\n }\n return res;\n}\n};" }, { "title": "Path Sum II", "algo_input": "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.\n\nA root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.\n\n \nExample 1:\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: [[5,4,11,2],[5,8,4,5]]\nExplanation: There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n\n\nExample 2:\n\nInput: root = [1,2,3], targetSum = 5\nOutput: []\n\n\nExample 3:\n\nInput: root = [1,2], targetSum = 0\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 5000].\n\t-1000 <= Node.val <= 1000\n\t-1000 <= targetSum <= 1000\n\n", "solution_py": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\n res = []\n def dfs(v, path, pathsum):\n if not v:\n return\n path.append(v.val)\n pathsum += v.val\n if not v.left and not v.right and pathsum == targetSum:\n res.append(path[:])\n dfs(v.left, path, pathsum)\n dfs(v.right, path, pathsum)\n path.pop()\n dfs(root, [], 0)\n return res", "solution_js": "var pathSum = function(root, targetSum) {\n const paths = [];\n\n function dfs(root, sum, curr = []) {\n if (!root) return;\n\n const newCurr = [...curr, root.val];\n if (!root.left && !root.right && sum === root.val) return paths.push(newCurr);\n\n dfs(root.left, sum - root.val, newCurr);\n dfs(root.right, sum - root.val, newCurr);\n }\n\n dfs(root, targetSum);\n return paths;\n};", "solution_java": "class Solution \n{\n public List> pathSum(TreeNode root, int targetSum) \n {\n List> ans = new ArrayList<>();\n pathSum(root, targetSum, new ArrayList<>(), ans);\n return ans;\n }\n \n public void pathSum(TreeNode root, int targetSum, List path, List> ans)\n {\n if(root == null)\n return;\n path.add(root.val);\n if(root.left == null && root.right == null && targetSum == root.val)//leaf node that completes path\n {\n ans.add(new ArrayList(path));// we use new ArrayList because if we don't the originaly List is added which is mutable, if we add a copy that's not mutable.\n }\n else\n {\n pathSum(root.left, targetSum-root.val, path, ans);\n pathSum(root.right, targetSum-root.val, path, ans);\n }\n path.remove(path.size()-1); //removal of redundant nodes\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 vector> v;\n void helper(vector& t, int target, TreeNode* root){\n if(root==NULL){\n return;\n }\n if(root->left==NULL&&root->right==NULL&&target==root->val){\n t.push_back(root->val);\n v.push_back(t);\n t.pop_back();\n return;\n }\n target=target-root->val;\n t.push_back(root->val);\n helper(t,target,root->left);\n helper(t,target,root->right);\n t.pop_back();\n\n //cout<val<<\" \"<> pathSum(TreeNode* root, int targetSum) {\n vector t;\n helper(t,targetSum,root);\n return v;\n }\n};" }, { "title": "Gas Station", "algo_input": "There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].\n\nYou have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.\n\nGiven two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique\n\n \nExample 1:\n\nInput: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput: 3\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n\n\nExample 2:\n\nInput: gas = [2,3,4], cost = [3,4,3]\nOutput: -1\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n\n\n \nConstraints:\n\n\n\tn == gas.length == cost.length\n\t1 <= n <= 105\n\t0 <= gas[i], cost[i] <= 104\n\n", "solution_py": "class Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n deltas = [x-y for x, y in zip(gas, cost)]\n n = len(deltas)\n deltas = deltas + deltas\n cursum, curi = 0, 0\n maxsum, maxi = 0, 0\n for i, delta in enumerate(deltas):\n cursum = max(0, cursum + delta)\n if cursum == 0:\n curi = i+1\n if cursum > maxsum:\n maxi = curi\n maxsum = cursum\n cursum = 0\n for i in range(n):\n cursum += deltas[(maxi+i)%n]\n if cursum < 0: return -1\n return maxi", "solution_js": "var canCompleteCircuit = function(gas, cost) {\n const len = gas.length;\n // scan forward from the current index\n const scan = (i) => {\n let numTries = 0;\n let tank = 0;\n let c = 0;\n while (numTries <= len) {\n tank -= c;\n if (tank < 0) return -1;\n // if we made it back around, and we have gas, return the index, we made it!\n if (numTries === len && tank >= 0) {\n return i;\n }\n tank += gas[i];\n c = cost[i];\n i++;\n if (i === len) i = 0; // if we hit the end, bounce back to zero\n numTries++;\n }\n return -1;\n }\n\n for (let i = 0; i < len; i++) {\n if (!gas[i]) continue; // no gas / zero gas so let's just move on\n let index = scan(i);\n if (~index) return index; // if it's not -1, return it\n }\n\n return -1;\n};", "solution_java": "class Solution {\n public int canCompleteCircuit(int[] gas, int[] cost) {\n // *Upvote will be appreciated*\n int totalFuel = 0;\n int totalCost = 0;\n int n = gas.length;\n for(int i = 0; i < n; i++) {\n totalFuel += gas[i];\n }\n for(int i = 0; i < n; i++) {\n totalCost += cost[i];\n }\n // if totalfuel < totalCost then It is not possible to tavel\n if(totalFuel < totalCost) {\n return -1;\n }\n\n // It is greather then There may be an Answer\n int start = 0;\n int currFuel = 0;\n for(int i = 0; i < n; i++) {\n currFuel += (gas[i]-cost[i]);\n if(currFuel < 0) { // It Current Fuel is less than 0 mean we can't star from that index\n start = i+1; // so we start from next index\n currFuel = 0;\n }\n }\n return start;\n }\n}", "solution_c": "class Solution {\npublic:\n int canCompleteCircuit(vector& gas, vector& cost) {\n int n = gas.size();\n int start = -1;\n\n int sum = 0 , gastillnow = 0;\n for(int i = 0 ; i < 2*n ; i++){\n if(start == i%n){\n return i%n;\n }\n if(gas[i%n] + gastillnow >= cost[i%n]){ // we can start from this index\n if(start==-1) start = i;\n gastillnow += gas[i%n]-cost[i%n];\n }else if(gastillnow + gas[i%n] < cost[i%n]){ // previous start index was wrong we have to start from another\n start = -1;\n gastillnow = 0;\n }\n }\n return -1;\n }\n};" }, { "title": "Number of Segments in a String", "algo_input": "Given a string s, return the number of segments in the string.\n\nA segment is defined to be a contiguous sequence of non-space characters.\n\n \nExample 1:\n\nInput: s = \"Hello, my name is John\"\nOutput: 5\nExplanation: The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]\n\n\nExample 2:\n\nInput: s = \"Hello\"\nOutput: 1\n\n\n \nConstraints:\n\n\n\t0 <= s.length <= 300\n\ts consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\".\n\tThe only space character in s is ' '.\n\n", "solution_py": "class Solution:\n def countSegments(self, s: str) -> int:\n return len(s.split())", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar countSegments = function(s) {\n return s.trim() ? s.trim().split(/\\s+/).length : 0\n};", "solution_java": "class Solution {\n public int countSegments(String s) {\n int length = 0;\n boolean flag = false;\n\n for(Character c : s.toCharArray()) {\n if(c == ' ' && flag) {\n length++;\n flag = !flag;\n } else if(c != ' ') {\n flag = true;\n }\n }\n\n return flag ? length + 1 : length;\n }\n}", "solution_c": "class Solution {\npublic:\n int countSegments(string s) {\n if(s==\"\")\n return 0;\n int res=0,flag=0;\n for(int i=0;i 0:\n\t\t\t# smallest number in sorted nums with freq > 0 to start a sequence [v, v+1, v+2 ... , v+k-1]\n for v in nums: \n if freq[v] > 0: \n for i in range(k):\n if freq[v+i] <= 0:\n return False\n else:\n freq[v+i] -= 1\n return True", "solution_js": "var isPossibleDivide = function(nums, k) {\n if(nums.length % k) {\n return false;\n }\n\n nums.sort((a, b) => a - b);\n\n let numberOfArrays = nums.length / k, index = 0, dp = Array(numberOfArrays).fill(null).map(() => []);\n\n dp[0].push(nums[0]);\n\n for(let i = 1; i < nums.length; i++) {\n if(nums[i] === nums[i - 1]) {\n if(index === numberOfArrays - 1) {\n return false;\n }\n index++;\n }\n else {\n index = 0;\n while(dp[index].length === k) {\n index++;\n }\n }\n if(dp[index].length && dp[index].at(-1) + 1 != nums[i]) {\n return false;\n }\n dp[index].push(nums[i])\n }\n\n return true;\n};", "solution_java": "class Solution {\n public boolean isPossibleDivide(int[] nums, int k) {\n if (nums.length % k != 0) return false;\n Map countMap = new HashMap<>();\n for (int num : nums) {\n int count = countMap.getOrDefault(num, 0);\n countMap.put(num , count + 1);\n }\n Arrays.sort(nums);\n for (int num : nums) {\n if (!countMap.containsKey(num)) continue;\n int count = countMap.get(num);\n if (count == 1) countMap.remove(num);\n else countMap.put(num, count - 1);\n for (int i = 1; i < k; i++) {\n int next = num + i;\n if (!countMap.containsKey(next)) return false;\n count = countMap.get(next);\n if (count == 1) countMap.remove(next);\n else countMap.put(next, count - 1);\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool isPossibleDivide(vector& nums, int k) {\n if(nums.size() % k) return false;\n \n map m;\n for(int i : nums) m[i]++;\n \n int n = m.size();\n while(n) {\n int a = m.begin() -> first;\n m[a]--;\n if(!m[a]) m.erase(a), n--;\n for(int i=1; i List[str]:\n \n li = {}\n for i in words:\n if i in li:\n li[i]+=1\n else:\n li[i]=1\n \n heap = []\n for i in li:\n heap.append([-li[i],i])\n \n heapq.heapify(heap)\n \n ans = []\n for i in range(k):\n ans.append(heapq.heappop(heap)[1])\n \n return ans", "solution_js": "var topKFrequent = function(words, k) {\n let map=new Map()\n let res=[]\n for(let i of words){\n if(map.has(i)){\n map.set(i,map.get(i)+1)\n }else{\n map.set(i,1)\n }\n }\n \n res=[...map.keys()].sort((a,b)=>{\n if(map.get(a)===map.get(b)){\n return b < a ? 1:-1\n }\n return map.get(b)-map.get(a)\n }).slice(0,k)\n \n return res\n};", "solution_java": "class Solution {\n public List topKFrequent(String[] words, int k) {\n Map map=new LinkedHashMap<>();\n for(String word:words) \n map.put(word,map.getOrDefault(word,0)+1);\n PriorityQueue> queue=new PriorityQueue<>(new Comparator>(){\n @Override\n public int compare(Pair a,Pair b){\n if(a.getValue()!=b.getValue()) return b.getValue()-a.getValue();\n return a.getKey().compareTo(b.getKey());\n }\n });\n map.forEach((key,val)->{\n queue.add(new Pair(key,val));\n });\n List list=new ArrayList<>();\n while(k>0){\n list.add(queue.poll().getKey());\n k--;\n }\n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n bool static comp(pair a, pair b){\n if(a.second > b.second) return true;\n else if(a.second < b.second) return false;\n else{\n return a.first < b.first;\n }\n }\n vector topKFrequent(vector& words, int k) {\n unordered_map m;\n for(auto i : words){\n m[i]++;\n }\n vector> v;\n for(auto i : m){\n v.push_back(i);\n }\n sort(v.begin(), v.end(), comp);\n vector ans;\n for(int i=0; i bool:\n \n def getNeighbours(row,col,char):\n neighbours = []\n if row > 0 and grid[row-1][col] == char and not visited[row-1][col]:\n neighbours.append([row-1,col])\n if col > 0 and grid[row][col-1] == char and not visited[row][col-1]:\n neighbours.append([row,col-1])\n if row < len(grid)-1 and grid[row+1][col] == char and not visited[row+1][col]:\n neighbours.append([row+1,col])\n if col < len(grid[0])-1 and grid[row][col+1] == char and not visited[row][col+1]:\n neighbours.append([row,col+1])\n return neighbours\n \n def dfs(row,col,char,cyclePresent):\n if visited[row][col] or cyclePresent:\n cyclePresent = True\n return cyclePresent\n visited[row][col] = True\n neighbours = getNeighbours(row,col,char)\n for r,c in neighbours:\n cyclePresent = dfs(r,c,char,cyclePresent)\n return cyclePresent\n \n visited = [[False for _ in range(len(grid[0]))] for _ in range(len(grid))]\n cyclePresent = False\n for row in range(len(grid)):\n for col in range(len(grid[0])):\n if cyclePresent:\n return True\n if visited[row][col]:\n continue\n cyclePresent = dfs(row,col,grid[row][col],cyclePresent)\n \n return cyclePresent", "solution_js": "/**\n * @param {character[][]} grid\n * @return {boolean}\n */\nvar containsCycle = function(grid) {\n const m = grid.length;\n const n = grid[0].length;\n const visited = [...Array(m)].map(i => Array(n).fill(0));\n const dir = [[-1,0],[1,0],[0,-1],[0,1]];\n \n const dfs = (x,y,lx,ly) => { \n visited[x][y] = 1;\n for (const [a, b] of dir) {\n const nx = x + a;\n const ny = y + b;\n \n if (nx < 0 || nx > m - 1 || ny < 0 || ny > n - 1)\n continue;\n \n if (visited[nx][ny] === 1 && (nx !== lx || ny !== ly) && grid[x][y] === grid[nx][ny]) { // !!! grid[nx][ny] === grid[x][y]\n return true;\n }\n \n if (visited[nx][ny] === 0 && grid[x][y] === grid[nx][ny]) {\n if (dfs(nx,ny,x,y))\n return true;\n }\n }\n return false;\n }\n \n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (visited[i][j] === 0 && dfs(i,j,-1,-1)) // !!!\n return true;\n }\n }\n \n return false;\n};", "solution_java": "class Solution {\n public boolean containsCycle(char[][] grid) {\n int rows = grid.length, cols = grid[0].length;\n\n\t\t// Create a boolean array of same dimensions to keep track of visited cells\n boolean[][] visited = new boolean[rows][cols];\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (!visited[i][j] && dfs(grid, visited, i, j, 0, 0, grid[i][j])) {\n return true;\n }\n }\n }\n\n return false;\n }\n \n public boolean dfs(\n char[][] grid,\n boolean[][] visited,\n int i,\n int j,\n int prevI,\n int prevJ,\n char c\n ) {\n\t\t// Check for out of bounds\n if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return false;\n\n\t\t// Check whether the current char matches the previous char\n if (grid[i][j] != c) return false;\n\t\t\n\t\t// If we stumble upon the same cell, we're guaranteed to have found a cycle!\n if (visited[i][j]) {\n return true;\n }\n \n\t\t// Mark the cell as visited\n visited[i][j] = true;\n \n\t\t// We want to search in the south direction ONLY IF we didn't come from north\n\t\t// Do the same for all four directions\n boolean south = i - prevI != -1;\n boolean north = i - prevI != 1;\n boolean east = j - prevJ != -1;\n boolean west = j - prevJ != 1;\n return\n (south && dfs(grid, visited, i + 1, j, i, j, c)) ||\n (north && dfs(grid, visited, i - 1, j, i, j, c)) ||\n (east && dfs(grid, visited, i, j + 1, i, j, c)) ||\n (west && dfs(grid, visited, i, j - 1, i, j, c));\n }\n}", "solution_c": "class Solution {\npublic:\n int dx[4]={-1,1,0,0};\n int dy[4]={0,0,1,-1};\n bool solve(vector>& grid,int i,int j,int m,int n,int x,int y,vector>&vis,char startChar){\n vis[i][j]=1;\n for(int k=0;k<4;k++){\n int xx=i+dx[k];\n int yy=j+dy[k];\n if(xx>=0 && yy>=0 && xx>& grid) {\n int m=grid.size();\n int n=grid[0].size();\n vector>vis(m,vector(n,0));\n for(int i=0;i int:\n def waste(i, j, h):\n sumI = sums[i-1] if i > 0 else 0\n return (j-i+1)*h - sums[j] + sumI\n \n def dp(i, k):\n if i <= k:\n return 0\n if k < 0:\n return MAX\n if (i, k) in memoize:\n return memoize[(i, k)]\n \n _max = A[i]\n r = MAX\n for j in range(i-1, -2, -1):\n r = min(r, dp(j, k-1) + waste(j+1, i, _max))\n _max = max(_max, A[j])\n\n memoize[(i, k)] = r\n return r\n \n sums = list(accumulate(A))\n n = len(A)\n MAX = 10**6*200\n memoize = {}\n\n return dp(n-1, K)", "solution_js": "var minSpaceWastedKResizing = function(nums, k) {\n var prefixSum = []; // prefix is index 1 based\n var rangeMax = []; // index 0 based\n var sum = 0;\n prefixSum[0] = 0; \n for (var i = 0; i < nums.length; i++) {\n sum += nums[i];\n prefixSum[i + 1] = sum;\n }\n for (var i = 0; i < nums.length; i++) {\n var max = -Infinity;\n rangeMax[i] = [];\n for (var j = i; j < nums.length; j++) {\n max = Math.max(nums[j], max);\n rangeMax[i][j] = max;\n }\n }\n var f = []; // f[i][j] is resize i times to get minimun with index j - 1 to get minimum space.\n f[0] = [];\n for (var i = 0; i <= k; i++) {\n f[i] = [];\n f[i][0] = 0;\n }\n for (var j = 1; j <= nums.length; j++) {\n f[0][j] = rangeMax[0][j - 1] * j - prefixSum[j];\n }\n\n for (var i = 1; i <= k; i++) {\n for (var j = 1; j <= nums.length; j++) {\n f[i][j] = Infinity;\n for (var m = 1; m <= j; m++) {\n f[i][j] = Math.min(f[i][j], f[i - 1][m - 1] + rangeMax[m - 1][j - 1] * (j - m + 1) - (prefixSum[j] - prefixSum[m - 1]));\n }\n }\n }\n return f[k][nums.length];\n};", "solution_java": "class Solution {\n\n// dp[idx][k]=minimum wasted space in between [idx....n-1] if we resize the region k times \n\n int INF=200 *(int)1e6; // according to constarints { 1 <= nums.length <= 200 , 1 <= nums[i] <= 106 }\n public int minSpaceWastedKResizing(int[] nums, int k) {\n \n int dp[][]=new int[nums.length+1][k+1];\n memeset(dp, -1);\n return f(dp, 0, k, nums);\n \n }\n \n int f(int dp[][], int idx, int k, int nums[])\n {\n if(idx==nums.length)\n return 0;\n if(k==-1)\n return INF;\n \n if(dp[idx][k] != -1)\n return dp[idx][k];\n \n int ans=INF, max=nums[idx], sum=0;\n \n for(int j=idx; j& nums, int idx, int k)\n {\n int n = nums.size();\n if(idx==n) return 0;\n if(k<0) return maxi;\n if(dp[idx][k]!=-1) return dp[idx][k];\n ll sum = 0, mx = 0, ans = maxi;\n for(int i=idx; i& nums, int k) {\n memset(dp,-1,sizeof(dp));\n return dfs(nums,0,k);\n }\n};" }, { "title": "Two Best Non-Overlapping Events", "algo_input": "You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.\n\nReturn this maximum sum.\n\nNote that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.\n\n \nExample 1:\n\nInput: events = [[1,3,2],[4,5,2],[2,4,3]]\nOutput: 4\nExplanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.\n\n\nExample 2:\n\nInput: events = [[1,3,2],[4,5,2],[1,5,5]]\nOutput: 5\nExplanation: Choose event 2 for a sum of 5.\n\n\nExample 3:\n\nInput: events = [[1,5,3],[1,5,1],[6,6,5]]\nOutput: 8\nExplanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.\n\n \nConstraints:\n\n\n\t2 <= events.length <= 105\n\tevents[i].length == 3\n\t1 <= startTimei <= endTimei <= 109\n\t1 <= valuei <= 106\n\n", "solution_py": "class Solution:\ndef maxTwoEvents(self, events: List[List[int]]) -> int:\n \n events.sort()\n heap = []\n res2,res1 = 0,0\n for s,e,p in events:\n while heap and heap[0][0] a[0] - b[0]);\n\n const minHeap = new MinPriorityQueue({ priority: x => x[1] });\n\n let maxVal = 0;\n let maxSum = 0;\n\n for (let i = 0; i < n; ++i) {\n const [currStart, currEnd, currVal] = events[i];\n\n while (!minHeap.isEmpty()) {\n const topElement = minHeap.front().element;\n const [topIdx, topEnd] = topElement;\n\n if (topEnd < currStart) {\n maxVal = Math.max(maxVal, events[topIdx][2]);\n minHeap.dequeue();\n }\n else {\n break;\n }\n }\n\n const sum = maxVal + currVal;\n maxSum = Math.max(maxSum, sum);\n minHeap.enqueue([i, currEnd]);\n }\n\n return maxSum;\n};", "solution_java": "class Solution {\n public int maxTwoEvents(int[][] events) {\n Arrays.sort(events, (a, b) -> a[0] - b[0]);\n int onRight = 0, maxOne = 0, n = events.length;\n int[] rightMax = new int[n+1];\n for (int i = n - 1; i >= 0; i--) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n maxOne = Math.max(val, maxOne);\n rightMax[i] = Math.max(rightMax[i+1], val);\n }\n int two = 0;\n for (int i = 0; i < n; i++) {\n int start = events[i][0], end = events[i][1], val = events[i][2];\n int idx = binarySearch(end, events);\n if (idx < n) {\n two = Math.max(rightMax[idx] + val, two);\n }\n }\n return Math.max(two, maxOne);\n }\n\n public int binarySearch(int end, int[][] arr) {\n int left = 0, right = arr.length;\n while (left < right) {\n int mid = left + (right - left) / 2;\n if (arr[mid][0] > end) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n }\n}", "solution_c": "#define ipair pair\nclass Solution {\npublic:\n int maxTwoEvents(vector>& events) {\n\t\n //sort based on smaller start time\n sort(events.begin(), events.end());\n \n int mx = 0, ans = 0, n = events.size();\n priority_queue, greater<>> pq;\n // pq conatins {event_endtime , even_value}\n // for every event check the max-value of earlier events whose \n // deadline is less than start time of curr event\n for(int i=0; i int:\n if r-l < 1: return 0 # <-- base case for the recursion; one number in [l,r] \n ans = 1000 # <-- the answer for n = 200 is 952\n \n for choice in range((l+r)//2,r):\n ans = min(ans,choice+max(dp(l,choice-1),dp(choice+1,r)))\n\n return ans\n\n return dp()", "solution_js": "/** https://leetcode.com/problems/guess-number-higher-or-lower-ii/\n * @param {number} n\n * @return {number}\n */\nvar getMoneyAmount = function(n) {\n // Memo\n this.memo = new Map();\n \n return dp(n, 0, n);\n};\n\nvar dp = function(n, start, end) {\n let key = `${start}_${end}`;\n \n // Base, there is only 1 node on this side of the leg, which mean our guess is always correct and it cost nothing so return 0\n if (end - start < 2) {\n return 0;\n }\n \n // Base, there are only 2 nodes on this side of the leg, which mean we only need to pick cheapest guess\n if (end - start === 2) {\n // The `start` will always be smaller so pick `start`, add 1 to account for 0 index\n return start + 1;\n }\n \n // Return from memo\n if (this.memo.has(key) === true) {\n return this.memo.get(key);\n }\n \n // Minimum cost\n let minCost = Infinity;\n \n // Try to arrange the tree's left and right leg and find the cost of each leg\n for (let i = start; i < end; i++) {\n let left = dp(n, start, i);\n let right = dp(n, i + 1, end);\n \n // Cost of current guess, add 1 to account for 0 index\n let curr = i + 1;\n \n // Update cost of current guess, which is the max of left or right leg\n curr = Math.max(left + curr, right + curr);\n \n // Then update the minimum cost for entire tree\n minCost = Math.min(minCost, curr);\n }\n \n // Set memo\n this.memo.set(key, minCost);\n \n return minCost;\n};", "solution_java": "class Solution {\n public int getMoneyAmount(int n) {\n int dp[][]=new int[n+1][n+1];\n for(int a[]:dp){\n Arrays.fill(a,-1);\n }\n return solve(1,n,dp);\n }\n static int solve(int start,int end,int[][] dp){\n if(start>=end) return 0;\n if(dp[start][end]!=-1) return dp[start][end];\n int min=Integer.MAX_VALUE;\n for(int i=start;i<=end;i++){\n min=Math.min(min,i+Math.max(solve(start,i-1,dp),solve(i+1,end,dp)));\n }\n dp[start][end]=min;\n return min;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> dp;\n\n int solve(int start, int end)\n {\n if(start>= end)\n return 0;\n\n if(dp[start][end] != -1)\n return dp[start][end];\n\n int ans = 0;\n int result = INT_MAX;\n for(int i=start; i<=end; i++)\n {\n int left = solve(start,i-1);\n int right = solve(i+1,end);\n ans = max(left,right) + i; // this line gurantee to include the money that is needed to win higher values\n result = min(ans,result);\n }\n\n return dp[start][end] = result;\n }\n\n int getMoneyAmount(int n) {\n int ans = 0;\n dp = vector>(n+1,vector(n+1,-1));\n return solve(1,n);\n }\n};" }, { "title": "N-th Tribonacci Number", "algo_input": "The Tribonacci sequence Tn is defined as follows: \n\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\n\nGiven n, return the value of Tn.\n\n \nExample 1:\n\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\n\nExample 2:\n\nInput: n = 25\nOutput: 1389537\n\n\n \nConstraints:\n\n\n\t0 <= n <= 37\n\tThe answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.\n", "solution_py": "class Solution:\n def tribonacci(self, n: int, q={}) -> int:\n if n<3:\n q[0]=0 #Initialize first 3 values \n q[1]=1\n q[2]=1\n if n not in q: #Have faith that last 3 calls will give the answer :)\n q[n]=self.tribonacci(n-1,q)+self.tribonacci(n-2,q)+self.tribonacci(n-3,q)\n return q[n]", "solution_js": "// Recursive and Memoiztion approach\nvar tribonacci = function(n, cache = {}) {\n if(n in cache) return cache[n]\n\n //Start of Base Cases\n if(n == 0) return 0\n if (n == 1 || n == 2) return 1;\n // End Of Base Cases\n \n // Caching the result\n cache[n] = tribonacci(n - 1, cache) + tribonacci(n - 2, cache) + tribonacci(n - 3, cache);\n \n return cache[n]; \n};\n\n// Tabulation Approach\nvar tribonacci = function(n) {\n // Create the Table;\n const table = Array(n + 1).fill(0);\n table[1] = 1;\n for(let i =0;i<=n;i++){\n //Iterate over the table and increase the values respectively\n table[i+1] += table[i]\n table[i+2] += table[i]\n table[i+3] += table[i]\n }\n return table[n]\n};", "solution_java": "class Solution {\n public int tribonacci(int n) {\n if(n==0)\n return 0;\n if(n==1)\n return 1;\n if(n==2)\n return 1;\n int p1=1;\n int p2=1;\n int p3=0;\n int cur=0;\n for(int i=3;i<=n;i++)\n {\n cur=p1+p2+p3;\n p3=p2;\n p2=p1;\n p1=cur;\n }\n return cur;\n }\n}", "solution_c": "class Solution {\npublic:\n int tribonacci(int n) {\n if(n<2)\n return n;\n \n int prev3 = 0;\n int prev2 = 1;\n int prev1 = 1;\n \n for(int i = 3; i<= n ; i++)\n {\n int ans = prev1+ prev2+prev3;\n prev3 = prev2;\n prev2 = prev1;\n prev1 = ans;\n }\n \n return prev1;\n }\n};" }, { "title": "Find Minimum in Rotated Sorted Array II", "algo_input": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:\n\n\n\t[4,5,6,7,0,1,4] if it was rotated 4 times.\n\t[0,1,4,4,5,6,7] if it was rotated 7 times.\n\n\nNotice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n\nGiven the sorted rotated array nums that may contain duplicates, return the minimum element of this array.\n\nYou must decrease the overall operation steps as much as possible.\n\n \nExample 1:\nInput: nums = [1,3,5]\nOutput: 1\nExample 2:\nInput: nums = [2,2,2,0,1]\nOutput: 0\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 5000\n\t-5000 <= nums[i] <= 5000\n\tnums is sorted and rotated between 1 and n times.\n\n\n \nFollow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums may contain duplicates. Would this affect the runtime complexity? How and why?\n\n \n", "solution_py": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n return min(nums)\n ", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMin = function(nums) {\n let min = Infinity;\n let l = 0;\n let r = nums.length - 1;\n while (l <= r) {\n const m = Math.floor((l + r) / 2);\n\n // Eliminate dupes ......................... only difference from #153\n while (l < m && nums[l] === nums[m]) l++;\n while (r > m && nums[r] === nums[m]) r--;\n // .........................................\n\n // locate the sorted side, the opposite side has the break point\n // min should be on the side that has the break point, so continue search on that side\n if (nums[l] <= nums[m]) {\n // left side is sorted (or l & m are the same index)\n // brake is on right side\n min = Math.min(min, nums[l]);\n l = m + 1;\n } else {\n // right side is sorted\n // break is on left side\n min = Math.min(min, nums[m]);\n r = m - 1;\n }\n }\n return min;\n};", "solution_java": "class Solution {\n public int findMin(int[] nums) {\n int l = 0;\n int h = nums.length - 1;\n while (l < h) {\n while (l < h && nums[l] == nums[l + 1])\n ++l;\n while (l < h && nums[h] == nums[h - 1])\n --h;\n int mid = l + (h - l) / 2;\n if (nums[mid] > nums[h]) { // smaller elements are in the right side\n l = mid + 1;\n } else {\n h = mid;\n }\n }\n return nums[l];\n }\n}", "solution_c": "class Solution {\npublic:\n int findMin(vector& nums) {\n int l=0,h=nums.size()-1;\n while(lnums[h]) l=m+1;\n else h--;\n }\n return nums[h];\n }\n};" }, { "title": "Partition Array into Disjoint Intervals", "algo_input": "Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:\n\n\n\tEvery element in left is less than or equal to every element in right.\n\tleft and right are non-empty.\n\tleft has the smallest possible size.\n\n\nReturn the length of left after such a partitioning.\n\nTest cases are generated such that partitioning exists.\n\n \nExample 1:\n\nInput: nums = [5,0,3,8,6]\nOutput: 3\nExplanation: left = [5,0,3], right = [8,6]\n\n\nExample 2:\n\nInput: nums = [1,1,1,0,6,12]\nOutput: 4\nExplanation: left = [1,1,1,0], right = [6,12]\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 105\n\t0 <= nums[i] <= 106\n\tThere is at least one valid answer for the given input.\n\n", "solution_py": "class Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n prefix = [nums[0] for _ in range(len(nums))]\n suffix = [nums[-1] for _ in range(len(nums))]\n for i in range(1, len(nums)):\n prefix[i] = max(prefix[i-1], nums[i-1])\n for i in range(len(nums)-2, -1, -1):\n suffix[i] = min(suffix[i+1], nums[i+1])\n for i in range(0, len(nums)-1):\n if prefix[i] <= suffix[i]:\n return i+1", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar partitionDisjoint = function(nums) {\n let n = nums.length;\n let leftMax = Array(n).fill(0), rightMin = Array(n).fill(0);\n let left = 0, right = n- 1;\n \n for(let i = 0, j = n - 1;i=0 ;i++,j--){\n leftMax[i] = Math.max(nums[i], !i ? -Infinity : leftMax[i-1]);\n rightMin[j] = Math.min(nums[j], j === n - 1 ? Infinity : rightMin[j+1]);\n }\n \n for(let i = 0;i tree;\n void build(vector &nums) {\n int n=nums.size();\n for(int i=0 ; i0 ; i--) tree[i] = min(tree[i<<1],tree[i<<1|1]);\n }\n\n int query(int l, int r, int n) {\n l+=n,r+=n;\n int ans = INT_MAX;\n while(l>=1; r>>=1;\n }\n return ans;\n }\n\n int partitionDisjoint(vector& nums) {\n int n=nums.size();\n int mx=-1 ;\n tree.resize(2*n,INT_MAX); build(nums);\n for(int left=0; left= mx) return left+1;\n }\n return n;\n }\n};" }, { "title": "Stone Game II", "algo_input": "Alice and Bob continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. \n\nAlice and Bob take turns, with Alice starting first.  Initially, M = 1.\n\nOn each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).\n\nThe game continues until all the stones have been taken.\n\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice can get.\n\n \nExample 1:\n\nInput: piles = [2,7,9,4,4]\nOutput: 10\nExplanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. \n\n\nExample 2:\n\nInput: piles = [1,2,3,4,5,100]\nOutput: 104\n\n\n \nConstraints:\n\n\n\t1 <= piles.length <= 100\n\t1 <= piles[i] <= 104\n\n", "solution_py": "class Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n n = len(piles)\n dp = {} \n def recursion(index,M):\n # if we reached to the end we cannot score any value\n if index == n:\n return 0\n # we search if we have solved the same case earlier\n if (index,M) in dp:\n return dp[(index,M)] \n # total remaining score is the sum of array from index to the end\n total = sum(piles[index:]) \n # if we can take the complete array it is the best choice\n if index + 2*M >= n :return total\n # my_score is the score we are getting as the player who is playing\n my_score = 0\n for x in range(index,index+2*M):\n # opponent score will be calculated by next recursion\n opponent_score = recursion(x+1,max(M,x-index+1))\n # my_score is the remaining value of total - opponent_score\n my_score = max(my_score,total - opponent_score) \n # this is memoization part\n dp[(index,M)] = my_score\n # return the score\n return my_score\n \n return recursion(0,1)", "solution_js": "var stoneGameII = function(piles) {\n const length = piles.length;\n const dp = [...Array(length + 1).fill(null)].map((_) =>\n Array(length + 1).fill(0)\n );\n const sufsum = new Array(length + 1).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n sufsum[i] = sufsum[i + 1] + piles[i];\n }\n for (let i = 0; i <= length; i++) {\n dp[i][length] = sufsum[i];\n }\n for (let i = length - 1; i >= 0; i--) {\n for (let j = length - 1; j >= 1; j--) {\n for (let X = 1; X <= 2 * j && i + X <= length; X++) {\n dp[i][j] = Math.max(dp[i][j], sufsum[i] - dp[i + X][Math.max(j, X)]);\n }\n }\n }\n return dp[0][1];\n};", "solution_java": "class Solution {\n public int stoneGameII(int[] piles) {\n Map memo = new HashMap<>();\n int diff = stoneGame(piles,1,0,0,memo);\n int totalSum = 0;\n for(int ele: piles)\n totalSum+=ele;\n return (diff+totalSum)/2;\n }\n\n public int stoneGame(int[] piles, int M, int index, int turn,Map memo )\n {\n if(index >= piles.length)\n return 0;\n if(memo.containsKey(index+\"-\"+M+\"-\"+turn))\n return memo.get(index+\"-\"+M+\"-\"+turn);\n int score=0,maxScore=Integer.MIN_VALUE;\n // Alice's turn\n if(turn == 0)\n {\n for(int X=1;X<=2*M && index+X-1& piles){\n if(i==piles.size()) return 0;\n if(dp[i][m][p]!=-1) return dp[i][m][p];\n int cnt = 0,ans=INT_MIN,n=piles.size();\n for(int j=i;j& piles) {\n int sum = 0;\n memset(dp,-1,sizeof(dp));\n for(auto i:piles) sum += i;\n return (sum + rec(0,1,0,piles))/2;\n }\n};" }, { "title": "Substring with Concatenation of All Words", "algo_input": "You are given a string s and an array of strings words. All the strings of words are of the same length.\n\nA concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.\n\n\n\tFor example, if words = [\"ab\",\"cd\",\"ef\"], then \"abcdef\", \"abefcd\", \"cdabef\", \"cdefab\", \"efabcd\", and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words.\n\n\nReturn the starting indices of all the concatenated substrings in s. You can return the answer in any order.\n\n \nExample 1:\n\nInput: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\nThe substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\nThe substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\nThe output order does not matter. Returning [9,0] is fine too.\n\n\nExample 2:\n\nInput: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\nOutput: []\nExplanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\nThere is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\nWe return an empty array.\n\n\nExample 3:\n\nInput: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\nOutput: [6,9,12]\nExplanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\nThe substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\nThe substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\nThe substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 104\n\t1 <= words.length <= 5000\n\t1 <= words[i].length <= 30\n\ts and words[i] consist of lowercase English letters.\n\n", "solution_py": "class Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n req={}\n for i in words:\n req[i]=1+req.get(i,0)\n l=0\n r=len(words)*len(words[0])\n ans=[]\n\n while r findSubstring(String s, String[] words) {\n\n HashMap input = new HashMap<>();\n int ID = 1;\n HashMap count = new HashMap<>();\n for(String word: words) {\n if(!input.containsKey(word))\n input.put(word, ID++);\n int id = input.get(word);\n count.put(id,count.getOrDefault(id,0)+1);\n\n }\n int len = s.length();\n int wordLen = words[0].length();\n int numWords = words.length;\n int windowLen = wordLen*numWords;\n int lastIndex = s.length()-windowLen;\n\n int curWordId[] = new int[len];\n String cur = \" \"+s.substring(0,wordLen-1);\n\n //Change to int array\n for(int i = 0; i< (len-wordLen+1); i++) {\n cur = cur.substring(1, cur.length())+s.charAt(i+wordLen-1);\n if(input.containsKey(cur)){\n curWordId[i] = input.get(cur);\n } else {\n curWordId[i] = -1;\n }\n }\n List res = new ArrayList<>();\n\n //compare using int make it faster 30 times in each comparison\n for(int i = 0; i<= lastIndex; i++) {\n\n HashMap winMap = new HashMap<>();\n for(int j = 0; j < windowLen && curWordId[i] != -1; j+=wordLen) {\n\n int candidate = curWordId[j+i];\n\n if(!count.containsKey(candidate))\n break;\n else{\n winMap.put(candidate, winMap.getOrDefault(candidate, 0)+1);\n }\n if(winMap.get(candidate) > count.get(candidate))\n break;\n\n if(j == (windowLen - wordLen) && winMap.size() == count.size()){\n res.add(i);\n\n }\n\n }\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector findSubstring(string s, vector& words) {\n int n = words[0].length();\n int slen = s.length();\n int len = slen - n*words.size();\n vector ans;\n if( len < 0) return ans;\n string t;\n unordered_map mp;\n for(auto i = 0; i < words.size(); ++i) ++mp[words[i]];\n\n for(int i = 0; i<= len; ++i){\n t = s.substr(i, n);\n if(mp.find(t) != mp.end()){\n unordered_map smp;\n ++smp[t];\n int flag = 1;\n for(int j = i+n, k = 1; k < words.size() && j+n <= slen; ++k, j = j + n){\n t = s.substr(j, n);\n if(mp.find(t) != mp.end()) ++smp[t];\n else {\n flag = 0;\n break;\n }\n }\n if(flag && smp == mp) ans.push_back(i);\n }\n }\n\n return ans;\n }\n};" }, { "title": "Longest Happy String", "algo_input": "A string s is called happy if it satisfies the following conditions:\n\n\n\ts only contains the letters 'a', 'b', and 'c'.\n\ts does not contain any of \"aaa\", \"bbb\", or \"ccc\" as a substring.\n\ts contains at most a occurrences of the letter 'a'.\n\ts contains at most b occurrences of the letter 'b'.\n\ts contains at most c occurrences of the letter 'c'.\n\n\nGiven three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string \"\".\n\nA substring is a contiguous sequence of characters within a string.\n\n \nExample 1:\n\nInput: a = 1, b = 1, c = 7\nOutput: \"ccaccbcc\"\nExplanation: \"ccbccacc\" would also be a correct answer.\n\n\nExample 2:\n\nInput: a = 7, b = 1, c = 0\nOutput: \"aabaa\"\nExplanation: It is the only correct answer in this case.\n\n\n \nConstraints:\n\n\n\t0 <= a, b, c <= 100\n\ta + b + c > 0\n\n", "solution_py": "class Solution:\n\tdef longestDiverseString(self, a: int, b: int, c: int) -> str:\n\t\tpq = []\n\t\tif a > 0: heapq.heappush(pq,(-a,'a')) \n\t\tif b > 0: heapq.heappush(pq,(-b,'b')) \n\t\tif c > 0: heapq.heappush(pq,(-c,'c'))\n\n\t\tans = ''\n\t\twhile pq:\n\t\t\tc, ch = heapq.heappop(pq)\n\t\t\tif len(ans)>1 and ans[-1] == ans[-2] == ch:\n\t\t\t\tif not pq: break\n\t\t\t\tc2, ch2 = heapq.heappop(pq)\n\t\t\t\tans += ch2\n\t\t\t\tc2 += 1\n\t\t\t\tif c2: heapq.heappush(pq,(c2,ch2))\n\t\t\telse:\n\t\t\t\tans += ch\n\t\t\t\tc += 1\n\t\t\tif c: heapq.heappush(pq,(c,ch))\n\n\t\treturn ans", "solution_js": "var longestDiverseString = function(a, b, c) {\n let str = '', aCount = 0, bCount = 0, cCount = 0;\n let len = a + b + c;\n for(let i = 0; i < len; i++) {\n if (a >= b && a >= c && aCount != 2 || bCount == 2 && a > 0 || cCount == 2 && a > 0) {\n adjustCounts('a', aCount+1, 0, 0);\n a--;\n } else if (b >= a && b >= c && bCount != 2 || aCount == 2 && b > 0 || cCount == 2 && b > 0) {\n adjustCounts('b', 0, bCount+1, 0);\n b--;\n } else if (c >= a && c >= b && cCount != 2 || bCount == 2 && c > 0|| aCount == 2 && c > 0) {\n adjustCounts('c', 0, 0 , cCount+1);\n c--;\n }\n }\n\n function adjustCounts(letter, newA, newB, newC){\n aCount = newA;\n bCount = newB;\n cCount = newC;\n str += letter;\n }\n\n return str;\n};", "solution_java": "/*\nThe idea behid this problem\n1. Here we start by taking the size as the sum of a, b, c.\n2. Then we use 3 variables A, B, C to count the occurance of a, b, c.\n3. Now we iterate until the size, and \n -> Checks the largest number among a, b, c and whether the count < 2 or whther the count of other letters is 2 and there is still letters that can be added, then we append the letter, decrement from the total count of that particular letter and increase the occurance of that letter and set others back to zero.\n \n4. Finally return the string.\n*/\nclass Solution {\n public String longestDiverseString(int a, int b, int c) {\n int totalSize = a + b + c;\n int A = 0;\n int B = 0;\n int C = 0;\n StringBuilder sb = new StringBuilder();\n for (int i=0; i=b && a>=c && A<2) || (B==2 && a>0) || (C==2 && a>0)) {\n sb.append(\"a\");\n a -= 1;\n A += 1;\n B = 0;\n C = 0;\n }\n // check b is largest and its count still < 2 or A and C = 2 and there are still b that cam be added\n else if ((b>=a && b>=c && B<2) || (A==2 && b>0) || (C==2 && b>0)) {\n sb.append(\"b\");\n b -= 1;\n B += 1;\n A = 0;\n C = 0;\n }\n // checks c is largest and its count still < 2 or B and A = 2 and there are still c that can be added\n else if ((c>=a && c>=b && C<2) || (A==2 && c>0) || (B==2 && c>0)) {\n sb.append(\"c\");\n c -= 1;\n C += 1;\n A = 0;\n B = 0;\n }\n }\n return sb.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n\t#define f first \n\t#define s second\n\tstring longestDiverseString(int a, int b, int c) {\n\t\tpriority_queue> pq;\n\t\tif(a>0)pq.push({a,'a'}); \n\t\tif(b>0)pq.push({b,'b'}); \n\t\tif(c>0)pq.push({c,'c'});\n\n\t\tstring ans = \"\";\n\t\twhile(!pq.empty()){\n\t\t\tauto t = pq.top(); pq.pop();\n\t\t\tint c = t.f;\n\t\t\tchar ch = t.s;\n\t\t\tif(ans.size() > 1 && ans[ans.size()-1]==ch && ch == ans[ans.size()-2]) {\n\t\t\t\tif(pq.empty())break;\n\t\t\t\tauto t = pq.top(); pq.pop();\n\t\t\t\tint c2 = t.f;\n\t\t\t\tchar ch2 = t.s;\n\t\t\t\tans += ch2;\n\t\t\t\tc2-=1;\n\t\t\t\tif(c2)pq.push({c2,ch2});\n\t\t\t}else{\n\t\t\t\tans += ch;\n\t\t\t\tc-=1;\n\t\t\t}\n\t\t\tif(c)pq.push({c,ch});\n\t\t}\n\t\treturn ans;\n\t}\n};" }, { "title": "Coordinate With Maximum Network Quality", "algo_input": "You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.\n\nYou are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.\n\nThe signal quality of the ith tower at a coordinate (x, y) is calculated with the formula ⌊qi / (1 + d)⌋, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.\n\nReturn the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.\n\nNote:\n\n\n\tA coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:\n\n\t\n\t\tx1 < x2, or\n\t\tx1 == x2 and y1 < y2.\n\t\n\t\n\t⌊val⌋ is the greatest integer less than or equal to val (the floor function).\n\n\n \nExample 1:\n\nInput: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput: [2,1]\nExplanation: At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.\n\nExample 2:\n\nInput: towers = [[23,11,21]], radius = 9\nOutput: [23,11]\nExplanation: Since there is only one tower, the network quality is highest right at the tower's location.\n\n\nExample 3:\n\nInput: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput: [1,2]\nExplanation: Coordinate (1, 2) has the highest network quality.\n\n\n \nConstraints:\n\n\n\t1 <= towers.length <= 50\n\ttowers[i].length == 3\n\t0 <= xi, yi, qi <= 50\n\t1 <= radius <= 50\n\n", "solution_py": "class Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n return max(\n (\n (sum(qi // (1 + dist) for xi, yi, qi in towers if (dist := sqrt((xi - x) ** 2 + (yi - y) ** 2)) <= radius),\n [x, y]) for x in range(51) for y in range(51)\n ),\n key=lambda x: (x[0], -x[1][0], -x[1][1])\n )[1]", "solution_js": "var bestCoordinate = function(towers, radius) {\n const n = towers.length;\n const grid = [];\n \n for (let i = 0; i <= 50; i++) {\n grid[i] = new Array(51).fill(0);\n }\n \n \n for (let i = 0; i < n; i++) {\n const [x1, y1, quality1] = towers[i];\n \n for (let x2 = 0; x2 <= 50; x2++) {\n for (let y2 = 0; y2 <= 50; y2++) {\n const dist = Math.sqrt((x1 - x2)**2 + (y1 - y2)**2);\n\n if (dist > radius) continue;\n\n const network = Math.floor(quality1 / (1 + dist));\n \n grid[x2][y2] += network;\n }\n }\n }\n \n\t\n let maxX = 0;\n let maxY = 0;\n let maxVal = grid[0][0];\n \n for (let i = 0; i <= 50; i++) {\n for (let j = 0; j <= 50; j++) {\n const val = grid[i][j];\n \n if (val > maxVal) {\n maxVal = val;\n maxX = i;\n maxY = j;\n }\n else if (val === maxVal) {\n if (i < maxX || (i === maxX && j < maxY)) {\n maxVal = val;\n maxX = i;\n maxY = j;\n }\n }\n }\n }\n \n return [maxX, maxY];\n};", "solution_java": "class Solution {\n public int[] bestCoordinate(int[][] towers, int radius) {\n int minX = 51, maxX = 0, minY = 51, maxY = 0, max = 0;\n int[] res = new int[2];\n for(int[] t : towers) {\n minX = Math.min(minX, t[0]);\n maxX = Math.max(maxX, t[0]);\n minY = Math.min(minY, t[1]);\n maxY = Math.max(maxY, t[1]);\n }\n for(int i = minX; i <= maxX; i++) {\n for(int j = minY; j <= maxY; j++) {\n int sum = 0;\n for(int[] t : towers) {\n int d = (t[0] - i) *(t[0] - i) + (t[1] - j) *(t[1] - j);\n if(d <= radius * radius) {\n sum += t[2] /(1+ Math.sqrt(d)); \n }\n }\n if(sum > max) {\n max = sum;\n res = new int[]{i,j};\n }\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector bestCoordinate(vector>& towers, int radius) {\n int n = towers.size();\n int sum;\n int ans = 0;\n pair ansCoor;\n\t\t// Calculate for every 'x's and 'y's \n for(int x = 0; x <= 50; x++){\n for(int y = 0; y <= 50; y++){\n sum = 0;\n for(const auto it : towers){\n int xa = it[0];\n int ya = it[1];\n int qa = it[2];\n\t\t\t\t\t// get the distance between the two points\n int distance = pow(x - xa, 2) + pow(y - ya, 2);\n if(distance > radius * radius) {\n continue;\n }\n\t\t\t\t\t// increment the quality value\n sum += (int)(qa / (1 + sqrt(distance)));\n }\n\t\t\t\t// store the maximum ans\n if(sum > ans){\n ans = sum;\n ansCoor = {x,y};\n }\n }\n }\n return vector{{ansCoor.first, ansCoor.second}};\n }\n};" }, { "title": "Number of Steps to Reduce a Number in Binary Representation to One", "algo_input": "Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:\n\n\n\t\n\tIf the current number is even, you have to divide it by 2.\n\t\n\t\n\tIf the current number is odd, you have to add 1 to it.\n\t\n\n\nIt is guaranteed that you can always reach one for all test cases.\n\n \nExample 1:\n\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4.  \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1.  \n\n\nExample 2:\n\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1.  \n\n\nExample 3:\n\nInput: s = \"1\"\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 500\n\ts consists of characters '0' or '1'\n\ts[0] == '1'\n\n", "solution_py": "class Solution:\n def numSteps(self, s: str) -> int:\n size = len(s)\n if size == 1:\n return 0\n one_group = s.split('0')\n zero_group = s.split('1')\n\n \n if size - len(zero_group[-1]) == 1:\n return size - 1\n else:\n return size + len(one_group) - len(zero_group[-1])", "solution_js": "var numSteps = function(s) {\n let res = 0;\n s = s.split(\"\");\n while(s.length>1){\n if(s[s.length-1]===\"0\") s.pop();\n else plusone(s);\n res++;\n }\n return res;\n};\nvar plusone = function(p) {\n p.unshift(\"0\");\n let i = p.length-1;\n p[i] = 1+(+p[i]);\n while(p[i]===2){\n p[i-1] = 1+(+p[i-1]);\n i--;\n p[i+1] = \"0\";\n }\n if(p[0]===\"0\") p.shift();\n return p;\n};", "solution_java": "class Solution \n{\n public int numSteps(String s)\n {\n int countSteps = 0;\n int carry = 0;\n for(int i = s.length()-1;i>=1;i--)\n {\n int rightMostBit = s.charAt(i)-'0';\n if((rightMostBit+carry) == 1)\n {\n carry=1;\n countSteps += 2;\n }\n else\n {\n countSteps++;\n }\n }\n return countSteps+carry;\n }\n} ", "solution_c": "class Solution {\npublic:\n int numSteps(string s) {\n int n=0;\n bool carry = false;\n int steps = 0;\n if(s == \"1\") return 0;\n while(s.length() > 0){\n int i = s.length()-1;\n if(carry){\n if(s[i] == '1'){\n carry = true; s[i] = '0';\n }else{\n s[i] = '1'; carry = false;\n }\n }\n if(s[i] == '0'){ s.pop_back(); steps++;}\n else{carry = true; s.pop_back(); steps += 2;}\n if(s == \"1\"){\n if(carry) steps++;\n break;\n }\n }\n return steps;\n }\n};" }, { "title": "Maximum Number of Points with Cost", "algo_input": "You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.\n\nTo gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.\n\nHowever, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.\n\nReturn the maximum number of points you can achieve.\n\nabs(x) is defined as:\n\n\n\tx for x >= 0.\n\t-x for x < 0.\n\n\n \nExample 1: \n\nInput: points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput: 9\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.\n\n\nExample 2:\n\nInput: points = [[1,5],[2,3],[4,2]]\nOutput: 11\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.\n\n\n \nConstraints:\n\n\n\tm == points.length\n\tn == points[r].length\n\t1 <= m, n <= 105\n\t1 <= m * n <= 105\n\t0 <= points[r][c] <= 105\n\n", "solution_py": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n for i in range(m - 1):\n for j in range(1, n):\n points[i][j] = max(points[i][j], points[i][j - 1] - 1)\n \n for j in range(n - 2, -1, -1):\n points[i][j] = max(points[i][j], points[i][j + 1] - 1)\n \n for j in range(n):\n points[i + 1][j] += points[i][j]\n \n return max(points[m - 1])", "solution_js": "var maxPoints = function(points) {\n let prev = points[0];\n let curr = Array(points[0].length);\n\n for(let i = 1; i=0; j--){\n maxAdd = Math.max(maxAdd-1, prev[j]);\n curr[j] = Math.max(curr[j], points[i][j] + maxAdd)\n }\n\n prev = curr;\n curr = Array(points[0].length)\n\n }\n return Math.max(...prev)\n};", "solution_java": "/* \n -> take a frame same width as points,this frame will contains most effective(which provide maximum sum)values which will later get \n\tadded to next values from next row.\n\n -> conditions to update values in frame \n\t\t* we will keep only those values which will contribute maximum in next row addition\n\n\te.g-->\n\t\tpoints --->[[1,2,3]\n\t\t\t\t\t[1,5,1]\n\t\t\t\t\t[3,1,1]]\n\n\t\tfor 1st iteration frame <--- [1,2,3] rest of two loops will not affect frame so in \n\t\t2nd itreration frame <--------[2,7,4] <-------- [1,2,3] + [1,5,1]\n\t\tnow we have to update frame so it can give max values for next row addition\n\t\t 0 1 2 \n\t\t[2,7,4] \n\t\t \\ \n\t\t[2,7,4] check left to right--> just check value at index 0 can contribute more than curr_sum at index 1 but to do so it has to give up (1-0) a penalty,here 7 can contribute more than 2-1=1 in next sum.\n\t\t2 7 4 now check for index 2,where (7-1)>4\n\t\t \\\n\t\t2 7 6\n\t\t\t\t\tnow do in reverse,can 6 contribute more than 7 no ( 7 >(6-1) ) \n\t\t\t\t\tcan 7 contibute more than 2 yes (2<(7-1)),so now frame will be\n\t\t6 7 6 now we can cal optimal-frame for rest of the matrix.\n\t+ 3 1 1\n ------------------- \n\t\t9 8 7 check left to right--> can 9 can contibute 8>(9-1) no; can 8 can contibute for index 2 no simlier for right to left\n*/\n\nclass Solution {\n\tpublic long maxPoints(int[][] points) {\n\t\tlong[] frame = new long[points[0].length];\n\n\t\tfor (int i = 0; i < points.length; i++) {\n\t\t\tfor (int j = 0; j =0;j--) frame[j] = Math.max(frame[j], frame[j + 1] - 1);\n\n\t\t\tfor(long k:frame) System.out.println(k);\n\t\t}\n\n\n\t\tlong ans = 0;\n\t\tfor (int i = 0; i < frame.length; i ++) {\n\t\t\tans = Math.max(ans, frame[i]);\n\t\t}\n\t\treturn ans;\n\t}\n}", "solution_c": "class Solution {\npublic:\n long long maxPoints(vector>& points) {\n vector> dp(points.size(), vector(points[0].size(), -1));\n \n for (int i = 0; i < points[0].size(); ++i) {\n dp[0][i] = points[0][i];\n }\n \n for (int i = 1; i < points.size(); ++i) {\n for (int j = 0; j < points[i].size(); ++j) {\n for (int k = 0; k < points[i].size(); ++k) {\n dp[i][j] = max(dp[i][j], dp[i - 1][k] - abs(k - j) + points[i][j]);\n }\n }\n }\n \n long long max_ans = -1;\n for (const auto v : dp.back()) {\n max_ans = max(max_ans, v);\n }\n \n return max_ans;\n }\n};" }, { "title": "Monotone Increasing Digits", "algo_input": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.\n\nGiven an integer n, return the largest number that is less than or equal to n with monotone increasing digits.\n\n \nExample 1:\n\nInput: n = 10\nOutput: 9\n\n\nExample 2:\n\nInput: n = 1234\nOutput: 1234\n\n\nExample 3:\n\nInput: n = 332\nOutput: 299\n\n\n \nConstraints:\n\n\n\t0 <= n <= 109\n\n", "solution_py": "class Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n num = list(str(n))\n for i in range(len(num)-1):\n # Step1: When don't meet the condition, num[i]-=1 and repalce all num left into '9' and directly return\n # However, there is the case that num[i-1]==num[i], which will make num[i]-1 num[i+1]:\n while i >= 1 and num[i-1] == num[i]:\n i -= 1\n num[i] = chr(ord(num[i])-1)\n return int(''.join(num[:i+1]+['9']*(len(num)-i-1)))\n return n", "solution_js": "var monotoneIncreasingDigits = function(n) {\n let arr = String(n).split('');\n for (let i=arr.length-2; i>=0; i--) {\n if (arr[i]>arr[i+1]) {\n arr[i]--;\n for(let j=i+1; j 0) {\n if (k < n % 10) {\n return position;\n } else {\n k = n % 10;\n n /= 10;\n position++;\n }\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int monotoneIncreasingDigits(int n) {\n if(n < 10) return n;\n\n string s = to_string(n);\n\n for(int i = s.size() - 2; i >= 0; i--) {\n if(s[i] > s[i+1]) {\n s[i]--;\n for(int j = i + 1; j < s.size(); j++) s[j] = '9';\n }\n }\n int ans = stoi(s);\n return ans;\n }\n};" }, { "title": "Serialize and Deserialize Binary Tree", "algo_input": "Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n\nDesign an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.\n\nClarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.\n\n \nExample 1:\n\nInput: root = [1,2,3,null,null,4,5]\nOutput: [1,2,3,null,null,4,5]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-1000 <= Node.val <= 1000\n\n", "solution_py": "class Codec:\n\n def serialize(self, root):\n if not root: return 'N'\n\n left = self.serialize(root.left)\n right = self.serialize(root.right)\n\n return ','.join([str(root.val), left, right])\n\n def deserialize(self, data):\n data = data.split(',')\n root = self.buildTree(data)\n return root\n\n def buildTree(self, data):\n val = data.pop(0)\n if val == 'N': return None\n node = TreeNode(val)\n node.left = self.buildTree(data)\n node.right = self.buildTree(data)\n return node", "solution_js": "var serialize = function (root) {\n if (!root) return \"\";\n let res = [];\n\n function getNode(node) {\n if (!node) {\n res.push(\"null\");\n } else {\n res.push(node.val);\n getNode(node.left);\n getNode(node.right);\n }\n }\n\n getNode(root);\n\n return res.join(\",\");\n};\n\n/**\n * Decodes your encoded data to tree.\n *\n * @param {string} data\n * @return {TreeNode}\n */\nvar deserialize = function (data) {\n if (data === \"\") return null;\n const arr = data.split(\",\");\n\n function buildTree(array) {\n const nodeVal = array.shift();\n\n if (nodeVal === \"null\") return null;\n\n const node = new TreeNode(nodeVal);\n node.left = buildTree(array); //build left first\n node.right = buildTree(array); //build right with updated array.\n\n return node;\n }\n\n return buildTree(arr);\n};", "solution_java": "public class Codec {\n\n // Encodes a tree to a single string.\n public String serialize(TreeNode root) {\n String data=\"\";\n Queue q=new LinkedList<>();\n if(root!=null)\n q.add(root);\n else\n return \"\";\n data=Integer.toString(root.val)+\"e\";\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i q=new LinkedList<>();\n q.add(root);\n while(i bool:\n\n def getValidPrefixLength(s,start):\n end = start\n while end < len(s) and s[end].isdigit(): end += 1\n return end\n\n @lru_cache(None)\n def possibleLengths(s):\n \"\"\"Return all possible lengths represented by numeric string s.\"\"\"\n ans = {int(s)}\n for i in range(1, len(s)):\n # add all lengths by splitting numeric string s at i\n ans |= {x+y for x in possibleLengths(s[:i]) for y in possibleLengths(s[i:])}\n return ans\n\n @lru_cache(None)\n def dp(i, j, diff):\n \"\"\"Return True if s1[i:] matches s2[j:] with given differences.\"\"\"\n\n # If both have reached end return true if none of them are leading\n if i == len(s1) and j == len(s2): return diff == 0\n\n # s1 has not reached end and s1 starts with a digit\n if i < len(s1) and s1[i].isdigit():\n i2 = getValidPrefixLength(s1,i)\n for L in possibleLengths(s1[i:i2]):\n # substract since lead of s2 decreases by L\n if dp(i2, j, diff-L): return True\n\n # s2 has not reached end and s2 starts with a digit\n elif j < len(s2) and s2[j].isdigit():\n j2 = getValidPrefixLength(s2,j)\n for L in possibleLengths(s2[j:j2]):\n # add since lead of s2 increase by L\n if dp(i, j2, diff+L): return True\n\n # if none of them have integer prefix or a lead over the other\n elif diff == 0:\n # if only one of them has reached end or current alphabets are not the same\n if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False\n # skip same alphabets\n return dp(i+1, j+1, 0)\n\n # if none of them have integer prefix & s2 lead over s1\n elif diff > 0:\n # no s1 to balance s2's lead\n if i == len(s1): return False\n # move s1 pointer forward and reduce diff\n return dp(i+1, j, diff-1)\n\n # if none of them have integer prefix & s1 lead over s2\n else:\n # no s2 to balance s1's lead\n if j == len(s2): return False\n # move s2 pointer forward and increase diff\n return dp(i, j+1, diff+1)\n\n # start with starts of both s1 and s2 with no lead by any of them\n return dp(0, 0, 0)", "solution_js": "var possiblyEquals = function(s1, s2) {\n // Memo array, note that we do not need to memoize true results as these bubble up\n const dp = Array.from({length: s1.length+1}, () =>\n Array.from({length: s2.length+1},\n () => ([])));\n\n const backtrack = (p1, p2, count) => {\n if(p1 === s1.length && p2 === s2.length) return count === 0;\n // Optimization: Exit early if we have already visited here and know that it's false\n if(dp[p1][p2][count] !== undefined) return dp[p1][p2][count];\n\n let c1 = s1[p1];\n let c2 = s2[p2];\n\n // Case 1: string matches exactly\n if(p1 < s1.length && p2 < s2.length &&\n c1 === c2 && count === 0 &&\n backtrack(p1+1, p2+1, count)) return true;\n\n // Case 2: we can delete a character\n if(p1 < s1.length && isNaN(c1) && count < 0 &&\n backtrack(p1+1, p2, count+1)) return true;\n if(p2 < s2.length && isNaN(c2) && count > 0 &&\n backtrack(p1, p2+1, count-1)) return true;\n\n // Case 3: we can start stacking numbers to delete\n let num = 0;\n for(let i = 0; i < 3 && p1+i < s1.length; i++) {\n let c1 = s1[p1+i];\n if(isNaN(c1)) break;\n num = num * 10 + parseInt(c1);\n\n if(backtrack(p1+i+1, p2, count + num)) return true;\n }\n\n num = 0;\n for(let i = 0; i < 3 && p2+i < s2.length; i++) {\n let c2 = s2[p2+i];\n if(isNaN(c2)) break;\n num = num * 10 + parseInt(c2);\n\n if(backtrack(p1, p2+i+1, count - num)) return true;\n }\n\n dp[p1][p2][count] = false;\n return false;\n }\n\n return backtrack(0,0,0);\n};", "solution_java": "/**\nCases:\n\ndiff > 0 meaning we need to pick more chars in s1\ndiff < 0 meaning we need to pick more chars in s2\n\n-1000 < diff < 1000 as there can be at most 3 digits in the string meaning largest digits are 999\n\n1. s1[i] == s2[j] and diff = 0\n increment i+1 and j+1\n\n2. if s1[i] is not digit and diff > 0 then increment i i+1, diff\n3. if s2[j] is not digit and diff < 0 then increment j j+1, diff\n4. if s1[i] is digit then get digit value and decrement diff val as we have covered such chars in the s1 string\n and increment i i+1, diff-val\n5. if s2[j] is digit then get digit value and increment diff val as we need to cover such chars in the s2 string and\n increment j, j+1, diff+val\n\n 01234\ns1 = l123e\ns2 = 44\n\ni: 0\nj: 0\ndiff: 0\n // Wildcard matching on s2[j]\n val = 4, diff = 0+4 j = 1\n\n i: 0\n j: 1\n diff: 4\n // Literal matching on s1[i]\n increment ith pointer as ith is a literal and we can move on to next char in s1 and decrement diff\n\n i: 1\n j: 1\n diff: 3\n // Wildcard matching on s1[i]\n val = 1 diff = 3-1 = 2 increment i\n\n i: 2\n j: 1\n diff: 2\n // Wildcard matching on s1[i]\n val = 2 diff = 2-2 = 0 increment i\n\n i: 3\n j: 1\n diff: 0\n // Wildcard matching on s1[i]\n val=3 diff = 0-3 = -3, increment i\n\n i: 4\n j: 1\n diff: -3\n // Wildcard matching on s2[j]\n val = 4 diff = -3+4 =1 increment j\n\n i: 4\n j: 2\n diff: 1\n // Literal matching on s1[i]\n decrement i-1 and increment i\n\n i=5\n j=2\n diff==0 return true\n dp[4][2][1] = true\n return true\n return dp[4][1][1000-3] = true\n return dp[3][1][0] = true\n\n i: 2\n j: 1\n diff: 2\n return dp[2][1][2] = true\n return true\n\n i: 0\n j: 1\n diff: 4\n return dp[0][1][4] = true\n return true\n*/\n\nclass Solution {\n //112ms\n public boolean possiblyEquals(String s1, String s2) {\n return helper(s1.toCharArray(), s2.toCharArray(), 0, 0, 0, new Boolean[s1.length()+1][s2.length()+1][2001]);\n }\n\n boolean helper(char[] s1, char[] s2, int i, int j, int diff, Boolean[][][] dp) {\n if(i == s1.length && j == s2.length) {\n return diff == 0;\n }\n\n if(dp[i][j][diff+1000] != null)\n return dp[i][j][diff+1000];\n\n // if both i and j are at the same location and chars are same then simply increment both pointers\n if(i < s1.length && j < s2.length && diff == 0 && s1[i] == s2[j]) {\n if(helper(s1, s2, i+1, j+1, diff, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // if s1[i] is literal and diff > 0 then increment i and decrement diff by 1\n if(i < s1.length && !Character.isDigit(s1[i]) && diff > 0 && helper(s1, s2, i+1, j, diff-1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // if s2[j] is literal and diff < 0 then increment j and increment diff by 1\n // as we are done with the current jth char\n if(j < s2.length && !Character.isDigit(s2[j]) && diff < 0 && helper(s1, s2, i, j+1, diff+1, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n\n // wildcard matching in s1\n // if s1 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = i, val = 0; k < i + 4 && k < s1.length && Character.isDigit(s1[k]); k++) {\n val = val * 10 + s1[k] -'0';\n if(helper(s1, s2, k+1, j, diff-val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n // wildcard matching in s2\n // if s2 contains l123\n // then need to check with val as 1 then val as 12 and val as 123\n for(int k = j, val = 0; k < j + 4 && k < s2.length && Character.isDigit(s2[k]); k++) {\n val = val * 10 + s2[k] -'0';\n if(helper(s1, s2, i, k+1, diff+val, dp)) {\n return dp[i][j][diff+1000] = true;\n }\n }\n\n return dp[i][j][diff+1000] = false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool memo[50][50][2000];\n bool comp_seqs(string& s1, string& s2, int i1, int i2, int diff){\n // check true condition\n if(i1 == s1.size() && i2 == s2.size())\n return diff == 0;\n // add 1000 to 'diff' be in range [0, 2000)\n bool& ret = memo[i1][i2][diff+1000];\n if(ret)\n return false; // immediately return\n ret = true; // check visited\n\n // diff > 0 or diff < 0 checking to ensure the diff always be in range (-1000, 1000)\n // in the case that s1[i1] is a digit\n if(diff >= 0 && i1 < s1.size() && s1[i1] <= '9'){\n int num1 = 0;\n for(int i=0; i '9')\n break;\n num1 = num1*10 + s1[i1 + i] - '0';\n if(comp_seqs(s1, s2, i1+i+1, i2, diff-num1))\n return true;\n }\n }else if(diff <= 0 && i2 < s2.size() && s2[i2] <= '9'){ // in the case that s2[i2] is a digit\n int num2 = 0;\n for(int i=0; i '9')\n break;\n num2 = num2*10 + s2[i2 + i] - '0';\n if(comp_seqs(s1, s2, i1, i2+i+1, diff+num2))\n return true;\n }\n }else if(diff == 0){\n if(i1 >= s1.size() || i2 >= s2.size() || s1[i1] != s2[i2]) // reject infeasible cases\n return false;\n return comp_seqs(s1, s2, i1+1, i2+1, 0);\n }else if(diff > 0){\n if(i1 >= s1.size()) // reject infeasible cases\n return false;\n return comp_seqs(s1, s2, i1+1, i2, diff - 1);\n }else{\n if(i2 >= s2.size()) // reject infeasible cases\n return false;\n return comp_seqs(s1, s2, i1, i2+1, diff + 1);\n }\n return false;\n }\n bool possiblyEquals(string s1, string s2) {\n return comp_seqs(s1, s2, 0, 0, 0);\n }\n};" }, { "title": "Concatenation of Array", "algo_input": "Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).\n\nSpecifically, ans is the concatenation of two nums arrays.\n\nReturn the array ans.\n\n \nExample 1:\n\nInput: nums = [1,2,1]\nOutput: [1,2,1,1,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]\n\nExample 2:\n\nInput: nums = [1,3,2,1]\nOutput: [1,3,2,1,1,3,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t1 <= n <= 1000\n\t1 <= nums[i] <= 1000\n\n", "solution_py": "class Solution(object):\n def getConcatenation(self, nums):\n return nums * 2", "solution_js": "var getConcatenation = function(nums) {\n\t//spread the nums array twice and return it\n return [...nums,...nums]\n};", "solution_java": "class Solution {\n public int[] getConcatenation(int[] nums) {\n int[] ans = new int[2 * nums.length];\n for(int i = 0; i < nums.length; i++){\n ans[i] = ans[i + nums.length] = nums[i];\n }\n\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector getConcatenation(vector& nums) {\n int n=nums.size();\n for(int i=0;i 0:\n i = dq.pop()\n for j in adj[i]:\n if j not in ret and j not in dq:\n dq.append(j)\n ret.append(j)\n return len(ret)\n\n adj = collections.defaultdict(list)\n for i in range(len(bombs)):\n for j in range(i + 1, len(bombs)):\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[i][2] ** 2:\n adj[i].append(j)\n if (bombs[i][0] - bombs[j][0]) ** 2 + (bombs[i][1] - bombs[j][1]) ** 2 <= bombs[j][2] ** 2:\n adj[j].append(i)\n ret = 0\n for i in range(len(bombs)):\n ret = max(ret, count(i))\n return ret", "solution_js": "/**\n * @param {number[][]} bombs\n * @return {number}\n */\nvar maximumDetonation = function(bombs) {\n if(bombs.length <= 1) return bombs.length;\n \n let adj = {}, maxSize = 0;\n const checkIfInsideRange = (x, y, center_x, center_y, radius) =>{\n return ( (x-center_x)**2 + (y-center_y)**2 <= radius**2 ) \n }\n\t\n\t//CREATE ADJACENCY MATRIX\n for(let i = 0;i{\n let detonated = 1;\n visited[node] = true;\n let childs = adj[node] || []\n for(let child of childs){\n if(visited[child]) continue;\n detonated += dfs(child, visited)\n }\n maxSize = Math.max(maxSize, detonated)\n return detonated;\n }\n \n for(let i = 0 ;i v means, v is in the range of u\n check from which node maximum nodes can be reached and return the number of nodes reached\n */\n public int maximumDetonation(int[][] bombs) {\n Map> graph = new HashMap<>();\n\n int n = bombs.length;\n for(int i = 0; i< n; i++){\n graph.put(i, new ArrayList<>());\n for(int j = 0; j< n; j++){\n if(i == j) continue;\n if(inRange(bombs[i], bombs[j]))\n graph.get(i).add(j);\n }\n }\n\n int max = 0;\n for(int i = 0; i< n; i++){\n max = Math.max(max, dfs(i, graph, new HashSet<>()));\n }\n return max;\n }\n\n private boolean inRange(int[] u, int[] v){\n // (x-a)^2 + (y-b)^2 = R^2 -> point (a, b) is at border\n // (x-a)^2 + (y-b)^2 < R^2 -> point (a, b) is inside the circle\n // (x-a)^2 + (y-b)^2 > R^2 -> point (a, b) is outside the circle\n return Math.pow(u[0]-v[0], 2) + Math.pow(u[1]-v[1], 2) <= Math.pow(u[2], 2);\n }\n\n private int dfs(int node, Map> graph, Set visited){\n if(visited.contains(node)) return 0;\n visited.add(node);\n int res = 0;\n for(int neigh: graph.get(node)){\n res += dfs(neigh, graph, visited);\n }\n return res + 1;\n }\n}", "solution_c": "class Solution {\npublic:\n double eucDis(int x1,int y1,int x2,int y2)\n {\n double temp=pow(x1-x2,2)+pow(y1-y2,2);\n return sqrt(temp);\n }\n void dfs(int node,vector&vis,vectorgraph[],int &c)\n {\n c++;\n vis[node]=1;\n for(auto i:graph[node])\n {\n if(!vis[i])\n {\n dfs(i,vis,graph,c);\n }\n }\n }\n int maximumDetonation(vector>& bombs) {\n \n int n=bombs.size();\n vectorgraph[n+1];\n int i,j;\n for(i=0;ivis(n+1,0);\n \n dfs(i,vis,graph,c); \n maxi=max(maxi,c);\n \n \n }\n return maxi;\n }\n};" }, { "title": "Count Hills and Valleys in an Array", "algo_input": "You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].\n\nNote that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.\n\nReturn the number of hills and valleys in nums.\n\n \nExample 1:\n\nInput: nums = [2,4,1,1,6,5]\nOutput: 3\nExplanation:\nAt index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.\n\n\nExample 2:\n\nInput: nums = [6,6,5,5,4,1]\nOutput: 0\nExplanation:\nAt index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.\n\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 100\n\t1 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def countHillValley(self, nums: List[int]) -> int:\n c = 0\n i = 1\n while i nums[i] and nums[j] > nums[i]) or (nums[i-1] < nums[i] and nums[j] < nums[i]):\n c += 1\n i = j\n return c", "solution_js": "var countHillValley = function(nums) {\n let previous;\n let count = 0;\n for (let i=0; i nums[previous] && nums[i] > nums[nextCheck]) {\n count++;\n }\n if(nums[i] < nums[previous] && nums[i] < nums[nextCheck]) {\n count++;\n }\n previous = i;\n i = nextCheck - 1;\n }\n return count;\n};", "solution_java": "class Solution {\n public int countHillValley(int[] nums) {\n int result = 0;\n \n\t\t// Get head start. Find first index for which nums[index] != nums[index-1]\n\t\tint start = 1;\n\t\twhile(start < nums.length && nums[start] == nums[start-1])\n\t\t\tstart++;\n\n\t\tint prev = start-1; //index of prev different value num\n\t\tfor(int i=start; i nums[prev] && nums[i] > nums[i+1]) //compare current num with prev number and next number\n\t\t\t\t\tresult++;\n\t\t\t\tif(nums[i] < nums[prev] && nums[i] < nums[i+1])\n\t\t\t\t\tresult++;\n\t\t\t\tprev = i; // Now your current number will become prev number.\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n}", "solution_c": "class Solution {\npublic:\n int countHillValley(vector& nums) {\n\t// taking a new vector\n vectorv;\n v.push_back(nums[0]);\n\t\t//pushing unique elements into new vector\n for(int i=1;iv[i-1] and v[i]>v[i+1] or v[i] str:\n counter = Counter(s)\n alphabets = \"abcdefghijklmnopqrstuvwxyz\"\n rev_alphabets = alphabets[::-1]\n total = len(s)\n res = []\n while total > 0:\n for c in alphabets:\n if counter[c]: \n res.append(c)\n counter[c] -= 1\n total -= 1\n for c in rev_alphabets:\n if counter[c]:\n res.append(c)\n counter[c] -= 1\n total -= 1\n return \"\".join(res)", "solution_js": "/**\n * @param {string} s\n * @return {string}\n */\nvar sortString = function(s) {\n const counts = [...s].reduce((acc, cur) => (acc[cur.charCodeAt() - 97] += 1, acc), new Array(26).fill(0));\n const result = [];\n\n const pick = (code) => {\n if (counts[code]) {\n result.push(String.fromCharCode(code + 97));\n counts[code] -= 1;\n }\n }\n\n while (result.length < s.length) {\n for (let i = 0; i < counts.length; i++) pick(i);\n for (let i = 0; i < counts.length; i++) pick(counts.length - 1 - i);\n }\n\n return result.join('');\n};", "solution_java": "class Solution {\n public String sortString(String s) {\n \n StringBuilder result = new StringBuilder();\n int[] freq = new int[26];\n for(char c: s.toCharArray()){\n freq[c-'a']++;\n }\n int remaining = s.length();\n while(remaining!=0){\n for(int i=0;i<26&&remaining!=0;i++){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n for(int i=25;i>=0&&remaining!=0;i--){\n if(freq[i]!=0){\n freq[i]--;\n result.append((char)(i+'a'));\n remaining--;\n }\n }\n }\n return result.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string sortString(string s) {\n int count [26]={0};\n for(int i =0 ;i< s.size();i++){\n char ch = s[i];\n count[ch-'a']++;\n }\n string res ;\n while(res.size()!=s.size()){\n for(int i = 0 ;i<26;i++){\n if(count[i] >0) {\n char ch = i+'a';\n res += ch;\n count[i]--;\n }\n }\n for(int i = 25 ;i>=0 ;i--){\n if(count[i] >0){\n char ch= i+'a';\n res += ch;\n count[i]--;\n }\n }\n }\n return res ;\n }\n};" }, { "title": "Longest Continuous Increasing Subsequence", "algo_input": "Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.\n\nA continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].\n\n \nExample 1:\n\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2]\nOutput: 1\nExplanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 104\n\t-109 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n count=0\n for i in range(len(nums)):\n a=nums[i]\n c=1\n for j in range(i+1, len(nums)):\n if nums[j]>a:\n a=nums[j]\n c+=1\n else:\n break\n count=max(count, c)\n return count", "solution_js": "var findLengthOfLCIS = function(nums) {\n let res = 0;\n let curr = 1;\n \n nums.forEach((num, idx) => {\n if (num < nums[idx + 1]) {\n curr++;\n }\n else curr = 1;\n \n res = Math.max(res, curr);\n })\n \n return res;\n};", "solution_java": "class Solution {\n public int findLengthOfLCIS(int[] nums) {\n int count = 1;\n int maxCount = 1;\n for (int i = 1; i < nums.length; i++) {\n if (nums[i] > nums[i - 1]) {\n count++;\n } else {\n maxCount = Math.max(count, maxCount);\n count = 1;\n }\n }\n maxCount = Math.max(count, maxCount);\n return maxCount;\n }\n}", "solution_c": "class Solution {\npublic:\n int findLengthOfLCIS(vector& nums) {\n int maxLength = 1;\n int currLength = 1;\n int i = 0;\n int j = 1;\n \n while(j nums[i]){\n currLength++;\n i++;\n j++;\n if(currLength > maxLength) maxLength = currLength;\n } else{\n currLength = 1;\n i = j;\n j++;\n }\n }\n return maxLength;\n }\n};" }, { "title": "Maximum Width Ramp", "algo_input": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.\n\nGiven an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.\n\n \nExample 1:\n\nInput: nums = [6,0,8,2,1,5]\nOutput: 4\nExplanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\n\n\nExample 2:\n\nInput: nums = [9,8,1,0,1,9,4,0,4,1]\nOutput: 7\nExplanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 5 * 104\n\t0 <= nums[i] <= 5 * 104\n\n", "solution_py": "class Solution:\n def maxWidthRamp(self, nums: List[int]):\n st=[]\n n=len(nums)\n for i in range(n):\n if len(st)==0 or nums[st[-1]]>=nums[i]:\n st.append(i)\n print(st)\n max_idx=-1\n for j in range(n-1,-1,-1):\n while len(st) and nums[st[-1]]<=nums[j]:\n prev=st.pop()\n max_idx=max(max_idx,j-prev)\n\n return max_idx", "solution_js": "var maxWidthRamp = function(nums) {\n let stack = [], ans = 0;\n for (let i = 0; i < nums.length; i++) {\n let index = lower_bound(stack, i);\n ans = Math.max(ans, i - index);\n if (!stack.length || nums[i] < nums[stack[stack.length - 1]]) stack.push(i);\n }\n return ans;\n \n function lower_bound(arr, index) {\n if (!arr.length) return index;\n let low = 0, high = arr.length - 1;\n while (low < high) {\n let mid = Math.floor((low + high) / 2);\n if (nums[arr[mid]] <= nums[index]) high = mid;\n else low = mid + 1;\n }\n return nums[arr[low]] <= nums[index] ? arr[low] : index;\n }\n};", "solution_java": "class Solution {\n public int maxWidthRamp(int[] nums) {\n Stack s = new Stack<>();\n int res = 0;\n for(int i = 0; i< nums.length; i++){\n if(!s.isEmpty() && nums[s.peek()]<=nums[i]) {\n res = Math.max(res, i-s.peek());\n continue;\n }\n s.push(i);\n }\n int i = nums.length-1;\n while(!s.isEmpty() && i>=0){\n if(nums[s.peek()]<=nums[i]){\n res = Math.max(res, i-s.peek());\n s.pop();\n }else{\n i--;\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxWidthRamp(vector& nums) {\n int n=nums.size();\n if(n==2){\n if(nums[0]<=nums[1])return 1;\n return 0;\n }\n stackst;\n for(int i=0;i=0;i--){\n while(!st.empty() && nums[i]>=nums[st.top()] ){ \n ramp=max(ramp,i-st.top());\n st.pop();\n }\n }\n return ramp;\n }\n};" }, { "title": "Insert Delete GetRandom O(1)", "algo_input": "Implement the RandomizedSet class:\n\n\n\tRandomizedSet() Initializes the RandomizedSet object.\n\tbool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.\n\tbool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.\n\tint getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.\n\n\nYou must implement the functions of the class such that each function works in average O(1) time complexity.\n\n \nExample 1:\n\nInput\n[\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n[[], [1], [2], [2], [], [1], [2], []]\nOutput\n[null, true, false, true, 2, true, false, 2]\n\nExplanation\nRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.\n\n\n \nConstraints:\n\n\n\t-231 <= val <= 231 - 1\n\tAt most 2 * 105 calls will be made to insert, remove, and getRandom.\n\tThere will be at least one element in the data structure when getRandom is called.\n\n", "solution_py": "class RandomizedSet:\n\n def __init__(self):\n self.data = set() \n\n def insert(self, val: int) -> bool:\n if val not in self.data:\n self.data.add(val)\n return True \n return False \n \n def remove(self, val: int) -> bool:\n if val in self.data:\n self.data.remove(val)\n return True \n return False \n\n def getRandom(self) -> int:\n return random.choice(list(self.data))", "solution_js": "var RandomizedSet = function() {\n this._data = [];\n this._flatData = [];\n};\n\nRandomizedSet.prototype.hash = function(val) {\n return val % 1e5;\n}\n\nRandomizedSet.prototype.insert = function(val) {\n const hash = this.hash(val);\n let basket = this._data[hash];\n \n for (let i = 0; i < basket?.length; i++) {\n if (basket[i][0] === val) { return false; }\n }\n \n if (!basket) {\n this._data[hash] = [[val, this._flatData.length]];\n } else {\n this._data[hash].push([val, this._flatData.length]);\n }\n this._flatData.push(val); \n return true;\n};\n\nRandomizedSet.prototype.remove = function(val) {\n const hash = this.hash(val);\n let basket = this._data[hash];\n if (!basket) { return false; }\n for (let i = 0; i < basket.length; i++) {\n const currBasket = basket[i];\n if (currBasket[0] === val) {\n const idxInFlat = currBasket[1];\n const reassignedValueInFlat = del(this._flatData, idxInFlat);\n // Write new address in _data if needed\n if (reassignedValueInFlat) {\n this._data[this.hash(reassignedValueInFlat)].forEach(item => {\n if (item[0] === reassignedValueInFlat) {\n item[1] = idxInFlat;\n return; // from forEach\n }\n });\n }\n // Delete from _data\n del(basket, i);\n return true;\n }\n }\n return false;\n};\n\nRandomizedSet.prototype.getRandom = function() {\n return this._flatData[getRandomInt(0, this._flatData.length - 1)];\n};\n\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nfunction del(arr, idx) {\n if (!arr.length) { return null; }\n if (idx === arr.length - 1) { arr.pop(); return null; }\n arr[idx] = arr.pop();\n return arr[idx];\n}", "solution_java": "class RandomizedSet {\n HashMap map;\n ArrayList list;\n Random rand;\n public RandomizedSet() {\n map = new HashMap<>();\n list = new ArrayList<>();\n rand = new Random();\n }\n \n public boolean insert(int val) {\n if (!map.containsKey(val)){\n map.put(val, list.size());\n list.add(val);\n return true;\n }\n return false;\n }\n \n public boolean remove(int val) {\n if (map.containsKey(val)){\n int index = map.get(val);\n int last = list.get(list.size() - 1);\n if (index != list.size() - 1){\n list.set(index, last);\n map.put(last, index);\n }\n list.remove(list.size() - 1); \n map.remove(val);\n return true;\n }\n return false;\n }\n \n public int getRandom() {\n int r = rand.nextInt(list.size()); \n return list.get(r);\n }\n}", "solution_c": "class RandomizedSet {\npublic:\n unordered_map mp;\n vector v;\n RandomizedSet() {\n \n }\n \n bool insert(int val) {\n if(mp.find(val) != mp.end()) return false;\n mp[val] = v.size();\n v.push_back(val);\n return true;\n }\n \n bool remove(int val) {\n if(mp.find(val) != mp.end()){\n v[mp[val]] = v.back();\n mp[v.back()] = mp[val];\n v.pop_back();\n mp.erase(val);\n return true;\n } \n return false;\n }\n \n int getRandom() {\n return v[rand()%v.size()];\n }\n};" }, { "title": "Sum of Two Integers", "algo_input": "Given two integers a and b, return the sum of the two integers without using the operators + and -.\n\n \nExample 1:\nInput: a = 1, b = 2\nOutput: 3\nExample 2:\nInput: a = 2, b = 3\nOutput: 5\n\n \nConstraints:\n\n\n\t-1000 <= a, b <= 1000\n\n", "solution_py": "class Solution(object):\n def getSum(self, a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n sol=(a,b)\n return sum(sol)\n\t```", "solution_js": "/**\n * @param {number} a\n * @param {number} b\n * @return {number}\n */\nvar getSum = function(a, b) {\n if (a==0){\n return b;\n }\n else if (b==0){\n return a;\n }\n else{\n return getSum((a^b),(a&b)<<1);\n }\n \n};", "solution_java": "class Solution {\n \n public int getSum(int a, int b) {\n return Integer.sum(a, b);\n }\n}", "solution_c": "class Solution {\npublic:\n int getSum(int a, int b) {\n vector arr = {a,b};\n return accumulate(arr.begin(),arr.end(),0);\n }\n};" }, { "title": "Maximum Sum of Two Non-Overlapping Subarrays", "algo_input": "Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.\n\nThe array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.\n\nA subarray is a contiguous part of an array.\n\n \nExample 1:\n\nInput: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput: 20\nExplanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\n\n\nExample 2:\n\nInput: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput: 29\nExplanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\n\n\nExample 3:\n\nInput: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput: 31\nExplanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n\n\n \nConstraints:\n\n\n\t1 <= firstLen, secondLen <= 1000\n\t2 <= firstLen + secondLen <= 1000\n\tfirstLen + secondLen <= nums.length <= 1000\n\t0 <= nums[i] <= 1000\n\n", "solution_py": "class Solution:\n def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:\n n = len(nums)\n p = [0]\n for el in nums:\n p.append(p[-1] + el)\n msum = 0\n for f, s in [(firstLen, secondLen), (secondLen, firstLen)]:\n for i in range(f - 1, n - s + 1):\n for j in range(i + 1, n - s + 1):\n l = p[i + 1] - p[i - f + 1]\n r = p[j + s] - p[j]\n msum = max(msum, l + r)\n return msum", "solution_js": "var maxSumTwoNoOverlap = function(nums, firstLen, secondLen) {\n function helper(arr, x, y)\n {\n const n = arr.length;\n let sum = 0;\n const dp1 = []; // store left x sum\n const dp2 = []; // store right y sum\n\n for(let i = 0; i=0; i--)\n {\n if(i>=n-y)\n {\n sum += arr[i];\n dp2[i] = sum;\n }\n else\n {\n sum += arr[i] - arr[i+y];\n dp2[i] = Math.max(dp2[i+1], sum);\n }\n }\n let max = -Infinity;\n for(let i = x-1; i< n-y; i++)\n {\n max = Math.max(max, dp1[i] + dp2[i+1]);\n }\n return max;\n }\n return Math.max(helper(nums, firstLen, secondLen), \n helper(nums, secondLen, firstLen));\n};", "solution_java": "class Solution {\n public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {\n int []dp1=new int[nums.length];\n int []dp2=new int[nums.length];\n \n int sum=0;\n for(int i=0;i=0;i--){\n if(i+secondLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+secondLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n int max=0;\n \n for(int i=firstLen-1;i=0;i--){\n if(i+firstLen>=nums.length){\n sum+=nums[i];\n dp2[i]=sum;\n }else{\n sum+=nums[i]-nums[i+firstLen];\n dp2[i]=Math.max(sum,dp2[i+1]);\n }\n }\n \n max=0;\n \n for(int i=secondLen-1;i& prefixSum, int n, int firstLen, int secondLen){\n vector dp(n, 0);\n \n dp[n-secondLen] = prefixSum[n]-prefixSum[n-secondLen];\n \n for(int i=n-secondLen-1; i>=0; i--){\n dp[i] = max(dp[i+1], prefixSum[i+secondLen]-prefixSum[i]);\n }\n \n dp[firstLen] = dp[firstLen] + prefixSum[firstLen]-prefixSum[0];\n \n for(int i=firstLen+1; i<=n-secondLen; i++){\n dp[i] = max(dp[i-1], dp[i] + (prefixSum[i]-prefixSum[i-firstLen]));\n }\n \n return *max_element(dp.begin(), dp.end());\n }\n \n int maxSumTwoNoOverlap(vector& nums, int firstLen, int secondLen) {\n int n = nums.size();\n vector prefixSum(n+1, 0);\n \n for(int i=1; i<=n; i++){\n prefixSum[i] = prefixSum[i-1] + nums[i-1];\n }\n \n return max(solve(prefixSum, n, firstLen, secondLen), solve(prefixSum, n, secondLen, firstLen));\n }\n};" }, { "title": "Minimum Cost For Tickets", "algo_input": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.\n\nTrain tickets are sold in three different ways:\n\n\n\ta 1-day pass is sold for costs[0] dollars,\n\ta 7-day pass is sold for costs[1] dollars, and\n\ta 30-day pass is sold for costs[2] dollars.\n\n\nThe passes allow that many days of consecutive travel.\n\n\n\tFor example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.\n\n\nReturn the minimum number of dollars you need to travel every day in the given list of days.\n\n \nExample 1:\n\nInput: days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput: 11\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.\n\n\nExample 2:\n\nInput: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput: 17\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.\n\n\n \nConstraints:\n\n\n\t1 <= days.length <= 365\n\t1 <= days[i] <= 365\n\tdays is in strictly increasing order.\n\tcosts.length == 3\n\t1 <= costs[i] <= 1000\n\n", "solution_py": "class Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n min_cost = float('inf')\n que = deque()\n # enqueue the possible state of day 1\n que.append((days[0], costs[0]))\n que.append((days[0]+7-1, costs[1]))\n que.append((days[0]+30-1, costs[2]))\n last_day = days[-1]\n for i in range(1, len(days)):\n for _ in range(len(que)):\n node = que.popleft()\n if node[0] < days[i]:\n # try taking all the three pass on that day and enqueue \n que.append((days[i], node[1]+costs[0]))\n if days[i] + 7 - 1 >= last_day:\n min_cost = min(min_cost, node[1] + costs[1])\n else:\n que.append((days[i]+7-1, node[1]+costs[1]))\n if days[i] + 30 - 1 >= last_day: \n min_cost = min(min_cost, node[1] + costs[2])\n else:\n que.append((days[i]+30-1, node[1]+costs[2]))\n else:\n que.append(node)\n for _ in range(len(que)):\n node = que.popleft()\n min_cost = min(min_cost, node[1])\n return min_cost", "solution_js": "var mincostTickets = function(days, costs) {\n let store = {};\n for(let i of days) {\n store[i] = true\n }\n let lastDay = days[days.length - 1]\n let dp = new Array(days[days.length - 1] + 1).fill(Infinity);\n dp[0] = 0;\n\n for(let i = 1; i< days[days.length - 1] + 1; i++) {\n if(!store[i]) {\n dp[i] = dp[i-1];\n continue;\n }\n dp[i] = costs[0] + dp[i-1];\n dp[i] = Math.min(costs[1] + dp[Math.max(i - 7, 0)], dp[i]);\n dp[i] = Math.min(costs[2] + dp[Math.max(i - 30, 0)], dp[i]);\n }\n\n return dp[lastDay]\n\n};", "solution_java": "class Solution {\n public int mincostTickets(int[] days, int[] costs) {\n HashSet set = new HashSet<>();\n for(int day: days) set.add(day);\n int n = days[days.length - 1];\n int[] dp = new int[n + 1];\n Arrays.fill(dp, Integer.MAX_VALUE);\n dp[0] = 0;\n for(int i = 1; i <= n; i++){\n if(!set.contains(i)){\n dp[i] = dp[i - 1];\n continue;\n }\n int a = dp[Math.max(0, i - 1)] + costs[0];\n int b = dp[Math.max(0, i - 7)] + costs[1];\n int c = dp[Math.max(0, i - 30)] + costs[2];\n dp[i] = Math.min(a, Math.min(b, c));\n }\n return dp[n];\n }\n}", "solution_c": "class Solution {\npublic:\n int f(int i,int j,vector& days,vector& costs,vector>& dp) {\n if (i==days.size()) return 0;\n if (days[i]& days, vector& costs) {\n vector> dp(days.size(),vector(days[days.size()-1]+1,-1));\n return f(0,1,days,costs,dp);\n }\n};" }, { "title": "Circular Array Loop", "algo_input": "You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:\n\n\n\tIf nums[i] is positive, move nums[i] steps forward, and\n\tIf nums[i] is negative, move nums[i] steps backward.\n\n\nSince the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.\n\nA cycle in the array consists of a sequence of indices seq of length k where:\n\n\n\tFollowing the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...\n\tEvery nums[seq[j]] is either all positive or all negative.\n\tk > 1\n\n\nReturn true if there is a cycle in nums, or false otherwise.\n\n \nExample 1:\n\nInput: nums = [2,-1,1,2,2]\nOutput: true\nExplanation:\nThere is a cycle from index 0 -> 2 -> 3 -> 0 -> ...\nThe cycle's length is 3.\n\n\nExample 2:\n\nInput: nums = [-1,2]\nOutput: false\nExplanation:\nThe sequence from index 1 -> 1 -> 1 -> ... is not a cycle because the sequence's length is 1.\nBy definition the sequence's length must be strictly greater than 1 to be a cycle.\n\n\nExample 3:\n\nInput: nums = [-2,1,-1,-2,-2]\nOutput: false\nExplanation:\nThe sequence from index 1 -> 2 -> 1 -> ... is not a cycle because nums[1] is positive, but nums[2] is negative.\nEvery nums[seq[j]] must be either all positive or all negative.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 5000\n\t-1000 <= nums[i] <= 1000\n\tnums[i] != 0\n\n\n \nFollow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?\n", "solution_py": "class Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n n = len(nums)\n for i in range(n):\n seen = set()\n minval = float('inf')\n maxval = float('-inf')\n j = i\n while j not in seen:\n seen.add(j)\n minval = min(minval, nums[j])\n maxval = max(maxval, nums[j])\n k = 1 + abs(nums[j]) // n\n j = (k * n + j + nums[j]) % n\n if j == i and len(seen) > 1 and (minval > 0 or maxval < 0):\n return True\n return False", "solution_js": "var circularArrayLoop = function(nums) {\n // cannot be a cycle if there are less than 2 elements\n const numsLen = nums.length;\n if (numsLen < 2) return false;\n\n // init visited array\n const visited = Array(numsLen).fill(false);\n\n // check each index to see if a cycle can be produced\n for (let i = 0; i < numsLen; i++) {\n if (visited[i]) continue;\n visited[i] = true;\n // determine initial direction\n const isPositive = nums[i] > 0;\n \n // reset which indices were visited after each iteration\n const visitedPerIdx = Array(numsLen).fill(false);\n \n // reset cycle length and current index after each iteration\n let cycleLen = 0,\n currIdx = i;\n \n // loop while cycle is valid\n while (true) {\n // break if current index moves cycle in opposite direction\n if (isPositive !== nums[currIdx] > 0) break;\n\t\t\t\n // calc next valid index\n let nextIdx = (currIdx + nums[currIdx]) % numsLen;\n // map negative index to a positive index\n if (nextIdx < 0) nextIdx += numsLen; \n \n // break if cycle points to same index\n if (currIdx === nextIdx) break;\n \n cycleLen++; \n\t\t\t// a cycle is found when the index has already been visited in the current outer iteration, and\n\t\t\t// the cycle length is greater than 1.\n if (visitedPerIdx[nextIdx] && cycleLen > 1) return true;\n\t\t\t\n visitedPerIdx[nextIdx] = true;\n visited[nextIdx] = true;\n // set curr index to new index\n currIdx = nextIdx;\n }\n }\n\n return false;\n};", "solution_java": "class Solution {\n public boolean circularArrayLoop(int[] nums) {\n for (int i=0; i 0;\n int slow = i;\n int fast = i; \n do {\n slow = findNextIndex(nums, isForward, slow);\n fast = findNextIndex(nums, isForward, fast);\n if (fast != -1) {\n fast = findNextIndex(nums, isForward, fast);\n }\n } while (slow != -1 && fast != -1 && slow != fast);\n if (slow != -1 && slow == fast) {\n return true;\n }\n }\n return false;\n }\n private int findNextIndex(int[] arr, boolean isForward, int currentIndex) {\n boolean direction = arr[currentIndex] >= 0;\n if (isForward != direction) {\n return -1;\n }\n int nextIndex = (currentIndex + arr[currentIndex]) % arr.length;\n if (nextIndex < 0) {\n nextIndex += arr.length;\n }\n if (nextIndex == currentIndex) {\n nextIndex = -1;\n }\n return nextIndex;\n }\n}", "solution_c": "class Solution {\npublic:\n bool circularArrayLoop(vector& nums) {\n unordered_setus;\n for(int i{0};ium;\n int index=0;\n int j=i;\n um[i];\n bool flag1=0,flag2=0;\n while(true){\n if(nums.at(i)<0){\n index=(nums.size()+nums.at(j)+j)%nums.size();\n flag1=1;\n }else{\n index=(nums.at(j)+j)%nums.size();\n flag2=1;\n }\n if(nums.at(index)>0 && flag1==1){\n break;\n }else if(nums.at(index)<0 && flag2==1){\n break;\n }\n if(um.find(index)==um.end()){\n um[index];\n us.insert(index);\n }else{\n if(j==index){\n break;\n }\n if(um.size()>1){\n return true;\n }else{\n break;\n }\n }\n j=index;\n } \n }\n return false;\n }\n};" }, { "title": "Repeated DNA Sequences", "algo_input": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.\n\n\n\tFor example, \"ACGAATTCCG\" is a DNA sequence.\n\n\nWhen studying DNA, it is useful to identify repeated sequences within the DNA.\n\nGiven a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.\n\n \nExample 1:\nInput: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput: [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\nExample 2:\nInput: s = \"AAAAAAAAAAAAA\"\nOutput: [\"AAAAAAAAAA\"]\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts[i] is either 'A', 'C', 'G', or 'T'.\n\n", "solution_py": "class Solution(object):\n def findRepeatedDnaSequences(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n seqs = {}\n i = 0\n while i+10 <= len(s):\n curr = s[i:i+10]\n if curr in seqs:\n seqs[curr] = seqs[curr] + 1\n else:\n seqs[curr] = 1\n i += 1\n\n repeats = []\n for seq in list(seqs.keys()):\n if seqs[seq] > 1:\n repeats.append(seq)\n\n return repeats", "solution_js": "// 187. Repeated DNA Sequences\nvar findRepeatedDnaSequences = function(s) {\n let map = {};\n\tlet res = [];\n\tfor (let i = 0; i <= s.length-10; i++) {\n\t\tlet s10 = s.substring(i, i+10);\n\t\tmap[s10] = (map[s10] || 0) + 1;\n\t\tif (map[s10] === 2) res.push(s10);\n\t}\n\treturn res;\n};", "solution_java": "class Solution {\n public List findRepeatedDnaSequences(String s) {\n HashMap map =new HashMap();\n int i=0;\n int j=0;\n int k=10;\n StringBuilder sb=new StringBuilder(\"\");\n\n while(j list=new ArrayList();\n for(Map.Entry mapElement:map.entrySet()){\n if(mapElement.getValue()>1){\n list.add(mapElement.getKey());\n }\n }\n return list;\n }\n}", "solution_c": "class Solution {\n\tpublic:\n\t\tvector findRepeatedDnaSequences(string s) {\n\t\t\tunordered_map freq;\n\t\t\tint start = 0 , end = 9;\n\t\t\twhile(end < s.size()){\n\t\t\t\tbool flag = true;\n\t\t\t\tfor(int i = start ; i <= end ; i++){\n\t\t\t\t\tif(s[i] == 'A' or s[i] == 'C' or s[i] == 'G' or s[i] == 'T') continue;\n\t\t\t\t\telse {flag = false ; break ;}\n\t\t\t\t}\n\t\t\t\tif(flag){\n\t\t\t\t\tstring temp = s.substr(start , 10);\n\t\t\t\t\tfreq[temp]++;\n\t\t\t\t}\n\t\t\t\tstart++;\n\t\t\t\tend++;\n\t\t\t}\n\t\t\tvector ans;\n\t\t\tfor(auto it : freq){\n\t\t\t\tif(it.second >= 2) ans.push_back(it.first);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n};" }, { "title": "Minimum Number of Frogs Croaking", "algo_input": "You are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed.\n\nReturn the minimum number of different frogs to finish all the croaks in the given string.\n\nA valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1.\n\n \nExample 1:\n\nInput: croakOfFrogs = \"croakcroak\"\nOutput: 1 \nExplanation: One frog yelling \"croak\" twice.\n\n\nExample 2:\n\nInput: croakOfFrogs = \"crcoakroak\"\nOutput: 2 \nExplanation: The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".\n\n\nExample 3:\n\nInput: croakOfFrogs = \"croakcrook\"\nOutput: -1\nExplanation: The given string is an invalid combination of \"croak\" from different frogs.\n\n\n \nConstraints:\n\n\n\t1 <= croakOfFrogs.length <= 105\n\tcroakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.\n\n", "solution_py": "class Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n c = r = o = a = k = max_frog_croak = present_frog_croak = 0\n # need to know, at particular point,\n # what are the max frog are croaking,\n\n for i, v in enumerate(croakOfFrogs):\n if v == 'c':\n c += 1\n\t\t\t\t# c gives a signal for a frog\n present_frog_croak += 1\n elif v == 'r':\n r += 1\n elif v == 'o':\n o += 1\n elif v == 'a':\n a += 1\n else:\n k += 1\n\t\t\t\t# frog stop croaking\n present_frog_croak -= 1\n\n max_frog_croak = max(max_frog_croak, present_frog_croak)\n # if any inoder occurs;\n if c < r or r < o or o < a or a < k:\n return -1\n\n # if all good, else -1\n if present_frog_croak == 0 and c == r and r == o and o == a and a == k:\n return max_frog_croak\n return -1", "solution_js": "var minNumberOfFrogs = function(croakOfFrogs) {\n const croakArr = new Array(5).fill(0); //Array to store occurence of each char\n let overlap = 0; //Store the number of overlaps\n for(let i = 0; i < croakOfFrogs.length; i++) {\n switch(croakOfFrogs[i]) {\n case 'c':\n croakArr[0] += 1;\n //Check if new start, is overlapping with others\n if((croakArr[0] - croakArr[4] - overlap) > 1) {\n ++overlap;\n }\n break;\n case 'r':\n //Condition to check if r comes before c\n if(croakArr[0] <= croakArr[1]) return -1;\n croakArr[1] += 1;\n break;\n case 'o':\n //Condition to check if o comes before r\n if(croakArr[1] <= croakArr[2]) return -1;\n croakArr[2] += 1;\n break;\n case 'a':\n //Condition to check if a comes before o\n if(croakArr[2] <= croakArr[3]) return -1;\n croakArr[3] += 1;\n break;\n case 'k':\n //Condition to check if k comes before a\n if(croakArr[3] <= croakArr[4]) return -1;\n croakArr[4] += 1;\n break;\n }\n }\n //Check if all items of array have same count else return -1\n //If all items have same count return overlap + 1\n return (Math.max(...croakArr) === Math.min(...croakArr)) ? overlap + 1 : -1;\n};", "solution_java": "class Solution {\n public int minNumberOfFrogs(String croakOfFrogs) {\n int[] index = new int[26];\n String corak = \"croak\";\n\n // Giving index to each characters\n for (int i = 0; i < corak.length(); ++i)\n index[corak.charAt(i) - 'a'] = i;\n\n int ans = 0, sum = 0;\n int[] count = new int[5];\n\n for (char c : croakOfFrogs.toCharArray()) {\n int i = index[c - 'a'];\n // If it is not 'c' it will decrease the sum\n if (c != 'c') {\n if (count[i - 1]-- <= 0) return -1;\n sum--;\n }\n // If it is not 'k' it will increase the sum\n if (c != 'k') {\n count[i]++;\n sum++;\n }\n ans = Math.max(ans, sum);\n }\n return sum == 0 ? ans : -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int minNumberOfFrogs(string croakOfFrogs) {\n unordered_map mp;\n int size=croakOfFrogs.size();\n \n for(int i=0;ians)\n ans=temp;\n }\n return ans;\n }\n};" }, { "title": "Unique Binary Search Trees", "algo_input": "Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.\n\n \nExample 1:\n\nInput: n = 3\nOutput: 5\n\n\nExample 2:\n\nInput: n = 1\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= n <= 19\n\n", "solution_py": "class Solution(object):\n def numTrees(self, n):\n if n == 0 or n == 1:\n return 1\n # Create 'sol' array of length n+1...\n sol = [0] * (n+1)\n # The value of the first index will be 1.\n sol[0] = 1\n # Run a loop from 1 to n+1...\n for i in range(1, n+1):\n # Within the above loop, run a nested loop from 0 to i...\n for j in range(i):\n # Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1]\n # Return the value of the nth index of the array to get the solution...\n return sol[n]", "solution_js": "var numTrees = function(n) {\n // Create 'sol' array to store the solution...\n var sol = [1, 1];\n // Run a loop from 2 to n...\n for (let i = 2; i <= n; i++) {\n sol[i] = 0;\n // Within the above loop, run a nested loop from 1 to i...\n for (let j = 1; j <= i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[i - j] * sol[j - 1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n};", "solution_java": "class Solution {\n public int numTrees(int n) {\n // Create 'sol' array of length n+1...\n int[] sol = new int[n+1];\n // The value of the first index will be 1.\n sol[0] = 1;\n // Run a loop from 1 to n+1...\n for(int i = 1; i <= n; i++) {\n // Within the above loop, run a nested loop from 0 to i...\n for(int j = 0; j < i; j++) {\n // Update the i-th position of the array by adding the multiplication of the respective index...\n sol[i] += sol[j] * sol[i-j-1];\n }\n }\n // Return the value of the nth index of the array to get the solution...\n return sol[n];\n }\n}", "solution_c": "class Solution {\npublic:\n \n int catalan (int n,vector &dp)\n {\n if(n<=1)\n return 1;\n \n int ans =0;\n for(int i=0;i dp(n+1,-1);\n \n dp[0] = 1;\n dp[1] = 1;\n \n for(int i=2;i<=n;i++)\n {\n int ans = 0;\n for(int j=0;j List[int]:\n\n\tres = map(self.h_fcn, self.f_fcn(restaurants, veganFriendly, maxPrice, maxDistance))\n\n\n\treturn map(lambda x: x[0], sorted(res, key=lambda x: (-x[1], -x[0])))", "solution_js": "var filterRestaurants = function(restaurants, veganFriendly, maxPrice, maxDistance) {\n let result = []\n // veganFriendly filter\n if(veganFriendly === 1){\n restaurants = restaurants.filter(restaurant=> restaurant[2] === 1) \n }\n \n //max price\n restaurants = restaurants.filter(restaurant=>restaurant[3]<=maxPrice)\n \n // max distance\n restaurants = restaurants.filter(restaurant=>restaurant[4]<=maxDistance)\n \n restaurants.sort((a,b)=>b[1]-a[1])\n \n let tempArr = []\n for(let i=0; i0){\n tempArr.sort((a,b)=>b-a)\n result =[...result,...tempArr] \n tempArr=[]\n } \n result.push(restaurants[i][0])\n }\n \n }\n \n return result\n};", "solution_java": "class Restaurant {\n int id, rating;\n Restaurant(int id, int rating) {\n this.id = id;\n this.rating = rating;\n }\n}\n\nclass RestaurantComparator implements Comparator {\n @Override\n public int compare(Restaurant r1, Restaurant r2) {\n return r1.rating == r2.rating ? r2.id - r1.id : r2.rating - r1.rating;\n }\n}\n\nclass Solution {\n public List filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {\n PriorityQueue heap = new PriorityQueue<>(new RestaurantComparator());\n if(veganFriendly == 1) {\n for(int[] restaurant: restaurants) {\n if(restaurant[2] == 1 && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n } else {\n for(int[] restaurant: restaurants) {\n if(restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {\n heap.offer(new Restaurant(restaurant[0], restaurant[1]));\n }\n }\n }\n List answer = new ArrayList<>();\n while(!heap.isEmpty()) {\n answer.add(heap.poll().id);\n }\n return answer;\n }\n}", "solution_c": "//comparator class for sorting restaurants by their rating \nclass comp{\n public:\n bool operator ()(vectora,vectorb){\n\t\t//same rating then sort by ids\n if(a[1]==b[1]) return a[0]>b[0];\n return a[1]>b[1];\n }\n};\nclass Solution {\npublic:\n vector filterRestaurants(vector>& restaurants, int veganFriendly, int maxPrice, int maxDistance)\n\t\t{ //sort restaurants by their rating\n sort(restaurants.begin(),restaurants.end(),comp());\n vectorans;\n for(int i=0;i int:\n m,n=len(grid),len(grid[0])\n q=deque()\n start,target,box=(0,0),(0,0),(0,0)\n for i in range(m):\n for j in range(n):\n if grid[i][j]==\"B\":\n box=(i,j)\n elif grid[i][j]==\"T\":\n target=(i,j)\n elif grid[i][j]==\"S\":\n start=(i,j)\n q.append((box[0],box[1],0,start[0],start[1]))\n visited=set()\n directions=((1,0,-1,0),(0,1,0,-1),(-1,0,1,0),(0,-1,0,1))\n visited.add(box+box)\n def solve(i,j,bi,bj):\n nonlocal seen\n if (i,j)==(bi,bj):\n return True\n ans=False\n for d in directions:\n ni,nj=i+d[0],j+d[1]\n if 0<=nim+n:\n return -1\n for d in directions:\n ni,nj,bi,bj=i+d[0],j+d[1],i+d[2],j+d[3]\n if 0<=ni [a[0] + b[0], a[1] + b[1]]\n const equals = (a, b) => a[0] === b[0] && a[1] === b[1]\n const validate = ([x, y]) => x >= 0 && y >= 0 && x < m && y < n\n const getKey = ([x, y]) => x * n + y\n\n // find all player, ball, target, and free cells\n const init = () => {\n let player\n let ball\n let target\n const freeSet = new Set()\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n if (grid[i][j] === '.') {\n freeSet.add(getKey([i, j]))\n } else if (grid[i][j] === 'S') {\n freeSet.add(getKey([i, j]))\n player = [i, j]\n } else if (grid[i][j] === 'B') {\n freeSet.add(getKey([i, j]))\n ball = [i, j]\n } else if (grid[i][j] === 'T') {\n freeSet.add(getKey([i, j]))\n target = [i, j]\n }\n }\n }\n return { player, ball, target, freeSet }\n }\n const { player, ball, target, freeSet } = init()\n const targetKey = getKey(target)\n\n // detect whether two cells are connected\n const connCache = new Map() // [x,y,x2,y2,x3,y3] => boolean\n const getConnKey = (a, b, ball) => {\n if (\n a[0] > b[0] ||\n a[0] === b[0] && a[1] > b[1]\n ) {\n [a, b] = [b, a]\n }\n return [a[0], a[1], b[0], b[1], ball[0], ball[1]].join(',')\n }\n const isConnected = (a, b, ball) => {\n if (a[0] === b[0] && a[1] === b[1]) {\n return true\n }\n const connKey = getConnKey(a, b, ball)\n if (connCache.has(connKey)) {\n return connCache.get(connKey)\n }\n const bKey = getKey(b)\n const ballKey = getKey(ball)\n const visited = new Array(m * n).fill(false)\n visited[getKey(a)] = true\n const queue = [a]\n while (queue.length) {\n const cell = queue.shift()\n for (let i = 0; i < dirs.length; i++) {\n const next = add(cell, dirs[i])\n if (validate(next)) {\n const nextKey = getKey(next)\n if (nextKey === bKey) {\n connCache.set(connKey, true)\n return true\n }\n if (\n freeSet.has(nextKey) &&\n nextKey !== ballKey &&\n !visited[nextKey]\n ) {\n visited[nextKey] = true\n queue.push(next)\n }\n }\n }\n }\n connCache.set(connKey, false)\n return false\n }\n\n // solve the game\n const getStateKey = ([x, y], [xx, yy]) => [x, y, xx, yy].join(',') // ball, player\n const stateCache = new Set() // Set\n let queue = [[ball, player]]\n let count = 1\n while (queue.length) {\n const nextQueue = []\n for (let i = 0; i < queue.length; i++) {\n const [ball, player] = queue[i]\n for (let j = 0; j < dirs.length; j++) {\n const dir = dirs[j]\n const reverseDir = [dir[0] ? -dir[0] : 0, dir[1] ? -dir[1] : 0]\n const nextBall = add(ball, dir)\n const nextPlayer = add(ball, reverseDir)\n const nextBallKey = getKey(nextBall)\n const nextPlayerKey = getKey(nextPlayer)\n if (\n validate(nextBall) &&\n validate(nextPlayer) &&\n freeSet.has(nextBallKey) &&\n freeSet.has(nextPlayerKey)\n ) {\n const nextStateKey = getStateKey(nextBall, nextPlayer)\n if (isConnected(player, nextPlayer, ball)) {\n if (!stateCache.has(nextStateKey)) {\n stateCache.add(nextStateKey)\n if (nextBallKey === targetKey) {\n return count\n }\n nextQueue.push([nextBall, nextPlayer])\n }\n }\n }\n }\n }\n queue = nextQueue\n count++\n }\n return -1\n};", "solution_java": "/**\n Finds Initial State (State consists of shopkeeper & box locations + # of boxMoves)\n Uses BFS/A* Algorithm to visit valid transition states\n Note: The min heuristic here is # of boxMoves + manHattanDistance between box & target locations\n*/\nclass Solution {\n private int targetRow;\n private int targetCol;\n private char[][] grid;\n private static int[][] DIRS = {\n {1,0}, //Down\n {-1,0},//Up\n {0,1}, //Right\n {0,-1} //Left\n };\n\n /**\n State holds shopkeeper and box location, as well as how many times the box has been pushed\n */\n class State implements Comparable{\n int personRow;\n int personCol;\n int boxRow;\n int boxCol;\n int boxPushes;\n\n public State(int personRow, int personCol, int boxRow, int boxCol, int boxPushes){\n this.personRow = personRow;\n this.personCol = personCol;\n this.boxRow = boxRow;\n this.boxCol = boxCol;\n this.boxPushes = boxPushes;\n }\n\n // Override equals - used along with hashcode when we have visited HashSet\n public boolean equals(Object o){\n State other = (State) o;\n return\n this.personRow == other.personRow &&\n this.personCol == other.personCol &&\n this.boxRow == other.boxRow &&\n this.boxCol == other.boxCol;\n }\n\n // Override the hashCode - Note: it's okay for this to have collisions\n // But it won't due to the problem constraint that there is a bound on NxM dimensions\n public int hashCode(){\n return personRow *10_000 + personCol * 1_000 + boxRow * 100 + boxCol;\n }\n\n // Override to string method - helpful in debugging state.\n public String toString(){\n return \"ShopKeeper:{row:\"+personRow+\", col:\"+personCol+\"}\" +\n \"Box:{row:\"+boxRow+\", col:\"+boxCol+\"}\";\n }\n\n // Implement comparable interface such that we return the state that\n // has the possibility of lowest distance using box push count + Manhattan distance\n public int compareTo(State other){\n int minDistanceThis = this.boxPushes + distanceToTarget(this);\n int minDistanceOther = other.boxPushes + distanceToTarget(other);\n return Integer.compare(minDistanceThis, minDistanceOther);\n }\n\n }\n\n // Calculates Manhattan distance\n private int distanceToTarget(State state){\n int yDiff = Math.abs(state.boxCol - targetCol);\n int xDiff = Math.abs(state.boxRow - targetRow);\n return yDiff + xDiff;\n }\n\n /**\n Given a state, compare box location to target location to determine if it is\n a solution state.\n */\n private boolean isSolutionState(State state){\n return state.boxRow == targetRow && state.boxCol == targetCol;\n }\n\n /**\n Given a state, finds all valid transition states.\n This is accomplished by moving the ShopKeeper in all 4 directions and validate\n - Next ShopKeeper location is in bounds and is not a wall\n\n We have additional logic for when the next shopkeeper location is the box location:\n - Get next box location, by pushing the same direction, again validate that\n the next box location is in bounds, and is not a wall.\n\n If it's a valid transition, create the new state with the new shop keeper location\n and if the box moved, the new box location (also increment the number of box moves).\n\n **/\n private List getNeighbors(State state){\n\n int personRow = state.personRow;\n int personCol = state.personCol;\n int boxRow = state.boxRow;\n int boxCol = state.boxCol;\n\n List states = new ArrayList<>();\n for(int[] dir : DIRS){\n int rowMove = dir[0];\n int colMove = dir[1];\n int personRowNew = personRow + rowMove;\n int personColNew = personCol + colMove;\n // Shopkeeper cannot move into wall or go out of bounds skip to next direction\n if(!inBounds(personRowNew, personColNew) ||\n isWall(personRowNew, personColNew)){\n continue;\n }\n // Whether or not person will collide with box\n boolean willPushBox = personRowNew == boxRow && personColNew == boxCol;\n\n if(willPushBox){\n int boxRowNew = boxRow + rowMove;\n int boxColNew = boxCol + colMove;\n // Validate box can be pushed - if so push box and add to neighbor states\n if(inBounds(boxRowNew, boxColNew) &&\n !isWall(boxRowNew, boxColNew)){\n states.add(new State(personRowNew, personColNew, boxRowNew, boxColNew, state.boxPushes + 1));\n }\n } else {\n //Shop keeper moved, but not box\n states.add(new State(personRowNew, personColNew, boxRow, boxCol, state.boxPushes));\n }\n }\n return states;\n\n }\n\n // Given row/col, return whether it is wall\n private boolean isWall(int row, int col){\n char cell = grid[row][col];\n return cell == '#';\n }\n\n // Given row/col return whether is inBounds\n private boolean inBounds(int row, int col){\n int rows = grid.length;\n int cols = grid[0].length;\n if(row < 0 || col < 0 || row > rows-1 || col > cols-1){\n return false;\n }\n return true;\n }\n\n /**\n Returns initial state. Also finds and stores the target location.\n */\n private State getInitialState(){\n\n int shopKeeperRow=0;\n int shopKeeperCol=0;\n\n int boxRow = 0;\n int boxCol = 0;\n\n for(int r=0; r queue = new PriorityQueue<>();\n Set visited = new HashSet<>();\n queue.offer(initialState);\n\n // Explore every state using BSF and keep track of the best solution\n while(!queue.isEmpty()){\n State state = queue.poll();\n if(visited.contains(state)){\n continue;\n }\n visited.add(state);\n /*\n Note: the reason we can return the first solution state we find, is because we are\n using priority queue with minDistance heuristic which means the first solution we find\n is guaranteed to be the optimal solution - (A* Algorithm)\n */\n if(isSolutionState(state)){\n return state.boxPushes;\n }\n for(State neighbor : getNeighbors(state)){\n if(!visited.contains(neighbor)){\n queue.offer(neighbor);\n }\n };\n }\n // No solution - return -1\n return -1;\n }\n\n}", "solution_c": "class Solution {\npublic:\n \n pair t; //target\n pair s; //source\n pair b; //box\n \n // struct to store each member in priority queue\n struct node {\n int heuristic; // to find the dist between target and box\n int dist; // to keep track of how much the box moved\n pair src; // to store the source\n pair dest; // to store the box location\n };\n \n struct comp {\n bool operator()(node const& a, node const& b){\n return a.heuristic + a.dist > b.heuristic + b.dist;\n }\n };\n \n int direction[4][2]= {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};\n \n int minPushBox(vector>& grid) {\n \n int m=grid.size();\n int n=grid[0].size();\n \n for(int i=0;i,comp> pq;\n set visited;\n \n node initialState = node{manhattanDist(b.first,b.second),0,s,b};\n string initialStr = hash(initialState);\n \n pq.push(initialState);\n \n while(!pq.empty()){\n auto cur = pq.top();\n pq.pop();\n \n // we have reached the target return\n if(cur.dest == t) \n return cur.dist;\n \n // hash the cur string and \n string cur_vis = hash(cur);\n if(visited.count(cur_vis)) continue;\n \n // mark it as visited\n visited.insert(cur_vis);\n \n // in all the four directions\n for(auto& dir:direction){\n int sx = cur.src.first + dir[0];\n int sy = cur.src.second + dir[1];\n \n // if the new source is valid index\n if(valid(sx,sy,grid)){\n \n //if the source is equal to the where the box is\n if(sx == cur.dest.first && sy == cur.dest.second){\n int bx=cur.dest.first + dir[0];\n int by=cur.dest.second + dir[1];\n \n // if the box is at right position\n if(valid(bx,by,grid)){\n \n // increment the dist by 1 and update the source and box location\n node updated = node{manhattanDist(bx,by),cur.dist+1,{sx,sy},{bx,by}};\n pq.push(updated);\n }\n }else{\n // update the new location of source \n node updated = node{cur.heuristic,cur.dist,{sx,sy},cur.dest};\n pq.push(updated);\n }\n }\n }\n }\n \n // we cannot perform the operation\n return -1;\n \n }\n \n string hash(node t){\n stringstream ss;\n ss<>& g){\n \n if(i<0 || j<0 || i>=g.size() || j>=g[0].size() || g[i][j]=='#') return false;\n \n return true;\n }\n};" }, { "title": "Encrypt and Decrypt Strings", "algo_input": "You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.\n\nA string is encrypted with the following process:\n\n\n\tFor each character c in the string, we find the index i satisfying keys[i] == c in keys.\n\tReplace c with values[i] in the string.\n\n\nNote that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string \"\" is returned.\n\nA string is decrypted with the following process:\n\n\n\tFor each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.\n\tReplace s with keys[i] in the string.\n\n\nImplement the Encrypter class:\n\n\n\tEncrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary.\n\tString encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.\n\tint decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.\n\n\n \nExample 1:\n\nInput\n[\"Encrypter\", \"encrypt\", \"decrypt\"]\n[[['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]], [\"abcd\"], [\"eizfeiam\"]]\nOutput\n[null, \"eizfeiam\", 2]\n\nExplanation\nEncrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]);\nencrypter.encrypt(\"abcd\"); // return \"eizfeiam\". \n  // 'a' maps to \"ei\", 'b' maps to \"zf\", 'c' maps to \"ei\", and 'd' maps to \"am\".\nencrypter.decrypt(\"eizfeiam\"); // return 2. \n // \"ei\" can map to 'a' or 'c', \"zf\" maps to 'b', and \"am\" maps to 'd'. \n // Thus, the possible strings after decryption are \"abad\", \"cbad\", \"abcd\", and \"cbcd\". \n // 2 of those strings, \"abad\" and \"abcd\", appear in dictionary, so the answer is 2.\n\n\n \nConstraints:\n\n\n\t1 <= keys.length == values.length <= 26\n\tvalues[i].length == 2\n\t1 <= dictionary.length <= 100\n\t1 <= dictionary[i].length <= 100\n\tAll keys[i] and dictionary[i] are unique.\n\t1 <= word1.length <= 2000\n\t1 <= word2.length <= 200\n\tAll word1[i] appear in keys.\n\tword2.length is even.\n\tkeys, values[i], dictionary[i], word1, and word2 only contain lowercase English letters.\n\tAt most 200 calls will be made to encrypt and decrypt in total.\n\n", "solution_py": "class Encrypter:\n\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n self.hashmap = dict()\n for i in range(len(keys)):\n self.hashmap[keys[i]] = values[i]\n self.dictmap = defaultdict(int)\n for word in dictionary:\n self.dictmap[self.encrypt(word)] += 1\n\n def encrypt(self, word1: str) -> str:\n output = ''\n for char in word1:\n output += self.hashmap[char]\n return output\n\n def decrypt(self, word2: str) -> int:\n return self.dictmap[word2]", "solution_js": "var Encrypter = function(keys, values, dictionary) {\n this.encryptMap = new Map();\n for (let i = 0; i < keys.length; i++) {\n this.encryptMap.set(keys[i], values[i]);\n }\n this.dict = new Set(dictionary);\n // Encypt the values in dict for easy comparison later\n this.encryptedVals = [];\n for (let word of this.dict) {\n this.encryptedVals.push(this.encrypt(word));\n }\n};\nEncrypter.prototype.encrypt = function(word1) {\n let encrypted = '';\n for (let char of word1) {\n encrypted += this.encryptMap.get(char);\n }\n return encrypted;\n};\nEncrypter.prototype.decrypt = function(word2) {\n return this.encryptedVals.filter(x => x === word2).length;\n};", "solution_java": "class Encrypter {\n \n Map encryptedDictCount;\n int[] keys;\n Set dictionary;\n String[] val;\n \n public Encrypter(char[] keys, String[] values, String[] dictionary) {\n this.keys = new int[26];\n encryptedDictCount = new HashMap<>();\n this.val = values.clone();\n this.dictionary = new HashSet<>(Arrays.asList(dictionary));\n \n for(int i=0; i dict;\n unordered_map en;\n unordered_map> dy;\n \n Encrypter(vector& keys, vector& values, vector& dictionary) {\n for(auto& t:dictionary)\n { dict.insert(t);}\n for(int i=0;i int:\n def calc(m):#function calculate no of days for given weight\n c,s=0,0\n for i in weights:\n if i+s>m:\n c+=1\n s=0\n s+=i\n if s>0:\n c+=1\n return c\n left,right=max(weights),sum(weights)\n while left <=right:\n mid = (left+right)//2\n if calc(mid) > days:\n left = mid+1\n else :\n right = mid -1\n return left", "solution_js": "/**\n * @param {number[]} weights\n * @param {number} days\n * @return {number}\n */\nvar shipWithinDays = function(weights, days) {\n // set left as max of weight, set right as sum of weight\n let left = Math.max(...weights), right = weights.reduce((a, b) => a + b);\n\n // max weight cannot exceed the capacity of ship\n while (left < right) {\n // set middle weight\n const m = Math.floor((left + right) / 2);\n // reset weight if can be load\n can(m) ? (left = m + 1) : (right = m);\n }\n\n // result\n return left;\n\n // check if load can be\n function can(v) {\n let need = 1, current = 0;\n\n for (let i of weights) {\n if (current + i > v) {\n need++;\n current = i;\n }\n else {\n current += i;\n }\n }\n\n return need > days;\n }\n};", "solution_java": "class Solution {\n public int shipWithinDays(int[] weights, int days) {\n int left = 0;\n int right = 0;\n // left is the biggest element in the array. It's set as the lower boundary.\n // right is the sum of the array, which is the upper limit. \n for (int weight : weights) {\n left = Math.max(weight, left);\n right += weight;\n }\n int res = 0;\n while (left <= right) {\n int mid = (left + right) / 2;\n // make sure mid is a possible value \n if (isPossible(weights, days, mid)) {\n res = mid;\n right = mid - 1;\n } else {\n left = mid + 1;\n }\n }\n return res;\n }\n \n public boolean isPossible(int [] weights, int days, int mid) {\n int totalDays = 1;\n int totalWeight = 0;\n for (int i = 0; i < weights.length; i++) {\n totalWeight += weights[i];\n // increase totalDays if totalWeight is larger than mid\n if (totalWeight > mid) {\n totalDays++;\n totalWeight = weights[i]; \n } \n // the problem states all the packages have to ship within `days` days \n if (totalDays > days) {\n return false;\n }\n }\n return true;\n }\n \n}", "solution_c": "class Solution {\npublic:\n // function to check if it is possible to ship all the items within the given number of days using a given weight capacity\n bool isPossible(int cp, vector& weights, int days)\n {\n int d = 1;\n int cw = 0;\n // iterate through the weights and check if it is possible to ship all the items\n for (auto x : weights) {\n if (x + cw <= cp) {\n // if the current weight can be added to the current capacity, add it\n cw += x;\n } else {\n // if not, increment the number of days required for shipping and start a new shipment\n d++;\n cw = x;\n if (x > cp) {\n // if the current weight is greater than the current capacity, it is impossible to ship all the items\n return false;\n }\n }\n }\n // check if it is possible to ship all the items within the given number of days\n return d <= days;\n }\n \n // function to find the minimum weight capacity required to ship all the items within the given number of days\n int shipWithinDays(vector& weights, int days)\n {\n // initialize the search range for the weight capacity\n int s = 1;\n int e = 1E9;\n int ans = -1;\n \n // perform binary search on the weight capacity range\n while (s <= e) {\n // set the mid-point of the range as the current weight capacity\n int mid = (s + e) / 2;\n \n // check if it is possible to ship all the items within the given number of days using the current weight capacity\n bool ok = isPossible(mid, weights, days);\n \n // if it is possible to ship all the items within the given number of days using the current weight capacity,\n // set the current weight capacity as the new answer and reduce the upper bound of the weight capacity range\n if (ok) {\n ans = mid;\n e = mid - 1;\n } else {\n // if it is not possible to ship all the items within the given number of days using the current weight capacity,\n // increase the lower bound of the weight capacity range\n s = mid + 1;\n }\n }\n \n // return the minimum weight capacity required to ship all the items within the given number of days\n return ans;\n }\n};" }, { "title": "Reverse Nodes in k-Group", "algo_input": "Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.\n\nk is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.\n\nYou may not alter the values in the list's nodes, only nodes themselves may be changed.\n\n \nExample 1:\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [2,1,4,3,5]\n\n\nExample 2:\n\nInput: head = [1,2,3,4,5], k = 3\nOutput: [3,2,1,4,5]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the list is n.\n\t1 <= k <= n <= 5000\n\t0 <= Node.val <= 1000\n\n\n \nFollow-up: Can you solve the problem in O(1) extra memory space?\n", "solution_py": "# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n\n # Intialize the result and the current node to the head\n res = node = head\n\n # Initialize the index of the current node to 0\n i = 0\n\n # Initialize the head and tail of the reversed nodes group to None\n reversedHead, reversedTail = None, None\n\n # Initialize the tail of the previous group to None\n previousTail = None\n\n # Iterate through all nodes\n while node:\n\n # When we reach the first node in a group\n if i % k == 0:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have less than k nodes left\n if previousTail:\n previousTail.next = node\n\n # Initialize the head and tail of the reversed nodes group\n reversedHead = reversedTail = ListNode(node.val)\n\n # Continue to reverse subsequent nodes\n else:\n reversedHead = ListNode(node.val, reversedHead)\n\n # If we are able to reach the last node in a reversed nodes group\n if i % k == k - 1:\n\n # If there is a previous group, connect its tail to the current node\n # This is the case when we have k nodes and thus, we should reverse this group\n if previousTail:\n previousTail.next = reversedHead\n\n # Set the tail of the previous group to the tail of the reversed nodes group\n previousTail = reversedTail\n\n # Set the head of the first reversed nodes group as the result\n if i == k - 1:\n res = reversedHead\n\n # Continue to the next node\n i, node = i + 1, node.next\n\n return res", "solution_js": "var reverseKGroup = function(head, k) {\n const helper = (node) => {\n let ptr = node;\n \n let t = k;\n let prev = null;\n \n while(t && ptr) {\n prev = ptr;\n ptr = ptr.next;\n t -= 1;\n }\n \n if(t > 0) //if k is not zero then do not reverse, simply return;\n return node;\n \n let f = prev.next;\n prev.next = null;\n \n let [rev, end] = reverseList(node);\n \n end.next = helper(f);\n \n return rev;\n }\n \n return helper(head);\n};\n\nvar reverseList = function(head) {\n let prev = null;\n let current = head;\n let end = head;\n\n while(current) {\n let next = current.next;\n current.next = prev;\n prev = current;\n current = next;\n }\n\n return [prev, end];\n };", "solution_java": "class Solution {\n public ListNode reverseKGroup(ListNode head, int k) {\n int numOfNodes = count(head);\n ListNode ptr = null;\n List start = new ArrayList<>(), end = new ArrayList<>();\n ListNode f = null;\n while (head != null) {\n if (numOfNodes >= k) {\n start.add(head);\n int count = 0;\n while (count < k) {\n ListNode temp = head.next;\n head.next = ptr;\n ptr = head;\n head = temp;\n count++;\n }\n end.add(ptr);\n ptr = null;\n numOfNodes -= count;\n }\n else {\n f = head;\n break;\n }\n }\n int n = start.size();\n for (int i = 0; i < n - 1; i++) start.get(i).next = end.get(i + 1);\n start.get(n - 1).next = f;\n return end.get(0);\n }\n public int count(ListNode head) {\n ListNode temp = head;\n int count = 0;\n while (temp != null) {\n count++;\n temp = temp.next;\n }\n return count;\n }\n}", "solution_c": "class Solution {\n pair get_rev_list(ListNode* root){\n ListNode *tail = root;\n ListNode *curr = root , *temp , *prev = NULL;\n \n while(curr != NULL){\n temp = curr -> next;\n curr -> next = prev;\n \n prev = curr;\n curr = temp;\n }\n \n return make_pair(prev , tail);\n }\n \n public:\n ListNode* reverseKGroup(ListNode* head, int k) {\n if(k == 1)\n return head;\n \n vector> store;\n \n ListNode *temp = head , *temp_head = head;\n int len = 0;\n \n while(temp != NULL){\n len++;\n \n if(len == k){\n ListNode *next_head = temp -> next;\n temp -> next = NULL;\n \n store.push_back(get_rev_list(temp_head));\n temp = next_head;\n len = 0;\n temp_head = next_head;\n }\n else\n temp = temp -> next;\n }\n \n if(len == k)\n store.push_back(get_rev_list(temp_head));\n \n for(int i = 1; i < store.size(); i++)\n store[i - 1].second -> next = store[i].first;\n \n if(len != k)\n store[store.size() - 1].second -> next = temp_head;\n \n return store[0].first;\n }\n};" }, { "title": "Making A Large Island", "algo_input": "You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.\n\nReturn the size of the largest island in grid after applying this operation.\n\nAn island is a 4-directionally connected group of 1s.\n\n \nExample 1:\n\nInput: grid = [[1,0],[0,1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n\n\nExample 2:\n\nInput: grid = [[1,1],[1,0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n\nExample 3:\n\nInput: grid = [[1,1],[1,1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 4.\n\n\n \nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 <= n <= 500\n\tgrid[i][j] is either 0 or 1.\n", "solution_py": "class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n # parent array to keey track\n parent = list(range(m*n))\n # rank array used for union by rank and size calculation\n rank = [1 for _ in range(m*n)]\n \n # standard DSU find function\n def find(x):\n while x != parent[x]:\n parent[x] = parent[parent[x]]\n x = parent[x]\n return x\n \n # standard DSU union by rank function\n def union(x,y):\n parX, parY = find(x), find(y)\n if parX == parY: return\n if rank[parX] >= rank[parY]:\n rank[parX] += rank[parY]\n parent[parY] = parX\n else:\n rank[parY] += rank[parX]\n parent[parX] = parY\n \n # Step 1: join the land\n\n # for each island we perform union operation\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # important condition: if we have a water body, we set its rank to 0 (will be used in the next step)\n if not val: \n rank[i*m+j] = 0\n continue\n \n # performing union of land bodies\n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n if grid[x][y]: union(i*m+j, x*m+y)\n \n # Step 2: convert a water body (if present)\n \n # the minimum final ans will always be the size of the largest land present \n ans = max(rank)\n for i, row in enumerate(grid):\n for j, val in enumerate(row):\n \n # we dont need to do anything if we encounter a land\n if val: continue\n \n neighbours = set()\n res = 0\n \n # \n for x,y in [(i-1, j),(i+1, j),(i, j+1),(i, j-1)]:\n # outside of grid check\n if not (0 <= x < m and 0 <= y < n): continue\n \n # checking unique neighbours by adding the parent to the set\n # here we dont care if the neighbour is water as its rank is 0 so it contributes nothing\n idx = x*m+y\n neighbours.add(find(idx))\n \n # Once we have all unique neighbours, just add their ranks\n for idx in neighbours:\n res += rank[idx]\n \n # res + 1 because we convert the current cell (i,j) to land too\n ans = max(ans, res+1)\n \n return ans", "solution_js": "var largestIsland = function(grid) {\n const n = grid.length\n\t/**\n\t * Create the merge find (union find) structure --> https://www.youtube.com/watch?v=ibjEGG7ylHk\n\t * For this case, we will form the sets at once, already assigning the same representative to all members.\n\t * Thus, we can use this simplistic implementation without path compression and find(i) = mf[i]\n\t */\n const mf = []\n for (let i = 0; i < n*n; i++) {\n mf.push(i)\n }\n\t// Helper that converts coordinates to array position\n const toPos = (r, c) => r * n + c\n\t// Recursively set the merge find structure to represent the islands' map\n const merge = (r, c, repr) => {\n mf[toPos(r, c)] = repr // Merge coordinate\n\t\t/**\n\t\t * Visit neighbors. To visit a neighboring coordinate we first check for:\n\t\t * Boundaries (coordinates stay within matrix limits)\n\t\t * Neighbor is land (contains a 1)\n\t\t * We didn't visit it already (has different representative)\n\t\t */\n if (r > 0 && grid[r-1][c] === 1 && mf[toPos(r-1, c)] !== repr) { // Top\n merge(r-1, c, repr)\n }\n if (c < n-1 && grid[r][c+1] === 1 && mf[toPos(r, c+1)] !== repr) { // Right\n merge(r, c+1, repr)\n }\n if (r < n-1 && grid[r+1][c] === 1 && mf[toPos(r+1, c)] !== repr) { // Bottom\n merge(r+1, c, repr)\n }\n if (c > 0 && grid[r][c-1] === 1 && mf[toPos(r, c-1)] !== repr) { // Left\n merge(r, c-1, repr)\n }\n }\n\t/**\n\t * For each land (1) position that wasn't already merged into a set,\n\t * we define a new set with its neighbors.\n\t */\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n const pos = toPos(i, j)\n if (grid[i][j] === 1 && mf[pos] === pos) {\n merge(i, j, pos)\n } \n }\n }\n\t/**\n\t * We can now calculate the surface of every island by counting the number of cells\n\t * with the same representative.\n\t */\n const count = Array(n*n).fill(0)\n mf.forEach(el => count[el]++)\n /**\n\t * Now we have to decide on which sea (0) should be toggled into land (1).\n\t * For this we save, for each zero, which sets it is contact with. Once this is done,\n\t * we can calculate the entire surface by suming 1 + the surface of all touching sets.\n\t * Again, to add the neighbor set to the store, we need to check that it is a one, that we\n\t * are within the boundaries, and that it was not already marked as neighbor.\n\t * We store the maximum surface found, which is the final solution.\n\t */\n let maxSurface = 0\n for (let r = 0; r < n; r++) {\n for (let c = 0; c < n; c++) {\n if (grid[r][c] === 0) {\n const touching = []\n let currentSurface = 1\n if (r > 0 && grid[r-1][c] === 1 && !touching.includes(mf[toPos(r-1, c)])) { // Top\n touching.push(mf[toPos(r-1,c)])\n }\n if (c < n-1 && grid[r][c+1] === 1 && !touching.includes(mf[toPos(r, c+1)])) { // Right\n touching.push(mf[toPos(r,c+1)])\n }\n if (r < n-1 && grid[r+1][c] === 1 && !touching.includes(mf[toPos(r+1, c)])) { // Bottom\n touching.push(mf[toPos(r+1, c)])\n }\n if (c > 0 && grid[r][c-1] === 1 && !touching.includes(mf[toPos(r, c-1)])) { // Left\n touching.push(mf[toPos(r, c-1)])\n }\n touching.forEach(set => currentSurface += count[set])\n if (currentSurface > maxSurface) {\n maxSurface = currentSurface\n }\n } \n }\n }\n /**\n\t * If maxSurface remained at zero, it means the input is a matrix of ones.\n\t */\n if (maxSurface > 0) { return maxSurface }\n return n*n\n}", "solution_java": "class Solution {\n int dir[][] = new int[][]{\n {1, 0},\n {-1,0},\n {0,1},\n {0,-1}\n };\n private int countArea(int grid[][], int i, int j, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length)\n return 0;\n \n if(grid[i][j] != 1) return 0;\n \n grid[i][j] = num;\n int count = 0;\n for(int d[] : dir){\n count += countArea(grid, i + d[0], j + d[1], num);\n }\n \n return 1 + count;\n }\n \n private void fillDP(int grid[][], int dp[][], int i, int j, int count, int num){\n if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return ;\n \n if(grid[i][j] != num) return;\n \n if(dp[i][j] != 0) return ;\n dp[i][j] = count;\n for(int d[] : dir){\n fillDP(grid, dp, i + d[0], j + d[1], count, num);\n }\n \n }\n \n \n public int largestIsland(int[][] grid) {\n int n = grid.length, m = grid[0].length;\n int dp[][] = new int[n][m];\n \n int num = 1;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] == 1){\n ++num;\n int count1 = countArea(grid, i, j, num);\n fillDP(grid, dp, i, j, count1, num);\n }\n }\n }\n \n int max = 0;\n for(int i = 0; i < n; ++i){\n for(int j = 0; j < m; ++j){\n if(grid[i][j] != 0) continue;\n int val = 1;\n Set set = new HashSet<>();\n for(int d[] : dir){\n int newRow = i + d[0];\n int newCol = j + d[1];\n \n if(newRow < 0 || newRow >= n || newCol < 0 || newCol >= m) continue;\n if(set.contains(grid[newRow][newCol])) continue;\n \n val += dp[newRow][newCol];\n set.add(grid[newRow][newCol]);\n }\n max = Math.max(max, val);\n }\n }\n \n if(max == 0) return n * m;\n return max;\n \n }\n}", "solution_c": "class Solution {\n int dir[4][2]={{0,1},{1,0},{-1,0},{0,-1}};\n \n bool isValid(vector>const &grid,vector> &visited, int row, int col){\n int n=grid.size();\n \n if(row<0 || row>=n || col<0 || col>=n || grid[row][col]!=1 || visited[row][col]!=0){\n return false;\n }\n return true;\n }\n \n int helper(vector>const &grid,vector> &visited, int row, int col){\n \n if(!isValid(grid,visited,row,col)) return 0;\n \n visited[row][col]=1;\n \n \n \n return 1+helper(grid,visited, row+dir[0][0], col+dir[0][1])+\n helper(grid,visited, row+dir[1][0], col+dir[1][1])+\n helper(grid,visited, row+dir[2][0], col+dir[2][1])+\n helper(grid,visited, row+dir[3][0], col+dir[3][1]);\n \n return 0;\n }\npublic:\n int largestIsland(vector>& grid) {\n int ans=0;\n int n=grid.size();\n for(int i=0;i> visited(n,vector(n,0));\n ans=max(ans,helper(grid,visited, i,j));\n grid[i][j]=0;\n }\n \n }\n }\n return ans==0?n*n:ans;\n }\n};" }, { "title": "Verbal Arithmetic Puzzle", "algo_input": "Given an equation, represented by words on the left side and the result on the right side.\n\nYou need to check if the equation is solvable under the following rules:\n\n\n\tEach character is decoded as one digit (0 - 9).\n\tNo two characters can map to the same digit.\n\tEach words[i] and result are decoded as one number without leading zeros.\n\tSum of numbers on the left side (words) will equal to the number on the right side (result).\n\n\nReturn true if the equation is solvable, otherwise return false.\n\n \nExample 1:\n\nInput: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput: true\nExplanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\n\nExample 2:\n\nInput: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput: true\nExplanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\n\nExample 3:\n\nInput: words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput: false\nExplanation: There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.\n\n\n \nConstraints:\n\n\n\t2 <= words.length <= 5\n\t1 <= words[i].length, result.length <= 7\n\twords[i], result contain only uppercase English letters.\n\tThe number of different characters used in the expression is at most 10.\n\n", "solution_py": "class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n \n # reverse words\n words = [i[::-1] for i in words]\n result = result[::-1]\n allWords = words + [result]\n \n # chars that can not be 0\n nonZero = set()\n for word in allWords:\n if len(word) > 1:\n nonZero.add(word[-1])\n \n # numbers selected in backtracking\n selected = set()\n # char to Int map\n charToInt = dict()\n mxLen = max([len(i) for i in allWords])\n \n def res(i = 0, c = 0, sm = 0):\n if c == mxLen:\n return 1 if sm == 0 else 0\n elif i == len(words):\n num = sm % 10\n carry = sm // 10\n if c >= len(result):\n if num == 0:\n return res(0, c+1, carry)\n else:\n return 0\n # result[c] should be mapped to num if a mapping exists\n if result[c] in charToInt:\n if charToInt[result[c]] != num:\n return 0\n else:\n return res(0, c+1, carry)\n elif num in selected:\n return 0\n # if mapping does not exist, create a mapping\n elif (num == 0 and result[c] not in nonZero) or num > 0:\n selected.add(num)\n charToInt[result[c]] = num\n ret = res(0, c + 1, carry)\n del charToInt[result[c]]\n selected.remove(num)\n return ret\n else:\n return 0\n else:\n word = words[i]\n if c >= len(word):\n return res(i+1, c, sm)\n elif word[c] in charToInt:\n return res(i+1, c, sm + charToInt[word[c]])\n else:\n ret = 0\n # possibilities for word[c]\n for j in range(10):\n if (j == 0 and word[c] not in nonZero) or j > 0:\n if j not in selected:\n selected.add(j)\n charToInt[word[c]] = j\n ret += res(i + 1, c, sm + j)\n del charToInt[word[c]]\n selected.remove(j)\n return ret\n \n return res() > 0", "solution_js": "/**\n * @param {string[]} words\n * @param {string} result\n * @return {boolean}\n */\nvar isSolvable = function(words, result) {\n // set to hold all the first characters\n const firstChars = new Set();\n \n // map for steps 1 & 2\n // this will hold the key as the character and multiple as the value\n let map = {};\n for (let i = 0; i < result.length; i++) {\n const char = result[i];\n if (!i) firstChars.add(char);\n if (!map.hasOwnProperty(char)) map[char] = 0;\n map[char] -= 10 ** (result.length - i - 1);\n }\n for (let j = 0; j < words.length; j++) {\n const word = words[j];\n for (let i = 0; i < word.length; i++) {\n const char = word[i];\n if (!i) firstChars.add(char);\n if (!map.hasOwnProperty(char)) map[char] = 0;\n map[char] += 10 ** (word.length - i - 1);\n }\n }\n \n // Step 3: we group the positive and negative values\n const positives = [];\n const negatives = [];\n Object.entries(map).forEach((entry) => {\n if (entry[1] < 0) negatives.push(entry);\n else positives.push(entry);\n })\n\n // Step 4: backtrack\n const numsUsed = new Set();\n const backtrack = (val = 0) => {\n // if we have used all the characters and the value is 0 the input is solvable\n if (!positives.length && !negatives.length) return val === 0;\n\t\n\t// get the store that we are going to examine depending on the value\n let store = val > 0 || (val === 0 && negatives.length) ? negatives : positives;\n if (store.length === 0) return false;\n const entry = store.pop();\n const [char, multiple] = entry;\n\t\n\t// try every possible value watching out for the edge case that it was a first character\n for (let i = firstChars.has(char) ? 1 : 0; i < 10; i++) {\n if (numsUsed.has(i)) continue;\n numsUsed.add(i);\n if (backtrack(i * multiple + val)) return true;\n numsUsed.delete(i);\n }\n store.push(entry);\n return false;\n }\n return backtrack();\n};", "solution_java": "class Solution {\n public static boolean isSolvable(String[] words, String result) {\n\t // reverse all strings to facilitate add calculation.\n for (int i = 0; i < words.length; i++) {\n words[i] = new StringBuilder(words[i]).reverse().toString();\n }\n result = new StringBuilder(result).reverse().toString();\n if (!checkLength(words, result)) {\n return false;\n }\n boolean[] visited = new boolean[10]; // digit 0, 1, ..., 9\n int[] chToDigit = new int[26];\n Arrays.fill(chToDigit, -1);\n return dfs(0, 0, 0, visited, chToDigit, words, result);\n }\n\n /**\n * Elminate the case where result is too long\n * word1: AAA\n * word2: BBB\n * result: XXXXXXXXX\n */\n private static boolean checkLength(String[] words, String result) {\n int maxLen = 0;\n for (String word : words) {\n maxLen = Math.max(maxLen, word.length());\n }\n return result.length() == maxLen || result.length() == maxLen + 1;\n }\n\n /*\n Put all words like this:\n w1: ABC\n w2: EF\n w3: GHIJ\n result: KLMNO\n i, is the row\n j, is the column\n carrier, the one contributed from previous calculation\n chToDigit, 26 int array, which records choosen digit for 'A', 'B', 'C', ... If not choosen any, default is -1 \n */\n private static boolean dfs(int i, int j, int carrier, boolean[] visited, int[] chToDigit, String[] words, String result) {\n if (i == words.length) {\n char ch = result.charAt(j);\n // (i, i) at bottom right corner. final check\n if (j == result.length() - 1) {\n // 1. check if carrier is equal or greater than 10. If so, false.\n if (carrier >= 10) {\n return false;\n }\n // 2. check if result.length() > 1 && result.lastCh is zero. If so the false.\n if (j > 0 && j == result.length() - 1 && chToDigit[ch - 'A'] == 0) {\n return false;\n }\n // not selected, can select any. True.\n if (chToDigit[ch - 'A'] == -1) {\n System.out.println(Arrays.toString(chToDigit));\n return true;\n } else { // if selected, check if it matches with carrier. Also, carrier can't be 0. result = '00' is invalid\n return chToDigit[ch - 'A'] == carrier;\n }\n } else { // reached normal result line.\n // 1. if not selected. Use current carrier's unit digit\n if (chToDigit[ch - 'A'] == -1) {\n int selectedDigit = carrier % 10;\n // For example carrier = 13. selectedDigit = 3. ch = 'H'. Should set 3 to 'H'.\n // But 3 is already taken by 'B' previously. So wrong.\n if (visited[selectedDigit]) {\n return false;\n }\n visited[selectedDigit] = true;\n chToDigit[ch - 'A'] = selectedDigit;\n if (dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result)) {\n return true;\n }\n chToDigit[ch - 'A'] = -1;\n visited[selectedDigit] = false;\n } else { // 2. selected\n // just need to check if ch.digit equals to unit digit.\n if (chToDigit[ch - 'A'] != carrier % 10) {\n return false;\n }\n boolean ans = dfs(0, j + 1, carrier / 10, visited, chToDigit, words, result);\n return ans;\n }\n } //\n } else { // normal word\n String word = words[i];\n // 1. check if j is equal or greater than word.len. If so pass to next word.\n if (j >= word.length()) {\n boolean ans = dfs(i + 1, j, carrier, visited, chToDigit, words, result);\n return ans;\n }\n // 2. check if it's last ch, word.len is greater than 1, and is '0'. If so false;\n if (j == word.length() - 1 && word.length() > 1 && chToDigit[word.charAt(j) - 'A'] == 0) {\n return false;\n }\n char ch = word.charAt(j);\n // 3. check if word.ch is selected. Just add current digit and move to next word.\n if (chToDigit[ch - 'A'] != -1) {\n int newSum = carrier + chToDigit[ch - 'A'];\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n return ans;\n } else {\n for (int k = 0; k < visited.length; k++) {\n if (visited[k]) {\n continue;\n }\n visited[k] = true;\n chToDigit[ch - 'A'] = k;\n int newSum = k + carrier;\n boolean ans = dfs(i + 1, j, newSum, visited, chToDigit, words, result);\n if (ans) {\n return true;\n }\n visited[k] = false;\n chToDigit[ch - 'A'] = -1;\n }\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\n int limit = 0;\n unordered_map c2i;\n unordered_map i2c;\n bool helper(vector &words, string &result, int digit, int wid, int sum)\n {\n if(digit==limit)\n return sum == 0;\n if(wid==words.size())\n {\n if(c2i.count(result[digit])==0 && i2c.count(sum%10)==0)\n {\n if(sum%10==0 && digit+1 == limit)\n return false; //Means leading zeros\n c2i[result[digit]] = sum%10;\n i2c[sum%10] = result[digit];\n bool tmp = helper(words, result, digit+1, 0, sum/10); //0 because it will\n //go one digit at a time until all digits in words are finished\n c2i.erase(result[digit]);\n i2c.erase(sum%10);\n return tmp;\n }\n else if(c2i.count(result[digit]) && c2i[result[digit]] == sum%10) //c2i for that exits and is equal to sum%10, remember default will be 0 and sum%10 can also be 0\n {\n if(digit+1 == limit && c2i[result[digit]]==0)\n return false; //again same condition of leading zeros\n return helper(words, result, digit+1, 0, sum/10);\n }\n else //if result[digit] exists in c2i but is not equal to sum%10\n return false;\n }\n if(digit>=words[wid].length()) //digit>current words length\n return helper(words, result, digit, wid+1, sum); //go to next word at same position\n //(digit) and sum, also going wid + 1 that is why checking wid limit in last condition already\n if(c2i.count(words[wid][digit]))\n {\n if(digit+1 == words[wid].length() && words[wid].length() > 1 && c2i[words[wid][digit]]==0)\n return false; //here we checking if there is no leading 0 in the word itself\n return helper(words, result, digit, wid+1, sum+c2i[words[wid][digit]]);\n }\n for(int i=0; i<10; i++)\n {\n if(digit+1==words[wid].length() && i==0 && words[wid].length()>1)\n continue;\n if (i2c.count(i))\n continue;\n c2i[words[wid][digit]] = i;\n i2c[i] = words[wid][digit];\n bool tmp = helper(words, result, digit, wid+1, sum+i);\n c2i.erase(words[wid][digit]);\n i2c.erase(i);\n if(tmp)\n return true;\n }\n return false;\n }\n \npublic:\n bool isSolvable(vector& words, string result) {\n limit = result.length();\n for(auto s:words)\n {\n if(s.length()>limit)\n return false;\n }\n for(auto &s:words)\n {\n reverse(s.begin(), s.end());\n }\n reverse(result.begin(), result.end());\n return helper(words, result, 0, 0, 0);\n }\n};" }, { "title": "Maximum Depth of Binary Tree", "algo_input": "Given the root of a binary tree, return its maximum depth.\n\nA binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n\n \nExample 1:\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 3\n\n\nExample 2:\n\nInput: root = [1,null,2]\nOutput: 2\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 104].\n\t-100 <= Node.val <= 100\n\n", "solution_py": "class Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n result = 0\n depths = []\n self.handler(root, result, depths)\n return max(depths)\n\n def handler(self, root, result, depths):\n if root:\n result += 1\n self.handler(root.left, result, depths)\n self.handler(root.right, result, depths)\n else:\n depths.append(result)", "solution_js": "var maxDepth = function(root) {\n if(root == null) return 0\n \n let leftDepth = maxDepth(root.left)\n let rightDepth = maxDepth(root.right)\n \n let ans = Math.max(leftDepth,rightDepth) + 1\n \n return ans\n};", "solution_java": "class Solution {\n public int maxDepth(TreeNode root) {\n // Base Condition\n if(root == null) return 0;\n // Hypothesis\n int left = maxDepth(root.left);\n int right = maxDepth(root.right);\n // Induction\n return Math.max(left, right) + 1;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxDepth(TreeNode* root) {\n if(root == NULL) return 0;\n int left = maxDepth(root->left);\n int right = maxDepth(root->right);\n return max(left, right) + 1;\n }\n};" }, { "title": "Tuple with Same Product", "algo_input": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.\n\n \nExample 1:\n\nInput: nums = [2,3,4,6]\nOutput: 8\nExplanation: There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n\n\nExample 2:\n\nInput: nums = [1,2,4,5,10]\nOutput: 16\nExplanation: There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t1 <= nums[i] <= 104\n\tAll elements in nums are distinct.\n\n", "solution_py": "class Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n\n from itertools import combinations\n mydict=defaultdict(int)\n ans=0\n\n for a,b in combinations(nums,2):\n mydict[a*b]+=1\n\n for i,j in mydict.items():\n if j>1:\n ans+=(j*(j-1)//2)*8\n\n return ans", "solution_js": "var tupleSameProduct = function(nums) {\n let tupleCount = 0;\n let products = {}; // we'll keep track of how many times we've seen a given product before\n for (let a = 0; a < nums.length; a++) {\n for (let b = a + 1; b < nums.length; b++) {\n let product = nums[a] * nums[b];\n if (products[product]) { // we've seen at least one other pair of numbers with the same product already\n tupleCount += 8 * products[product]; // multiply by 8 because for any 4 numbers there are 8 permutations\n products[product] += 1; // increment the count, if we see this product again there are even more possible tuple combinations\n } else {\n products[product] = 1; // mark as seen once\n }\n }\n }\n return tupleCount;\n};", "solution_java": "class Solution {\n public int tupleSameProduct(int[] nums) {\n \n if(nums.length < 4){\n return 0;\n }\n \n int res = 0;\n \n HashMap map = new HashMap<>();\n \n for(int i = 0; i < nums.length - 1; i++){\n \n for(int j = i + 1; j < nums.length; j++){\n \n int val = nums[i] * nums[j];\n map.put(val, map.getOrDefault(val, 0) + 1);\n }\n }\n \n for(int key : map.keySet()){\n \n int val = map.get(key);\n \n if(val > 1){\n res += val * (val - 1) * 4; // (val * (val - 1) / 2) * 8\n }\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int tupleSameProduct(vector& nums) {\n int n = nums.size();\n unordered_map map;\n int res = 0;\n for(int i = 0 ; i < n ; i++){\n for(int j = i+1 ; j < n ; j++){\n int prod = nums[i] * nums[j];\n map[prod]++;//store product of each possible pair\n }\n }\n for(pair m:map){\n int n=m.second;\n res += (n*(n-1))/2; //no. of tuple\n }\n return res*8; //Every tuple has 8 permutations\n }\n};" }, { "title": "Maximum Number of Eaten Apples", "algo_input": "There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.\n\nYou decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.\n\nGiven two integer arrays days and apples of length n, return the maximum number of apples you can eat.\n\n \nExample 1:\n\nInput: apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput: 7\nExplanation: You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.\n\n\nExample 2:\n\nInput: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput: 5\nExplanation: You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.\n\n\n \nConstraints:\n\n\n\tn == apples.length == days.length\n\t1 <= n <= 2 * 104\n\t0 <= apples[i], days[i] <= 2 * 104\n\tdays[i] = 0 if and only if apples[i] = 0.\n\n", "solution_py": "import heapq\nclass Solution(object):\n def eatenApples(self, apples, days):\n \"\"\"\n :type apples: List[int]\n :type days: List[int]\n :rtype: int\n \"\"\"\n heap = [(days[0], apples[0])]\n heapq.heapify(heap)\n day = 0\n rtn = 0\n while heap or day < len(days):\n # print(heap, day)\n apple = 0\n if heap :\n cnt, apple = heapq.heappop(heap)\n while heap and cnt <= day and apple > 0:\n cnt, apple = heapq.heappop(heap)\n if apple > 0 and cnt > day :\n rtn +=1\n day +=1\n if apple > 1 and cnt > day:\n heapq.heappush(heap, (cnt, apple-1))\n if day < len(days) and apples[day] > 0 :\n heapq.heappush(heap, (day +days[day], apples[day]))\n return rtn ", "solution_js": "var eatenApples = function(apples, days) {\n const heap = new MinPriorityQueue({priority: x => x[0]});\n let totalApple = 0;\n \n for(let i = 0; i < apples.length; i++) {\n heap.enqueue([i + days[i], apples[i]]);\n \n while(!heap.isEmpty()) {\n const [expire, count] = heap.front().element;\n if(!count || expire <= i) heap.dequeue();\n else break;\n }\n \n if(heap.isEmpty()) continue;\n totalApple++;\n heap.front().element[1]--;\n }\n \n let i = apples.length;\n \n while(!heap.isEmpty()) {\n const [expire, count] = heap.dequeue().element;\n if(!count || expire <= i) continue;\n totalApple += Math.min(count, expire - i);\n i = Math.min(expire, i + count);\n }\n return totalApple;\n};", "solution_java": "class Solution {\n public int eatenApples(int[] apples, int[] days) {\n PriorityQueue minHeap = new PriorityQueue((a, b) -> (a.validDay - b.validDay));\n \n //start from day 1\n int currentDay = 1;\n int eatenAppleCount = 0;\n \n for(int i = 0; i < apples.length; i++){\n \n //add apple count and their valid day\n if(apples[i] > 0 && days[i] > 0) {\n \n //current day is included\n int validDay = currentDay + days[i] - 1;\n \n minHeap.add(new Apple(apples[i], validDay));\n }\n\n \n //check for eatable apple\n while(!minHeap.isEmpty()){\n //get that applen, with minimum valid date (going to expiry soon)\n Apple apple = minHeap.remove();\n \n if(apple.validDay >= currentDay){\n //eat 1 apple\n apple.count--;\n \n //increment count\n eatenAppleCount++;\n\n //add remaiing apple, if not gonna expiry current day\n if(apple.count > 0 && apple.validDay > currentDay){\n minHeap.add(apple);\n }\n \n break;\n }\n }\n \n //move to the next day\n currentDay++;\n }\n \n \n //eat stored apple\n while(!minHeap.isEmpty()){\n Apple apple = minHeap.remove();\n\n if(apple.validDay >= currentDay){\n //eat 1 apple\n apple.count--;\n \n //increment count\n eatenAppleCount++;\n \n //add remaiing apple, if not gonna expiry current day\n if(apple.count > 0 && apple.validDay > currentDay){\n minHeap.add(apple);\n }\n \n //apple is eaten in current day, now move to next day\n currentDay++;\n }\n }\n \n \n return eatenAppleCount;\n }\n}\n\n\nclass Apple {\n int count;\n int validDay;\n \n public Apple(int count, int validDay){\n this.count = count;\n this.validDay = validDay;\n }\n}", "solution_c": "class Solution {\npublic:\n int eatenApples(vector& apples, vector& days) {\n ios_base::sync_with_stdio(0);cin.tie(0);\n priority_queue,greater>p;\n unordered_mapm;\n int ans=0;\n int i=0;\n while(p.size() || ii)\n break;\n p.pop();\n }\n if(p.size()){\n ans++;\n m[p.top()]--;\n }\n ++i;\n }\n return ans;\n }\n};" }, { "title": "Minimum Consecutive Cards to Pick Up", "algo_input": "You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.\n\nReturn the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.\n\n \nExample 1:\n\nInput: cards = [3,4,2,3,4,7]\nOutput: 4\nExplanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.\n\n\nExample 2:\n\nInput: cards = [1,0,5,3]\nOutput: -1\nExplanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.\n\n\n \nConstraints:\n\n\n\t1 <= cards.length <= 105\n\t0 <= cards[i] <= 106\n\n", "solution_py": "class Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n d={}\n x=[]\n for i in range(len(cards)):\n if cards[i] not in d:\n d[cards[i]]=i\n else:\n x.append(i-d[cards[i]])\n d[cards[i]]=i\n if len(x)<=0:\n return -1\n return min(x)+1", "solution_js": "var minimumCardPickup = function(cards) {\n let cardsSeen = {};\n let minPicks = Infinity;\n for (let i = 0; i < cards.length; i++) {\n if (!(cards[i] in cardsSeen)) {\n cardsSeen[cards[i]] = i;\n } else {\n const temp = i - cardsSeen[cards[i]] + 1;\n minPicks = Math.min(minPicks, temp);\n cardsSeen[cards[i]] = i;\n }\n }\n return minPicks === Infinity ? -1 : minPicks;\n};", "solution_java": "class Solution\n{\n public int minimumCardPickup(int[] cards)\n {\n Map map = new HashMap<>();\n int min = Integer.MAX_VALUE;\n for(int i = 0; i < cards.length; i++)\n {\n if(map.containsKey(cards[i]))\n min = Math.min(i-map.get(cards[i])+1,min); // Check if the difference in indices is smaller than minimum\n map.put(cards[i],i); // Update the last found index of the card\n }\n return min == Integer.MAX_VALUE?-1:min; // Repetition found or not\n }\n}", "solution_c": "class Solution {\npublic:\n int minimumCardPickup(vector& cards) {\n\n int res (INT_MAX), n(size(cards));\n unordered_map m;\n for (auto i=0; i 1:\n arr = []\n for i in range(len(nums)-1):\n arr.append((nums[i] + nums[i+1]) % 10)\n nums = arr\n return nums[0]", "solution_js": "var triangularSum = function(nums) {\n while(nums.length > 1){\n let arr = []\n for(let i=0; i& nums) {\n int n=nums.size();\n for(int i=n-1;i>=1;i--){\n for(int j=0;j int:\n self.ans = 0\n self.dfs(root, [])\n return self.ans", "solution_js": "var pseudoPalindromicPaths = function(root) {\n if(!root) return 0;\n // if even it's zero or it's power of two when odd\n const ways = (r = root, d = 0) => {\n if(!r) return 0;\n d = d ^ (1 << r.val);\n // leaf\n if(r.left == r.right && r.left == null) {\n const hasAllEven = d == 0;\n const hasOneOdd = (d ^ (d & -d)) == 0;\n return Number(hasEven || hasOneOdd);\n }\n return ways(r.left, d) + ways(r.right, d);\n }\n return ways();\n};", "solution_java": "class Solution {\n public int pseudoPalindromicPaths (TreeNode root) {\n return helper(root, 0);\n }\n \n public int helper(TreeNode node, int freq) {\n if (node == null) return 0;\n \n freq = freq ^ (1 << node.val);\n if (node.left == null && node.right == null) {\n return (freq & (freq - 1)) == 0 ? 1 : 0;\n // return Integer.bitCount(freq) <= 1 ? 1 : 0;\n }\n return helper(node.left, freq) + helper(node.right, freq);\n }\n}", "solution_c": "class Solution {\nprivate:\n\tvoid dfs(TreeNode* root,int &ans,unordered_map &m){\n\n\t\tif(!root) return;\n\t\tm[root -> val]++;\n\n\t\tif(!root -> left and !root -> right){\n\t\t\tint oddCnt = 0;\n\t\t\tfor(auto it : m){\n\t\t\t\tif(it.second % 2 != 0) oddCnt++;\n\t\t\t}\n\t\t\tif(oddCnt <= 1) ans++;\n\t\t}\n\n\n\t\tdfs(root -> left,ans,m);\n\t\tdfs(root -> right,ans,m);\n\n\t\tm[root -> val]--;\n\n\t}\npublic:\n\tint pseudoPalindromicPaths (TreeNode* root) {\n\n\t\tif(root == NULL) return 0;\n\n\t\tint ans = 0;\n\n\t\tunordered_map m;\n\n\t\tdfs(root,ans,m);\n\n\t\treturn ans;\n\n\t}\n};" }, { "title": "Maximal Square", "algo_input": "Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n\n \nExample 1:\n\nInput: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput: 4\n\n\nExample 2:\n\nInput: matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput: 1\n\n\nExample 3:\n\nInput: matrix = [[\"0\"]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 <= m, n <= 300\n\tmatrix[i][j] is '0' or '1'.\n\n", "solution_py": "class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n m, n = len(matrix), len(matrix[-1]) \n dp = [[0] * n for _ in range(m)] \n max_area = 0\n for i in range(m):\n for j in range(n): \n if i - 1 < 0 or j - 1 < 0:\n if matrix[i][j] == '1': dp[i][j] = 1\n else:\n if matrix[i][j] == '1':\n dp[i][j] = 1 + min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j])\n max_area = max(max_area, dp[i][j] ** 2)\n return max_area", "solution_js": "var maximalSquare = function(matrix) {\n let max = 0;\n const height = matrix.length-1;\n const width = matrix[0].length-1;\n for (let i=height; i>=0; i--) {\n for (let j=width; j>=0; j--) {\n const right = j < width ? Number(matrix[i][j+1]) : 0;\n const diag = i < height && j < width ? Number(matrix[i+1][j+1]) : 0\n const bottom = i < height ? Number(matrix[i+1][j]) : 0;\n matrix[i][j] = matrix[i][j] === '0' ? 0 : \n Math.min(right, diag, bottom) + 1;\n max = Math.max(max, matrix[i][j] * matrix[i][j]);\n } \n }\n return max;\n};", "solution_java": "class Solution {\n public int maximalSquare(char[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] dp = new int[m][n];\n\n int max = 0;\n\n for (int i = 0; i < m; i++) {\n dp[i][0] = matrix[i][0] - 48;\n if (matrix[i][0] == '1') max = 1;\n }\n for (int i = 0; i < n; i++) {\n dp[0][i] = matrix[0][i] - 48;\n if (matrix[0][i] == '1') max = 1;\n }\n\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][j] == '1') {\n dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;\n if (dp[i][j] > max) {\n max = dp[i][j];\n }\n }\n }\n }\n\n return max * max;\n }\n}", "solution_c": "class Solution {\npublic:\n \n int dp[305][305];\n int ans;\n \n int getMax(vector>& mat, int i, int j){\n int n=mat.size(), m=mat[0].size();\n if(i>=n || j>=m) return 0;\n if(dp[i][j] != -1) return dp[i][j];\n \n\t\t// getting min of the perfect squares formed by left adjacent, right adjacent, cross adjacent \n\t\t// +1 for including current\n dp[i][j] = min({getMax(mat, i, j+1), getMax(mat, i+1, j), getMax(mat, i+1, j+1)}) + 1;\n\t\t// There are no perfect squares if mat[i][j] is zero\n if(mat[i][j] == '0') dp[i][j] = 0;\n\t\t\n\t\t// final ans = max(ans, current_max);\n ans = max(ans, dp[i][j]);\n\t\t\n return dp[i][j];\n }\n \n int maximalSquare(vector>& matrix) {\n memset(dp, -1, sizeof(dp));\n ans = 0;\n getMax(matrix, 0, 0);\n return ans*ans;\n }\n};" }, { "title": "Number of Valid Words in a Sentence", "algo_input": "A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.\n\nA token is a valid word if all three of the following are true:\n\n\n\tIt only contains lowercase letters, hyphens, and/or punctuation (no digits).\n\tThere is at most one hyphen '-'. If present, it must be surrounded by lowercase characters (\"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).\n\tThere is at most one punctuation mark. If present, it must be at the end of the token (\"ab,\", \"cd!\", and \".\" are valid, but \"a!b\" and \"c.,\" are not valid).\n\n\nExamples of valid words include \"a-b.\", \"afad\", \"ba-c\", \"a!\", and \"!\".\n\nGiven a string sentence, return the number of valid words in sentence.\n\n \nExample 1:\n\nInput: sentence = \"cat and dog\"\nOutput: 3\nExplanation: The valid words in the sentence are \"cat\", \"and\", and \"dog\".\n\n\nExample 2:\n\nInput: sentence = \"!this 1-s b8d!\"\nOutput: 0\nExplanation: There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.\n\n\nExample 3:\n\nInput: sentence = \"alice and bob are playing stone-game10\"\nOutput: 5\nExplanation: The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.\n\n\n \nConstraints:\n\n\n\t1 <= sentence.length <= 1000\n\tsentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.\n\tThere will be at least 1 token.\n\n", "solution_py": "import re\nclass Solution:\n def countValidWords(self, sentence: str) -> int:\n \n # parse and get each word from sentence\n words = sentence.split()\n \n # regular expression pattern for valid words\n pattern = re.compile( r'^([a-z]+\\-?[a-z]+[!\\.,]?)$|^([a-z]*[!\\.,]?)$' )\n \n # valid word count\n count = 0\n \n # scan each word from word pool\n for word in words:\n \n # judge whether current word is valid or not\n match = re.match(pattern, word)\n \n if match:\n count+=1\n \n return count", "solution_js": "/**\n * @param {string} sentence\n * @return {number}\n */\nvar countValidWords = function(sentence) {\n let list = sentence.split(' ')\n let filtered = list.filter(s => {\n if (/\\d/.test(s) || s === '') return false //removes anything with numbers or is blank\n if (/^[!,.]$/.test(s)) return true //punctuation only\n if (/^\\w+[!,.]?$/.test(s)) return true //word + optional punctuation\n if (/^\\w+[-]?\\w+[!,.]?$/.test(s)) return true //word + optional hypen + word + optional punctuation\n return false\n })\n \n return filtered.length\n};", "solution_java": "class Solution {\n public int countValidWords(String sentence) {\n String regex = \"^([a-z]+(-?[a-z]+)?)?(!|\\\\.|,)?$\";\n String r2 = \"[^0-9]+\";\n String[] arr = sentence.split(\"\\\\s+\");\n int ans = 0;\n for(String s: arr)\n {\n if(s.matches(regex) && s.matches(r2))\n {\n ans++;\n //System.out.println(s);\n }\n }\n return ans;\n }\n}", "solution_c": "#include \n\nclass Solution {\npublic:\n int countValidWords(string sentence) {\n\n int count = 0;\n\n // Defining the regex pattern\n regex valid_word(\"[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?\");\n\n // splitting the sentence to words\n stringstream s(sentence);\n string word;\n while(getline(s, word, ' ')) {\n\n // Checking if the word matches the regex pattern\n if(word != \"\" && regex_match(word, valid_word)){\n ++count;\n }\n }\n\n return count;\n }\n};" }, { "title": "Contains Duplicate II", "algo_input": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.\n\n \nExample 1:\n\nInput: nums = [1,2,3,1], k = 3\nOutput: true\n\n\nExample 2:\n\nInput: nums = [1,0,1,1], k = 1\nOutput: true\n\n\nExample 3:\n\nInput: nums = [1,2,3,1,2,3], k = 2\nOutput: false\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-109 <= nums[i] <= 109\n\t0 <= k <= 105\n\n", "solution_py": "class Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n seen = {}\n for i, n in enumerate(nums):\n if n in seen and i - seen[n] <= k:\n return True\n seen[n] = i\n return False", "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nvar containsNearbyDuplicate = function(nums, k) {\n const duplicateCheck = {};\n let isValid = false;\n for(var indexI=0; indexI -1) {\n if(Math.abs(duplicateCheck[nums[indexI]] - indexI) <= k) {\n isValid = true;\n break;\n }\n\n }\n duplicateCheck[nums[indexI]] = indexI;\n }\n return isValid;\n};", "solution_java": "class Solution {\n public boolean containsNearbyDuplicate(int[] nums, int k) {\n HashMap map = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n if (map.containsKey(nums[i]) && (Math.abs(map.get(nums[i]) - i) <= k) ) {\n return true;\n }\n map.put(nums[i], i);\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool containsNearbyDuplicate(vector& nums, int k) {\n unordered_map m;\n for(int i=0;i int:\n return sum(nums)-min(nums)*len(nums)", "solution_js": "var minMoves = function(nums) {\n let minElm = Math.min(...nums);\n let ans = 0;\n for(let i=0; i& nums) {\n\n // sorting the array to get min at the first\n sort(nums.begin(), nums.end());\n int cnt = 0, n = nums.size();\n\n // Now we have to make min equal to every number and keep adding the count\n for(int i = 1; i < n; i++)\n cnt += nums[i] - nums[0];\n\n return cnt;\n }\n};" }, { "title": "Strong Password Checker II", "algo_input": "A password is said to be strong if it satisfies all the following criteria:\n\n\n\tIt has at least 8 characters.\n\tIt contains at least one lowercase letter.\n\tIt contains at least one uppercase letter.\n\tIt contains at least one digit.\n\tIt contains at least one special character. The special characters are the characters in the following string: \"!@#$%^&*()-+\".\n\tIt does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not).\n\n\nGiven a string password, return true if it is a strong password. Otherwise, return false.\n\n \nExample 1:\n\nInput: password = \"IloveLe3tcode!\"\nOutput: true\nExplanation: The password meets all the requirements. Therefore, we return true.\n\n\nExample 2:\n\nInput: password = \"Me+You--IsMyDream\"\nOutput: false\nExplanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.\n\n\nExample 3:\n\nInput: password = \"1aB!\"\nOutput: false\nExplanation: The password does not meet the length requirement. Therefore, we return false.\n\n \nConstraints:\n\n\n\t1 <= password.length <= 100\n\tpassword consists of letters, digits, and special characters: \"!@#$%^&*()-+\".\n\n", "solution_py": "class Solution:\n def strongPasswordCheckerII(self, pwd: str) -> bool:\n return (\n len(pwd) > 7\n and max(len(list(p[1])) for p in groupby(pwd)) == 1\n and reduce(\n lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0\n ) == 15\n )", "solution_js": "const checkLen = (password) => password.length >= 8;\n\nconst checkSmallLetter = (password) => {\n for(let i=0;i 96 && ind < 123){\n return true;\n }\n }\n return false;\n}\n\nconst checkCapitalLetter = (password) => {\n for(let i=0;i 64 && ind < 91){\n return true;\n }\n }\n return false;\n}\n\nconst checkDigit = (password) => {\n for(let i=0;i 47 && ind < 58){\n return true;\n }\n }\n return false;\n}\n\nconst checkSpecialChar = (password) => {\n const str = \"!@#$%^&*()-+\";\n for(let i=0;i {\n for(let i=1;i intAscii = new HashSet<>();\n String specialCharacters = \"!@#$%^&*()-+\";\n for (int i = 0; i < specialCharacters.length(); i++) {\n int ascii = specialCharacters.charAt(i);\n intAscii.add(ascii);\n }\n \n if(password.length() < 8){\n return false;\n }\n boolean small = false;\n boolean large = false;\n boolean numbers = false;\n boolean specialChars = false;\n for(int i = 0 ; i < password.length() ; i++){\n int ascii = (int)(password.charAt(i));\n if(ascii <= 90 && ascii>=65){\n large = true;\n }\n if(ascii <= 122 && ascii>=97){\n small = true;\n }\n if(ascii <=57 && ascii >=48){\n numbers = true;\n }\n if(intAscii.contains(ascii)){\n specialChars = true;\n }\n if(i> 0 && password.charAt(i)== password.charAt(i-1)){\n return false;\n }\n }\n if(large == false || small == false || numbers == false || specialChars ==false){\n return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool strongPasswordCheckerII(string password) {\n\t\tif(password.size() < 8) //8 char length\n return false;\n\t\t\t\n bool lower = 0, upper = 0;\n bool digit = 0, special = 0;\n\t\t\n for(int i=0; i0 && password[i] == password[i-1]) //check duplicate\n\t\t\t\treturn false; \n \n\t\t\tif(password[i] >=65 && password[i] <=90) upper = 1; //uppercase\n\t\t\telse if(password[i] >=97 && password[i] <=122) lower = 1; //lowercase\n\t\t\telse if(password[i] >=48 && password[i] <=57) digit = 1; //digit\n\t\t\telse //special char\n special = 1;\n }\n \n if(upper && lower && digit && special)\n return true;\n return false;\n }\n};" }, { "title": "Largest Component Size by Common Factor", "algo_input": "You are given an integer array of unique positive integers nums. Consider the following graph:\n\n\n\tThere are nums.length nodes, labeled nums[0] to nums[nums.length - 1],\n\tThere is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\n\nReturn the size of the largest connected component in the graph.\n\n \nExample 1:\n\nInput: nums = [4,6,15,35]\nOutput: 4\n\n\nExample 2:\n\nInput: nums = [20,50,9,63]\nOutput: 2\n\n\nExample 3:\n\nInput: nums = [2,3,6,7,4,12,21,39]\nOutput: 8\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t1 <= nums[i] <= 105\n\tAll the values of nums are unique.\n\n", "solution_py": "class Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \n def find(node):\n if parent[node] == -1: return node\n else:\n parent[node] = find(parent[node])\n return parent[node]\n \n def union(idx1,idx2):\n par1,par2 = find(idx1),find(idx2)\n if par1!=par2:\n if rank[par1] > rank[par2]:\n parent[par2] = par1\n elif rank[par2] > rank[par1]:\n parent[par1] = par2\n else:\n parent[par2] = par1\n rank[par1] += 1\n \n n = len(nums)\n parent = defaultdict(lambda:-1)\n rank = defaultdict(lambda:0)\n for i in range(n):\n limit = int(nums[i]**0.5)\n for j in range(2,limit+1):\n if nums[i] % j == 0:\n union(nums[i],j)\n union(nums[i],nums[i]//j)\n count = defaultdict(lambda:0)\n best = -1\n for num in nums:\n par = find(num)\n tmp = count[par] + 1\n if tmp > best: best = tmp\n count[par] = tmp\n return best", "solution_js": "var largestComponentSize = function(nums) {\n const rootByFactor = new Map();\n const parents = new Array(nums.length);\n\n function addFactor(i, factor) {\n if (rootByFactor.has(factor)) {\n let r = rootByFactor.get(factor);\n while (parents[i] != i) i = parents[i];\n while (parents[r] != r) r = parents[r];\n parents[i] = r;\n }\n rootByFactor.set(factor, parents[i]);\n }\n\n for (const [i, num] of nums.entries()) {\n parents[i] = i;\n addFactor(i, num);\n for (let factor = 2; factor * factor <= num; ++factor) {\n if (num % factor == 0) {\n addFactor(i, factor);\n addFactor(i, num / factor);\n }\n }\n }\n\n let largest = 0;\n const sums = new Array(nums.length).fill(0);\n for (let r of parents) {\n while (parents[r] != r) r = parents[r];\n largest = Math.max(largest, ++sums[r]);\n }\n return largest;\n};", "solution_java": "class Solution {\n public int largestComponentSize(int[] nums) {\n int maxNum = getMaxNum(nums);\n Map numToFirstPrimeFactor = new HashMap<>();\n DisjointSet ds = new DisjointSet(maxNum + 1);\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n List primeFactors = getPrimeFactors(num);\n int firstPrimeFactor = primeFactors.get(0);\n numToFirstPrimeFactor.put(num, firstPrimeFactor);\n\n for (int i = 1; i < primeFactors.size(); i++) {\n ds.union(primeFactors.get(i-1), primeFactors.get(i));\n }\n }\n\n Map componentToSize = new HashMap<>();\n int maxSize = 0;\n for (int num : nums) {\n if (num == 1) {\n continue;\n }\n\n int firstPrimeFactor = numToFirstPrimeFactor.get(num);\n int component = ds.find(firstPrimeFactor);\n int size = componentToSize.getOrDefault(component, 0);\n componentToSize.put(component, ++size);\n maxSize = Math.max(maxSize, size);\n }\n return maxSize;\n }\n\n public int getMaxNum(int[] nums) {\n int maxNum = 0;\n for (int num : nums) {\n maxNum = Math.max(maxNum, num);\n }\n return maxNum;\n }\n\n public List getPrimeFactors(int num) {\n List primeFactors = new ArrayList<>();\n\n // even prime factor i.e. 2\n if((num & 1) == 0){\n primeFactors.add(2);\n\n do{\n num >>= 1;\n }while((num & 1) == 0);\n }\n\n // odd prime factors\n int primeFactor = 3;\n while(num != 1 && primeFactor*primeFactor <= num){\n if(num % primeFactor == 0){\n primeFactors.add(primeFactor);\n\n do{\n num /= primeFactor;\n }while(num % primeFactor == 0);\n }\n primeFactor += 2;\n }\n\n // num is prime\n if(num != 1){\n primeFactors.add(num);\n }\n return primeFactors;\n }\n}\n\nclass DisjointSet {\n int[] root;\n int[] rank;\n\n public DisjointSet(int size) {\n root = new int[size];\n rank = new int[size];\n for (int i = 0; i < size; i++) {\n root[i] = i;\n rank[i] = 1;\n }\n }\n\n public int find(int x) {\n while (x != root[x]) {\n root[x] = root[root[x]];\n x = root[x];\n }\n return x;\n }\n\n public void union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n\n if (rootX == rootY) {\n return;\n }\n\n if (rank[rootX] > rank[rootY]) {\n root[rootY] = rootX;\n } else if (rank[rootX] < rank[rootY]) {\n root[rootX] = rootY;\n } else {\n root[rootY] = rootX;\n rank[rootX]++;\n }\n }\n}", "solution_c": "class Solution {\nprivate:\n vector sieve(int n) {\n vector prime(n + 1);\n for (int i = 0; i <= n; i++)\n prime[i] = 1;\n for (int p = 2; p * p <= n; p++) {\n if (prime[p] == 1) {\n for (int i = p * p; i <= n; i += p)\n prime[i] = 0;\n }\n }\n prime[1] = prime[0] = 0;\n return prime;\n }\n vector factors(int n, vector &primelist) {\n vector facs;\n for (int i = 0; primelist[i] * primelist[i] <= n && i < primelist.size(); i++) {\n if (n % primelist[i] == 0) {\n facs.push_back(primelist[i]);\n while (n % primelist[i] == 0) {\n n /= primelist[i];\n }\n }\n }\n if (n > 1) facs.push_back(n);\n return facs;\n }\n void dfs(vector> &gr, int node, vector &vis, int &compSize) {\n if(vis[node]) return;\n vis[node] = 1;\n compSize++;\n for(auto x : gr[node]) {\n dfs(gr, x, vis, compSize);\n }\n }\npublic:\n int largestComponentSize(vector& nums) {\n int n = nums.size();\n vector> gr(n);\n vector prime = sieve(1e5 + 6);\n vector primelist;\n\t\t// Getting all the primes till 10^5 as maximum value of nums[i] is 10^5\n for (int i = 2; i <= 1e5 + 5; i++) if (prime[i]) primelist.push_back(i);\n unordered_map m; // to store the index of the node with prime factor x\n for(int i = 0; i < n; i++) {\n vector facs = factors(nums[i], primelist);\n for(auto j : facs) {\n if(m.find(j) == m.end()) { // prime factor had not occured before\n m[j] = i; // j is the prime factor and its index is i\n } else {\n\t\t\t\t // prime factor has already been seen before in a previous number and nums[i] is connected to that number\n gr[i].push_back(m[j]);\n gr[m[j]].push_back(i);\n }\n }\n }\n int ans = 0;\n vector vis(n);\n for(int i = 0; i < n; i++) { // running a simple dfs to calculate the maximum component size\n if(!vis[i]) {\n int compSize = 0;\n dfs(gr, i, vis, compSize);\n ans = max(ans, compSize);\n }\n }\n return ans;\n }\n};" }, { "title": "Kth Distinct String in an Array", "algo_input": "A distinct string is a string that is present only once in an array.\n\nGiven an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string \"\".\n\nNote that the strings are considered in the order in which they appear in the array.\n\n \nExample 1:\n\nInput: arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\nOutput: \"a\"\nExplanation:\nThe only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1st distinct string.\n\"a\" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, \"a\" is returned. \n\n\nExample 2:\n\nInput: arr = [\"aaa\",\"aa\",\"a\"], k = 1\nOutput: \"aaa\"\nExplanation:\nAll strings in arr are distinct, so the 1st string \"aaa\" is returned.\n\n\nExample 3:\n\nInput: arr = [\"a\",\"b\",\"a\"], k = 3\nOutput: \"\"\nExplanation:\nThe only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".\n\n\n \nConstraints:\n\n\n\t1 <= k <= arr.length <= 1000\n\t1 <= arr[i].length <= 5\n\tarr[i] consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n hash_map = {}\n for string in arr:\n hash_map[string] = hash_map.get(string, 0) + 1\n for string in arr:\n if hash_map[string] == 1:\n k -= 1\n if k == 0:\n return string\n return \"\"", "solution_js": "var kthDistinct = function(arr, k) {\n const map = {} // used for arr occurences\n const distinctArr = [] // store the distinct values (only appearing once)\n \n\t// increment the occurence to the map\n arr.forEach(letter => map[letter] = map[letter] + 1 || 1)\n \n\t// store all the distinct values in order\n for (let [key, val] of Object.entries(map)) \n if (val == 1) distinctArr.push(key)\n \n\t// return the key or empty string\n return distinctArr[k-1] || \"\"\n};\n~``", "solution_java": "class Solution {\n public String kthDistinct(String[] arr, int k) {\n Map map=new HashMap<>();\n \n for(String s:arr){\n \n if(map.containsKey(s)) map.put(s,map.get(s)+1);\n else map.put(s,1);\n }\n\t\tint i=0;\n for(String s:arr){\n if(map.get(s)==1 && ++i==k){\n \n return s;\n } \n \n }\n return \"\";\n \n }\n}", "solution_c": "class Solution \n{\npublic:\n string kthDistinct(vector& arr, int k) \n {\n unordered_mapm;\n for(int i=0;i int:\n\n m = len(matrix)\n n = len(matrix[0])\n\n dp = [[0 for _ in range(n)] for _ in range(m)]\n total = 0\n\n for i in range(m):\n for j in range(n):\n\n if i == 0:\n dp[i][j] = matrix[0][j]\n\n elif j == 0:\n dp[i][j] = matrix[i][0]\n\n else:\n if matrix[i][j] == 1:\n dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j-1], dp[i-1][j])\n\n total += dp[i][j]\n\n return total", "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number}\n */\nvar countSquares = function(matrix) {\n let count = 0;\n for (let i = 0; i < matrix.length; ++i) {\n for (let j = 0; j < matrix[0].length; ++j) {\n if (matrix[i][j] === 0) continue;\n if (i > 0 && j > 0) {\n matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1], matrix[i - 1][j - 1]);\n }\n count += matrix[i][j];\n }\n }\n return count; \n};", "solution_java": "class Solution {\n public int countSquares(int[][] matrix) {\n int m = matrix.length;\n int n = matrix[0].length;\n int[][] res = new int[m][n];\n \n for(int j=0; j>&mat , int n , int m , vector>&dp){\n\n if(n<0 or m<0 or mat[n][m] == 0 )\n return 0;\n\n if(dp[n][m] != -1 )\n return dp[n][m];\n\n return dp[n][m] = ( 1 + min({\n solve( mat , n-1 , m , dp ),\n solve(mat , n-1 , m-1 , dp ),\n solve(mat , n , m-1 , dp )\n }));\n\n }\n\n int countSquares(vector>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n int ans = 0 ;\n\n // vector>dp(n , vector(m,-1));\n // for(int i = 0 ; i>dp(n , vector(m, 0));\n\n for(int i = 0 ; i> 1;\n if (indices[mid] <= firstIndex) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n if (indices[lo] && indices[lo] < lastIndex) {\n count++;\n }\n }\n }\n return count;\n};", "solution_java": "class Solution {\n public int countPalindromicSubsequence(String s) {\n \n int n = s.length();\n \n char[] chArr = s.toCharArray();\n \n int[] firstOcc = new int[26];\n int[] lastOcc = new int[26];\n \n Arrays.fill(firstOcc, -1);\n Arrays.fill(lastOcc, -1);\n \n for(int i = 0; i < n; i++){\n \n char ch = chArr[i];\n \n if(firstOcc[ch - 'a'] == -1){\n firstOcc[ch - 'a'] = i;\n }\n \n lastOcc[ch - 'a'] = i;\n }\n \n int ans = 0, count = 0;\n \n boolean[] visited;\n \n\t\t// check for each character ( start or end of palindrome )\n for(int i = 0; i < 26; i++){\n \n int si = firstOcc[i]; // si - starting index\n int ei = lastOcc[i]; // ei - ending index\n \n visited = new boolean[26];\n \n count = 0;\n \n\t\t\t// check for unique charcters ( middle of palindrome )\n for(int j = si + 1; j < ei; j++){\n \n if(!visited[chArr[j] - 'a']){\n visited[chArr[j] - 'a'] = true;\n count++;\n }\n }\n \n ans += count;\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int countPalindromicSubsequence(string s) {\n \n vector > v(26, {-1, -1} ); //to store first occurance and last occurance of every alphabet.\n \n int n = s.length(); //size of the string\n \n for (int i = 0 ; i< n ;i++ ){\n if (v[s[i] - 'a'].first == -1 ) v[s[i] - 'a'].first = i; // storing when alphabet appered first time.\n else v[s[i] - 'a'].second = i; // else whenever it appears again. So that the last occurrence will be stored at last.\n }\n \n int ans = 0 ;\n for (int i = 0 ; i <26 ;i++ ){ //traversing over all alphabets.\n\n if (v[i].second != -1 ){ //only if alphabet occured second time.\n \n unordered_set st; //using set to keep only unique elements between the range.\n \n for (int x = v[i].first + 1 ; x < v[i].second ; x++ ) st.insert(s[x]); // set keeps only unique elemets.\n \n ans += ((int)st.size()); // adding number of unique elements to the answer.\n }\n }\n return ans;\n \n }\n};" }, { "title": "Divide a String Into Groups of Size k", "algo_input": "A string s can be partitioned into groups of size k using the following procedure:\n\n\n\tThe first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.\n\tFor the last group, if the string does not have k characters remaining, a character fill is used to complete the group.\n\n\nNote that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.\n\nGiven the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.\n\n \nExample 1:\n\nInput: s = \"abcdefghi\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\"]\nExplanation:\nThe first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".\n\n\nExample 2:\n\nInput: s = \"abcdefghij\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\",\"jxx\"]\nExplanation:\nSimilar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists of lowercase English letters only.\n\t1 <= k <= 100\n\tfill is a lowercase English letter.\n\n", "solution_py": "class Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n l, i, N = [], 0, len(s)\n while i divideString(string s, int k, char fill) {\n vector v;\n for(int i=0;i int:\n count_dict = {}\n total_days = 0\n for task in tasks:\n if task not in count_dict:\n count_dict[task] = -math.inf\n total_days = max(total_days + 1, count_dict[task] + space + 1)\n count_dict[task] = total_days\n return total_days", "solution_js": "var taskSchedulerII = function(tasks, n) {\n\tconst config = {};\n\tlet totalIteration = 0;\n\tlet currentTime = 0;\n\tfor (const iterator of tasks) {\n\t\tcurrentTime++;\n\t\tif (!config[iterator]) {\n\t\t\tconfig[iterator] = 0;\n\t\t} else {\n\t\t\tif (config[iterator] > currentTime) {\n\t\t\t\tlet difference = config[iterator] - currentTime;\n\t\t\t\ttotalIteration += difference;\n\t\t\t\tcurrentTime += difference;\n\t\t\t}\n\t\t}\n\t\tconfig[iterator] = currentTime + n + 1;\n\t\ttotalIteration++;\n\t}\n\n\treturn totalIteration;\n};", "solution_java": "class Solution {\n public long taskSchedulerII(int[] tasks, int space) {\n HashMap map = new HashMap<>();\n long day = 0;\n\n for (int item : tasks) {\n if (map.containsKey(item) && map.get(item) > day)\n day = map.get(item);\n\n day++;\n map.put(item, day + space);\n }\n\n return day;\n }\n}", "solution_c": "class Solution {\npublic:\n long long taskSchedulerII(vector& tasks, int space) {\n unordered_map hash; long long int curday=0;\n for(int i=0;i int:\n text = text.split()\n length = len(text)\n brokenLetters = set(brokenLetters)\n\n for word in text:\n for char in word:\n if char in brokenLetters:\n length -= 1\n break\n\t\t\t\t\t\n return length", "solution_js": "var canBeTypedWords = function(text, brokenLetters) {\n let regexp=\"[\"+brokenLetters+\"]\\+\"\n let word=text.split(\" \"), count=0;\n for(let i=0; i ch(26,0);\n\t\t// store the broken letters in ch vector\n for(char c: brokenLetters){\n ch[c-'a']=1;\n }\n int cnt=0,ans=0;\n\t\t//traversing the text string\n for(int i=0;i None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n full = set('123456789')\n\t\t# lets keep rows, columns and boxes sets in hashmaps\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n boxes = [[set() for _ in range(3)] for _ in range(3)]\n\t\t# and remember empty cell to fill them in\n empty = set()\n\n for i in range(9):\n for j in range(9):\n if board[i][j] == '.':\n empty.add((i,j))\n continue\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n def options(i, j):\n\t\t\t\"\"\"returns possible options for i,j intersecting options from row, col and box\"\"\"\n return (\n (full - rows[i]) &\n (full - cols[j]) &\n (full - boxes[i//3][j//3])\n )\n\n psingle = True # did we have single option decisions in previos traverse\n while empty:\n single = False # for single option decisions in this traverse\n \n for i, j in deepcopy(empty):\n opts = options(i, j)\n if len(opts) == 0:\n\t\t\t\t\t# we've made a wrong assumption - sudoku is unsolvable\n return None, None\n elif len(opts) == 2 and not psingle: # we have no single-option decisions so have to take an assumption\n board1 = deepcopy(board)\n board1[i][j] = opts.pop()\n board1, empty1 = self.solveSudoku(board1)\n if board1 != None: # if solved - we're done\n empty = empty1\n for i, b1 in enumerate(board1):\n board[i] = b1 # have to modify initial list, not just replace the reference\n return board, empty\n if len(opts) == 1: # hey, we have a predetermined choice. nice\n single = True\n board[i][j] = opts.pop()\n empty.remove((i, j))\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[i//3][j//3].add(board[i][j])\n \n psingle = single\n\n return board, empty\n ```", "solution_js": "var solveSudoku = function(board) {\n let intBoard = convertBoardToInteger(board);\n\n let y = 0, x = 0;\n\n while (y <= 8){\n x = 0;\n while (x <= 8){\n if (isFreeIndex(board, x, y)){\n intBoard[y][x]++;\n while (!isPossibleValue(intBoard, x, y) && intBoard[y][x] < 10){\n intBoard[y][x]++;\n };\n\n if (intBoard[y][x] > 9){\n intBoard[y][x] = 0;\n let a = retraceBoard(board, x, y);\n x = a[0], y = a[1];\n x--;\n }\n }\n x++;\n }\n y++;\n }\n \n convertIntBoardToString(intBoard, board);\n}\n\nvar isFreeIndex = function(board, x, y){\n return (board[y][x] == '.');\n}\n\nvar isPossibleValue = function(intBoard, x, y){\n return (isUniqueInColumn(intBoard, x, y) && isUniqueOnRow(intBoard, x, y) && isUniqueInBox(intBoard, x, y))\n}\nvar isUniqueOnRow = function(intBoard, x, y){\n for (let i = 0;i<9;i++){\n if (intBoard[i][x] == intBoard[y][x] && i != y){\n return false;\n }\n }\n return true;\n}\nvar isUniqueInColumn = function(intBoard, x, y){\n for (let i = 0;i<9;i++){\n if (intBoard[y][i] == intBoard[y][x] && i != x){\n return false;\n }\n }\n return true;\n}\nvar isUniqueInBox = function(intBoard, x, y){\n let startX = x - (x % 3);\n let startY = y - (y % 3);\n\n for (let i = startX; i < startX+3; i++){\n for (let j = startY; j < startY+3; j++){\n if (intBoard[j][i] == intBoard[y][x] && (i != x || j != y)){\n return false;\n }\n }\n }\n return true;\n}\n\nvar retraceBoard = function(board, x, y){\n do {\n if (x > 0){\n x--;\n } else {\n x = 8;\n y--;\n }\n } while (board[y][x] != '.');\n return [x,y]; \n}\n\nvar convertBoardToInteger = function(board){\n\n let intBoard = new Array(8);\n for (let y = 0;y<9;y++){\n intBoard[y] = new Array(8);\n for (let x = 0;x < 9;x++){\n intBoard[y][x] = parseInt(board[y][x]);\n if (!intBoard[y][x]) intBoard[y][x] = 0;\n }\n }\n return intBoard;\n}\nvar convertIntBoardToString = function(intBoard, board){\n for (let y = 0;y<9;y++){\n for (let x = 0;x < 9;x++){\n board[y][x] = intBoard[y][x].toString();\n }\n }\n \n return board;\n}", "solution_java": "class Solution {\n public void solveSudoku(char[][] board) {\n solve(board);\n }\n boolean solve(char board[][]){\n for(int i = 0; i> &board,int row,int col,char c)\n {\n for(int i=0;i<9;i++)\n {\n if(board[row][i]==c)\n return 0;\n if(board[i][col]==c)\n return 0;\n if(board[3*(row/3)+i/3][3*(col/3)+i%3]==c)\n return 0;\n }\n return 1;\n }\n \n bool solve(vector> & board)\n {\n for(int i=0;i<9;i++)\n {\n for(int j=0;j<9;j++)\n {\n if(board[i][j]=='.')\n {\n for(char c='1';c<='9';c++)\n {\n if(issafe(board,i,j,c))\n {\n board[i][j]=c;\n if(solve(board)==1)\n return 1;\n else\n board[i][j]='.';\n }\n }\n return 0; \n }\n }\n }\n return 1;\n }\n \n void solveSudoku(vector>& board) {\n solve(board);\n }\n};" }, { "title": "Maximize the Confusion of an Exam", "algo_input": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).\n\nYou are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:\n\n\n\tChange the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').\n\n\nReturn the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.\n\n \nExample 1:\n\nInput: answerKey = \"TTFF\", k = 2\nOutput: 4\nExplanation: We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.\n\n\nExample 2:\n\nInput: answerKey = \"TFFT\", k = 1\nOutput: 3\nExplanation: We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.\n\n\nExample 3:\n\nInput: answerKey = \"TTFTTFTT\", k = 1\nOutput: 5\nExplanation: We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.\n\n\n \nConstraints:\n\n\n\tn == answerKey.length\n\t1 <= n <= 5 * 104\n\tanswerKey[i] is either 'T' or 'F'\n\t1 <= k <= n\n\n", "solution_py": "class Solution:\n def maxConsecutiveAnswers(self, string: str, k: int) -> int:\n result = 0\n j = 0\n count1 = k\n for i in range(len(string)):\n if count1 == 0 and string[i] == \"F\":\n while string[j] != \"F\":\n j+=1\n count1+=1\n j+=1\n\n if string[i] == \"F\":\n if count1 > 0:\n count1-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n j = 0\n count2 = k\n for i in range(len(string)):\n if count2 == 0 and string[i] == \"T\":\n while string[j] != \"T\":\n j+=1\n count2+=1\n j+=1\n\n if string[i] == \"T\":\n if count2 > 0:\n count2-=1\n\n if i - j + 1 > result:\n result = i - j + 1\n\n return result", "solution_js": "var maxConsecutiveAnswers = function(answerKey, k) {\n let [left, right, numOfTrue, numOfFalse, max] = new Array(5).fill(0);\n const moreChanges = () => numOfTrue > k && numOfFalse > k;\n while (right < answerKey.length) {\n if(answerKey[right] === 'T') numOfTrue++;\n if(answerKey[right] === 'F') numOfFalse++;\n while(moreChanges()) {\n if(answerKey[left] === 'T') numOfTrue--;\n if(answerKey[left] === 'F') numOfFalse--; \n left++; \n }\n max = Math.max(max, right - left + 1);\n right++;\n }\n return max;\n};", "solution_java": "class Solution {\n\n // Binary Search + Sliding Window fixed\n\n public int maxConsecutiveAnswers(String answerKey, int k) {\n\n int start = 1 ;\n int end = answerKey.length();\n int max_length = 0 ;\n\n while(start <= end) {\n int mid = start+(end-start)/2 ;\n if(isMax(answerKey , k , mid)) {\n max_length = mid ;\n start = mid+1 ;\n }else {\n end = mid-1 ;\n }\n }\n\n return max_length ;\n }\n\n public boolean isMax(String answerKey , int k , int max_val) {\n\n int T_count = 0 ;\n int F_count = 0 ;\n\n int i = 0 ;\n int j = 0 ;\n\n while(j < answerKey.length()) {\n\n if(answerKey.charAt(j) == 'T') {\n T_count++ ;\n }else {\n F_count++ ;\n }\n\n if(j-i+1 == max_val) {\n\n if(Math.max(T_count, F_count)+k >= max_val) {\n return true ;\n }\n\n if(answerKey.charAt(i) == 'T') {\n T_count-- ;\n }else {\n F_count-- ;\n }\n\n i++ ;\n }\n\n j++ ;\n }\n\n return false ;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxConsecutiveAnswers(string answerKey, int k) {\n return max(helper(answerKey,k,'T'),helper(answerKey,k,'F'));\n }\n\n int helper(string answerKey, int k,char c){\n int start = 0;\n int end = 0;\n int count = 0;\n int ans = 0;\n while(endk){\n if(answerKey[start]==c)count--;\n start++;\n }\n ans = max(ans,end-start+1);\n end++;\n }\n return ans;\n }\n};" }, { "title": "Maximum Difference Between Increasing Elements", "algo_input": "Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].\n\nReturn the maximum difference. If no such i and j exists, return -1.\n\n \nExample 1:\n\nInput: nums = [7,1,5,4]\nOutput: 4\nExplanation:\nThe maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.\n\n\nExample 2:\n\nInput: nums = [9,4,3,2]\nOutput: -1\nExplanation:\nThere is no i and j such that i < j and nums[i] < nums[j].\n\n\nExample 3:\n\nInput: nums = [1,5,2,10]\nOutput: 9\nExplanation:\nThe maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n\n\n \nConstraints:\n\n\n\tn == nums.length\n\t2 <= n <= 1000\n\t1 <= nums[i] <= 109\n\n", "solution_py": "class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n curmin = nums[0]\n diff = 0\n for num in nums:\n diff = max(diff, num - curmin)\n curmin = min(curmin, num)\n return diff or -1", "solution_js": "var maximumDifference = function(nums) {\n var diff=-1\n for(let i=0;i nums[i]) diff=Math.max(nums[j]-nums[i],diff)\n }\n }\n return diff\n};", "solution_java": "class Solution {\n public int maximumDifference(int[] nums) {\n if(nums.length < 2)\n return -1;\n int result = Integer.MIN_VALUE;\n int minValue = nums[0];\n for(int i = 1; i < nums.length; i++) {\n if(nums[i] > minValue)\n result = Math.max(result, nums[i] - minValue);\n minValue = Math.min(minValue, nums[i]);\n }\n return result == Integer.MIN_VALUE ? -1 : result;\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumDifference(vector& nums) {\n int mn = nums[0], res = 0;\n for (int i = 1; i < nums.size(); i++) {\n res = max(res, nums[i] - mn);\n mn = min(mn, nums[i]);\n }\n return res == 0 ? -1 : res;\n }\n};" }, { "title": "Sort the Matrix Diagonally", "algo_input": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].\n\nGiven an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.\n\n \nExample 1:\n\nInput: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n\n\nExample 2:\n\nInput: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 100\n\t1 <= mat[i][j] <= 100\n\n", "solution_py": "class Solution:\n def diagonalSort(self, A: List[List[int]]) -> List[List[int]]:\n n, m, d = len(A), len(A[0]), defaultdict(list)\n any(d[i - j].append(A[i][j]) for i in range(n) for j in range(m))\n any(d[sum_].sort(reverse=1) for sum_ in d)\n return [[d[i-j].pop() for j in range(m)] for i in range(n)]", "solution_js": "/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nvar diagonalSort = function(mat) {\nconst res=new Array(mat.length);\n \nfor(let i=0;ia-b);\n index.forEach(([x,y],id)=>res[x][y]=val[id]);\n }\n }\n}\n return res;\n\n};", "solution_java": "class Solution {\n public int[][] diagonalSort(int[][] mat) {\n int n = mat.length; \n int m = mat[0].length;\n for(int i=0;i>& mat,int m,int n,vector& temp){\n\t\tif(i>=m || j>=n){\n\t\t\tsort(temp.begin(),temp.end());\n\t\t\treturn ;\n\t\t}\n\t\ttemp.push_back(mat[i][j]);\n\t\tsortmat(i+1,j+1,mat,m,n,temp);\n\t\tmat[i][j]=temp.back();\n\t\ttemp.pop_back();\n\t}\n\n\tvector> diagonalSort(vector>& mat) {\n\t\tint m=mat.size();\n\t\tint n=mat[0].size();\n\t\tvectortemp;\n// For column\n\t\tfor(int j=0;j List[str]:\n start, end = s.split(':')\n start_letter, start_num = start[0], int(start[-1])\n end_letter, end_num = end[0], int(end[1])\n alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')\n alphabet_slice = \\\n alphabet[alphabet.index(start_letter):alphabet.index(end_letter) + 1]\n res = list()\n for el in alphabet_slice:\n res += [el + str(num) for num in range(start_num, end_num + 1)]\n return res", "solution_js": "const toCharCode = (char) => char.charCodeAt()\n\nvar cellsInRange = function(s) {\n const result = []\n for(let i = toCharCode(s[0]) ; i <= toCharCode(s[3]) ; i++){\n for(let j = s[1] ; j <= s[4] ; j++){\n result.push(String.fromCharCode(i) +j)\n }\n }\n return result\n};", "solution_java": "class Solution {\n public List cellsInRange(String s) {\n char sc = s.charAt(0), ec = s.charAt(3);\n char sr = s.charAt(1), er = s.charAt(4);\n List res = new ArrayList<>();\n \n for (char i = sc; i <= ec; ++i){\n for (char j = sr; j <= er; ++j){\n res.add(new String(new char[]{i, j}));\n }\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector cellsInRange(string s) {\n\n vectorans;\n\n for(char ch=s[0];ch<=s[3];ch++)\n {\n for(int i=s[1]-'0';i<=s[4]-'0';i++)\n {\n string res=\"\";\n res+=ch;\n res+=to_string(i);\n ans.push_back(res);\n\n }\n }\n return ans;\n }\n};" }, { "title": "Candy", "algo_input": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.\n\nYou are giving candies to these children subjected to the following requirements:\n\n\n\tEach child must have at least one candy.\n\tChildren with a higher rating get more candies than their neighbors.\n\n\nReturn the minimum number of candies you need to have to distribute the candies to the children.\n\n \nExample 1:\n\nInput: ratings = [1,0,2]\nOutput: 5\nExplanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n\n\nExample 2:\n\nInput: ratings = [1,2,2]\nOutput: 4\nExplanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.\n\n\n \nConstraints:\n\n\n\tn == ratings.length\n\t1 <= n <= 2 * 104\n\t0 <= ratings[i] <= 2 * 104\n\n", "solution_py": "class Solution:\n def candy(self, ratings: List[int]) -> int:\n n=len(ratings)\n temp = [1]*n\n\n for i in range(1,n):\n if(ratings[i]>ratings[i-1]):\n temp[i]=temp[i-1]+1\n if(n>1):\n if(ratings[0]>ratings[1]):\n temp[0]=2\n\n for i in range(n-2,-1,-1):\n if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):\n temp[i]=temp[i+1]+1\n\n return sum(temp)", "solution_js": "/**\n * @param {number[]} ratings\n * @return {number}\n */\nvar candy = function(ratings) {\n const n = ratings.length; \n \n let candies = [...Array(n)].fill(1);\n \n let index = 0;\n let copy = [ratings[0]];\n \n let isDecreasing = true;\n for(let i = 1; i < n; i++) {\n if (ratings[i] > ratings[i - 1]) {\n isDecreasing = false;\n break;\n }\n /* In case of decreasing sequence, make a copy of the current rating, but in inverted format */\n copy.unshift(ratings[i]);\n }\n \n if (isDecreasing) {\n ratings = copy;\n } else {\n copy = [];\n }\n \n while(index >= 0) {\n \n if (index >= n) {\n break;\n }\n\n if (ratings[index] > ratings[index + 1] && candies[index + 1] >= candies[index]) { \n candies[index] = candies[index] + 1; \n index = Math.max(-1, index - 2);\n }\n else if (ratings[index] > ratings[index - 1] && candies[index - 1] >= candies[index]) { \n candies[index] = candies[index - 1] + 1;\n }\n\n index++;\n }\n\n \n return candies.reduce((sum, candy) => sum + candy, 0);\n}", "solution_java": "class Solution {\n public int candy(int[] ratings) {\n\n int[] left = new int[ratings.length];\n Arrays.fill(left, 1);\n\n // we are checking from left to right that if the element next to our current element has greater rating, if yes then we are increasing their candy\n for(int i = 0; i=0; i--){\n if(ratings[i+1] < ratings[i] && right[i] <= right[i+1])\n right[i] = right[i+1]+1;\n }\n int sum = 0;\n for(int i = 0; i& ratings) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n int ans = 0, i;\n vector store(ratings.size(), 1);\n for (i = 0; i < ratings.size()-1; i++) if(ratings[i+1] > ratings[i]) store[i+1] = store[i]+1;\n for (i = ratings.size()-1; i > 0; i--) if(ratings[i-1] > ratings[i]) store[i-1] = max(store[i-1], store[i]+1);\n for (auto i:store) ans += i;\n return ans;\n }\n};" }, { "title": "Last Stone Weight", "algo_input": "You are given an array of integers stones where stones[i] is the weight of the ith stone.\n\nWe are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:\n\n\n\tIf x == y, both stones are destroyed, and\n\tIf x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\n\n\nAt the end of the game, there is at most one stone left.\n\nReturn the weight of the last remaining stone. If there are no stones left, return 0.\n\n \nExample 1:\n\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\n\n\nExample 2:\n\nInput: stones = [1]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= stones.length <= 30\n\t1 <= stones[i] <= 1000\n\n", "solution_py": "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n stones = [-x for x in stones]\n heapq.heapify(stones)\n\n while len(stones) > 1:\n mx1 = -heapq.heappop(stones)\n mx2 = -heapq.heappop(stones)\n if mx1 - mx2:\n heapq.heappush(stones, -(mx1 - mx2))\n\n if len(stones):\n return -heapq.heappop(stones)\n return 0", "solution_js": "var lastStoneWeight = function(stones) {\n let first = 0, second = 0;\n stones.sort((a,b) => a - b);\n while(stones.length > 1) {\n first = stones.pop();\n second = stones.pop();\n stones.push(first - second);\n stones.sort((a,b) => a - b);\n }\n return stones[0];\n};", "solution_java": "class Solution {\n public int lastStoneWeight(int[] stones) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Integer.compare(y,x));\n for (int i = 0; i < stones.length; i++) {\n pq.add(stones[i]);\n }\n while (pq.size() > 1) {\n int r1 = pq.poll();\n int r2 = pq.poll();\n if (r1 != r2) pq.add(r1 - r2);\n }\n return (pq.isEmpty()) ? 0 : pq.poll();\n }\n}", "solution_c": "class Solution {\npublic:\n int lastStoneWeight(vector& stones) {\n while(stones.size()>1){\n sort(stones.begin(), stones.end(), greater());\n stones[1] = (stones[0]-stones[1]);\n stones.erase(stones.begin());\n }\n return stones[0];\n }\n};" }, { "title": "Widest Vertical Area Between Two Points Containing No Points", "algo_input": "Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.\n\nA vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.\n\nNote that points on the edge of a vertical area are not considered included in the area.\n\n \nExample 1:\n​\nInput: points = [[8,7],[9,9],[7,4],[9,7]]\nOutput: 1\nExplanation: Both the red and the blue area are optimal.\n\n\nExample 2:\n\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput: 3\n\n\n \nConstraints:\n\n\n\tn == points.length\n\t2 <= n <= 105\n\tpoints[i].length == 2\n\t0 <= xi, yi <= 109\n\n", "solution_py": "class Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n # only taking x-axis point as it's relevant\n arr = [i[0] for i in points]\n \n arr.sort()\n \n diff = -1\n for i in range(1, len(arr)):\n diff = max(diff, arr[i] - arr[i - 1])\n \n return diff", "solution_js": "var maxWidthOfVerticalArea = function(points) {\n let ans = 0;\n points = points.map(item => item[0]).sort((a, b) => a - b);\n \n for(let i = 1; i < points.length; i++){\n \n ans = Math.max(ans, points[i] - points[i-1]);\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int maxWidthOfVerticalArea(int[][] points) {\n int L = points.length;\n // y-coordinate of a point does not matter in width\n int arr[] = new int[L];\n for(int i=0;idiff){\n diff=arr[i]-arr[i-1];\n }\n }\n return diff;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxWidthOfVerticalArea(vector>& points) {\n sort(begin(points),end(points));\n int n=points.size();\n int m=0;\n for(int i=0;i List[int]:\n maxright = arr[-1]\n for i in range(len(arr) -1,-1,-1):\n temp = arr[i]\n arr[i] = maxright\n if temp > maxright:\n maxright = temp\n arr[-1] = -1\n \n return arr", "solution_js": " * @param {number[]} arr\n * @return {number[]}\n */\nvar replaceElements = function(arr) {\n let max = arr[arr.length -1]\n \n for(let j=arr.length - 2; j>=0; --j){\n let curr = arr[j];\n arr[j] = max\n max = Math.max(max,curr)\n }\n \n arr[arr.length -1] = -1;\n return arr;\n};", "solution_java": "class Solution {\n public int[] replaceElements(int[] arr) {\n int greatElement = -1;\n for(int i = arr.length-1; i >= 0; i--) {\n int temp = arr[i];\n arr[i] = greatElement;\n greatElement = Math.max(temp, greatElement);\n }\n return arr;\n }\n}", "solution_c": "class Solution {\npublic:\n vector replaceElements(vector& arr) {\n int n=arr.size();\n\n //taking last index as greatest for now\n int g=arr[n-1];\n //setting last index as -1\n arr[n-1]=-1;\n for(int i=n-2;i>=0;i--)\n {\n //storing last index value to be changed to comapare with the greatest value till now\n int h=arr[i];\n //assigning greatest till now from right\n arr[i]=g;\n //checking if current is greater than the previous indices\n if(h>g)\n {\n g=h;\n }\n }\n //returning the value\n return arr;\n }\n};" }, { "title": "Best Poker Hand", "algo_input": "You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].\n\nThe following are the types of poker hands you can make from best to worst:\n\n\n\t\"Flush\": Five cards of the same suit.\n\t\"Three of a Kind\": Three cards of the same rank.\n\t\"Pair\": Two cards of the same rank.\n\t\"High Card\": Any single card.\n\n\nReturn a string representing the best type of poker hand you can make with the given cards.\n\nNote that the return values are case-sensitive.\n\n \nExample 1:\n\nInput: ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\nOutput: \"Flush\"\nExplanation: The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".\n\n\nExample 2:\n\nInput: ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\nOutput: \"Three of a Kind\"\nExplanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.\n\nExample 3:\n\nInput: ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\nOutput: \"Pair\"\nExplanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".\n\n\n \nConstraints:\n\n\n\tranks.length == suits.length == 5\n\t1 <= ranks[i] <= 13\n\t'a' <= suits[i] <= 'd'\n\tNo two cards have the same rank and suit.\n\n", "solution_py": "class Solution:\n def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n s={}\n for i in suits:\n if i in s:\n s[i]+=1\n if s[i]==5:\n return 'Flush'\n else:\n s[i]=1\n r={}\n max_ = 0\n for i in ranks:\n if i in r:\n r[i]+=1\n max_=max(max_,r[i])\n else:\n r[i]=1\n if max_>=3:\n return \"Three of a Kind\"\n elif max_==2:\n return \"Pair\"\n else:\n return \"High Card\"", "solution_js": "var bestHand = function(ranks, suits) {\n let suitsMap = {}\n for (let i=0; i= 3) return \"Three of a Kind\";\n } else {\n ranksMap[ranks[i]] = 1;\n }\n }\n if (Object.keys(ranksMap).length === 5) return \"High Card\";\n return \"Pair\";\n};", "solution_java": "class Solution {\n public String bestHand(int[] ranks, char[] suits) {\n int max = 0;\n int card = 0;\n char ch = suits[0];\n int[] arr = new int[14];\n for(int i = 0; i < 5; i++){\n arr[ranks[i]]++;\n max = Math.max(max,arr[ranks[i]]);\n if(suits[i] == ch) card++;\n }\n if(card == 5) return \"Flush\";\n return max >= 3 ? \"Three of a Kind\":(max == 2 ? \"Pair\" : \"High Card\");\n }\n}", "solution_c": "class Solution {\npublic:\n string bestHand(vector& ranks, vector& suits) {\n map m1;\n int mn = INT_MIN;\n int all_same = count(begin(suits), end(suits), suits[0]);\n int n = ranks.size();\n for (int i = 0; i < n; i++) {\n m1[ranks[i]]++;\n mn = max(mn, m1[ranks[i]]);\n }\n if (all_same == n) return \"Flush\";\n if (mn >= 3) return \"Three of a Kind\";\n if (mn == 2) return \"Pair\";\n return \"High Card\";\n }\n};" }, { "title": "Populating Next Right Pointers in Each Node II", "algo_input": "Given a binary tree\n\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n\n\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\n\nInitially, all next pointers are set to NULL.\n\n \nExample 1:\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: [1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 6000].\n\t-100 <= Node.val <= 100\n\n\n \nFollow-up:\n\n\n\tYou may only use constant extra space.\n\tThe recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.\n\n", "solution_py": "\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=0, left=None, right=None, next=None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n\"\"\"\n\nclass Solution(object):\n def findRightMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n right = self.findRightMost(root.right, level + 1, requiredLevel)\n if right:\n return right\n return self.findRightMost(root.left, level + 1, requiredLevel)\n def findLeftMost(self, root, level, requiredLevel):\n if not root:\n return root\n if level == requiredLevel:\n return root\n left = self.findLeftMost(root.left, level + 1, requiredLevel)\n if left:\n return left\n return self.findLeftMost(root.right, level + 1, requiredLevel)\n def findRightMostFromRoot(self, rootLevelInfo, requiredLevel, currentRight):\n if currentRight:\n if currentRight.right:\n return currentRight.right\n if currentRight.left:\n return currentRight.left\n root, rootlevel = rootLevelInfo\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n while not rightMost and root:\n root = root.right if root.right else root.left\n rootlevel += 1\n rightMost = self.findRightMost(root, rootlevel, requiredLevel)\n if rightMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n return rightMost\n def findLeftMostFromRoot(self, rootLevelInfo, requiredLevel, currentLeft):\n if currentLeft:\n if currentLeft.left:\n return currentLeft.left\n if currentLeft.right:\n return currentLeft.right\n root, rootlevel = rootLevelInfo\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n while not leftMost and root:\n root = root.left if root.left else root.right\n rootlevel += 1\n leftMost = self.findLeftMost(root, rootlevel, requiredLevel)\n if leftMost:\n rootLevelInfo[-1] = rootlevel\n rootLevelInfo[0] = root\n\n return leftMost\n def stitch(self, root):\n if not root:\n return\n leftRootStart = [root.left, 1]\n rightRootStart = [root.right, 1]\n connectLevel = 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, 1, None)\n currentRight = self.findRightMostFromRoot(leftRootStart, 1, None)\n while currentLeft and currentRight:\n currentRight.next = currentLeft\n connectLevel += 1\n currentLeft = self.findLeftMostFromRoot(rightRootStart, connectLevel, currentLeft)\n currentRight = self.findRightMostFromRoot(leftRootStart, connectLevel, currentRight)\n\n self.stitch(root.left)\n self.stitch(root.right)\n def connect(self, root):\n \"\"\"\n :type root: Node\n :rtype: Node\n \"\"\"\n if not root:\n return root\n self.stitch(root)\n return root", "solution_js": "var connect = function(root) {\n let curr = root;\n \n while (curr != null) {\n let start = null; // (1)\n let prev = null;\n \n while (curr != null) { // (2)\n if (start == null) { // (3)\n if (curr.left) start = curr.left;\n else if (curr.right) start = curr.right;\n \n prev = start; // (4)\n }\n \n if (prev != null) {\n if (curr.left && prev != curr.left) {\n prev = prev.next = curr.left; // (5)\n }\n if (curr.right && prev != curr.right) {\n prev = prev.next = curr.right;\n }\n }\n\n curr = curr.next; // (6)\n }\n\t\t\n curr = start; // (7)\n }\n \n return root;\n};", "solution_java": "class Solution {\n public Node connect(Node root) {\n if (root == null) {\n return root;\n }\n Node head = null; //the start node of next level, the first left of next level\n Node prev = null; //the next pointer\n Node curr = root;\n\n while (curr != null) {\n //traverse the whole current level, left -> right, until we meet a null pointer\n while (curr != null) {\n if (curr.left != null) {\n if (head == null) {\n head = curr.left;\n prev = curr.left;\n } else {\n prev.next = curr.left;\n prev = prev.next;\n }\n }\n\n if (curr.right != null) {\n if (head == null) {\n head = curr.right;\n prev = curr.right;\n } else {\n prev.next = curr.right;\n prev = prev.next;\n }\n }\n curr = curr.next;\n }\n\n curr = head;\n prev = null;\n head = null;\n }\n return root;\n }\n}", "solution_c": "// method-1\nclass Solution {\npublic:\n Node* connect(Node* root) {\n if(!root)\n return NULL;\n queue q;\n q.push(root);\n root->next=NULL;\n\n while(!q.empty()){\n\n int size=q.size();\n Node* prev=NULL;\n\n for(int i=0;inext=temp;\n\n if(i==size-1){\n temp->next=NULL;\n }\n\n if(temp->left)\n q.push(temp->left);\n\n if(temp->right)\n q.push(temp->right);\n\n prev=temp;\n\n }\n }\n\n return root;\n }\n};" }, { "title": "Number of Laser Beams in a Bank", "algo_input": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.\n\nThere is one laser beam between any two security devices if both conditions are met:\n\n\n\tThe two devices are located on two different rows: r1 and r2, where r1 < r2.\n\tFor each row i where r1 < i < r2, there are no security devices in the ith row.\n\n\nLaser beams are independent, i.e., one beam does not interfere nor join with another.\n\nReturn the total number of laser beams in the bank.\n\n \nExample 1:\n\nInput: bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\nOutput: 8\nExplanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0th row with any on the 3rd row.\nThis is because the 2nd row contains security devices, which breaks the second condition.\n\n\nExample 2:\n\nInput: bank = [\"000\",\"111\",\"000\"]\nOutput: 0\nExplanation: There does not exist two devices located on two different rows.\n\n\n \nConstraints:\n\n\n\tm == bank.length\n\tn == bank[i].length\n\t1 <= m, n <= 500\n\tbank[i][j] is either '0' or '1'.\n\n", "solution_py": "class Solution(object):\n def numberOfBeams(self, bank):\n ans, pre = 0, 0\n for s in bank:\n n = s.count('1')\n if n == 0: continue\n ans += pre * n\n pre = n\n return ans", "solution_js": "var numberOfBeams = function(bank) {\n let totalBeams = 0;\n const maximumSecurityDevicePerRow = bank.map(row => (row.match(/1/g) || []).length).filter(Boolean)\n for (let index = 0; index < maximumSecurityDevicePerRow.length - 1; index++) \n totalBeams+= maximumSecurityDevicePerRow[index] * maximumSecurityDevicePerRow[index + 1];\n return totalBeams;\n};", "solution_java": "class Solution {\n public int numberOfBeams(String[] bank) {\n int ans = 0, pre = 0;\n for (int i = 0;i < bank.length; i ++) {\n int n = 0;\n for (int j = 0; j < bank[i].length(); j ++) if(bank[i].charAt(j) == '1') n ++;\n if (n == 0) continue;\n ans += pre * n;;\n pre = n;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfBeams(vector& bank) \n {\n int rowLaserCount=0,totalLaserCount=0,prevCount=0;\n for(int i=0;i List[int]:\n n = len(arr)\n count_one = arr.count(1)\n if count_one == 0: return [0,n-1]\n if count_one % 3!= 0: return [-1,-1]\n target_ones = count_one // 3\n breaks = []\n one_count = 0\n for i , bit in enumerate(arr):\n if bit ==1 :\n one_count +=1\n if one_count in [1,target_ones+1,2*target_ones+1]:breaks.append(i) \n if one_count in [target_ones,2*target_ones,3*target_ones]:breaks.append(i)\n i1,j1,i2,j2,i3,j3 = breaks\n \n if not arr[i1:j1+1] == arr[i2:j2+1] == arr[i3:j3+1]:return [-1,-1]\n \n trailing_zeroes_left = i2 - j1 - 1\n trailing_zeroes_mid = i3 - j2 - 1\n trailing_zeroes_right = n - j3 - 1\n if trailing_zeroes_right > min(trailing_zeroes_left,trailing_zeroes_mid):return [-1,-1]\n j1 += trailing_zeroes_right\n j2 += trailing_zeroes_right\n return [j1,j2+1]\n ", "solution_js": "/**\n * @param {number[]} arr\n * @return {number[]}\n */\nvar threeEqualParts = function(arr) {\n const ones = arr.reduce((s, n) => s + n, 0);\n if (ones === 0) return [0, 2];\n if (ones % 3 !== 0) return [-1, -1];\n let onesToFind = ones / 3;\n let k = arr.length;\n while (onesToFind > 0) if (arr[--k] === 1) --onesToFind;\n const iter = arr.length - k;\n const firstOne = arr.indexOf(1);\n const secondOne = arr.indexOf(1, firstOne + iter);\n for (let i = 0; i < iter; i++)\n if (arr[i + firstOne] !== arr[k + i] || arr[i + secondOne] !== arr[k + i]) return [-1, -1];\n return [firstOne + iter - 1, secondOne + iter];\n};", "solution_java": "class Solution {\n public int[] threeEqualParts(int[] arr) {\n List ones = new ArrayList<>();\n for (int i = 0; i < arr.length; i++){\n if (arr[i]==1){\n ones.add(i);\n }\n }\n if (ones.size()==0){ // edge case\n return new int[]{0,2};\n }\n int[] ans = new int[2];\n int each = ones.size()/3;\n for (int i = 0; i < 2 && ones.size()%3==0; i++){ // for the first 2 partitions\n for (int j = 0; j < each-1; j++){ // compare gaps\n if (ones.get(j+1+i*each)-ones.get(j+i*each)!=ones.get(j+2*each+1)-ones.get(j+2*each))\n return new int[]{-1, -1};\n }\n ans[i]=ones.get((i+1)*each-1)+i+(arr.length - 1 - ones.get(ones.size()-1)); // cut point\n }\n return ones.size()%3>0||ans[0]>=ones.get(each)||ans[1]>ones.get(2*each)?\n new int[]{-1, -1} : ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector threeEqualParts(vector& v) {\n vector one;\n int n=v.size();\n for(int i=0;i0 || v[i]) s1+=to_string(v[i]);\n }\n\n for(int i=one[sz/3-1]+ext;i<=one[2*sz/3-1]+ext-1;i++){\n if(s2.length()>0 || v[i]) s2+=to_string(v[i]);\n }\n\n for(int i=one[2*sz/3-1]+ext;i<=n-1;i++){\n if(s3.length()>0 || v[i]) s3+=to_string(v[i]);\n }\n //All 3 Numbers in vector v :-\n // num1={0,one[sz/3-1]+ext-1};\n // num2={one[sz/3-1]+ext,one[2*sz/3-1]+ext-1}\n // num3={one[2*sz/3-1]+ext,n-1};\n if(s1==s2 && s2==s3) return {one[sz/3-1]+ext-1,one[2*sz/3-1]+ext};\n return {-1,-1};\n }\n};" }, { "title": "Shortest Path with Alternating Colors", "algo_input": "You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.\n\nYou are given two arrays redEdges and blueEdges where:\n\n\n\tredEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and\n\tblueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.\n\n\nReturn an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.\n\n \nExample 1:\n\nInput: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []\nOutput: [0,1,-1]\n\n\nExample 2:\n\nInput: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]\nOutput: [0,1,-1]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 100\n\t0 <= redEdges.length, blueEdges.length <= 400\n\tredEdges[i].length == blueEdges[j].length == 2\n\t0 <= ai, bi, uj, vj < n\n\n", "solution_py": "class Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n g = [[[] for _ in range(2)] for _ in range(n)]\n \n for i,j in redEdges:\n g[i][0] += [j]\n for i,j in blueEdges:\n g[i][1] += [j]\n distance = [float(\"inf\") for _ in range(n)]\n distance[0] = 0\n q = queue.Queue()\n q.put((0,0,False))\n q.put((0,0,True))\n \n redS = set([0])\n blueS = set([0])\n while not q.empty():\n node,dist,red = q.get()\n if red:\n neighbours = g[node][0]\n redS.add(node)\n curr = blueS\n else:\n neighbours = g[node][1]\n blueS.add(node)\n curr = redS\n for neighbour in neighbours:\n if dist + 1 < distance[neighbour]:\n distance[neighbour] = dist + 1\n q.put((neighbour,dist + 1,not red))\n if not (neighbour in curr):\n q.put((neighbour,dist + 1,not red))\n for i in range(n):\n if distance[i] == float(\"inf\"):\n distance[i] = -1\n return distance\n ", "solution_js": "const RED = \"red\";\nconst BLUE = \"blue\";\n\nfunction mapAllEdges(edges) {\n const map = new Map();\n for(let edge of edges) {\n if(!map.has(edge[0])) {\n map.set(edge[0], []);\n }\n map.get(edge[0]).push(edge[1])\n }\n return map;\n}\n\nfunction bfs(color, redNodeMap, blueNodeMap, result) {\n const queue = [0];\n let length = 0;\n let currentColor = color;\n while(queue.length > 0) {\n const size = queue.length;\n for(let i = 0; i < size; i++) {\n const node = queue.shift();\n if(result[node] === -1 || length < result[node] ) {\n result[node] = length;\n }\n const map = RED === currentColor ? redNodeMap : blueNodeMap;\n if(map.has(node)) {\n const edges = map.get(node);\n map.delete(node);\n queue.push(...edges)\n }\n }\n length++;\n currentColor = RED === currentColor ? BLUE : RED;\n }\n return result;\n}\n\nfunction shortestPath(redEdges, blueEdges, color, result) {\n const redNodeMap = mapAllEdges(redEdges);\n const blueNodeMap = mapAllEdges(blueEdges);\n bfs(color, redNodeMap, blueNodeMap, result);\n}\n\n/**\n * @param {number} n\n * @param {number[][]} redEdges\n * @param {number[][]} blueEdges\n * @return {number[]}\n */\nvar shortestAlternatingPaths = function(n, redEdges, blueEdges) {\n const result = new Array(n).fill(-1);\n shortestPath(redEdges, blueEdges, RED, result);\n shortestPath(redEdges, blueEdges, BLUE, result);\n return result\n};", "solution_java": "class Solution {\n // g1-> graph with red edges\n // g2-> graph with blue edges\n List g1[], g2[];\n int[] dist1, dist2, ans;\n int MX = (int) 2e9;\n\n public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) {\n dist1 = new int[n];\n dist2 = new int[n];\n g1=new ArrayList[n];\n g2=new ArrayList[n];\n ans=new int[n];\n for (int i=0;i();\n g2[i]=new ArrayList<>();\n dist1[i]=MX;\n dist2[i]=MX;\n ans[i]=MX;\n }\n for (int i=0;idist2[u]+1){\n dist1[v]=dist2[u]+1;\n dfs(v,!flag);\n }\n }\n } else {\n for (int v: g2[u]) {\n if (dist2[v]>dist1[u]+1){\n dist2[v]=dist1[u]+1;\n dfs(v,!flag);\n }\n }\n }\n }\n}", "solution_c": "#define red 1\n#define blue 2\nclass Solution {\npublic:\n vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) {\n vector>> graph(n);\n vector> visited(n, vector(3, false));\n for(int i = 0;i> q;\n q.push({0, 0, 0});\n \n vector res(n, INT_MAX);\n \n while(!q.empty())\n {\n auto top = q.front();\n q.pop();\n int parent = get<0>(top);\n int step = get<1>(top);\n int color = get<2> (top);\n res[parent] = min(res[parent], step);\n if(visited[parent][color]) continue;\n visited[parent][color] = true;\n for(auto child:graph[parent])\n {\n if(color == child.second) continue;\n q.push(make_tuple(child.first, step+1, child.second));\n }\n }\n for(int i = 0;i int:\n\t\treturn n - 1", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar numberOfMatches = function(n) {\n let matches = 0,current = n;\n while(current > 1){\n if(current % 2 === 0){\n matches += current/2;\n current = current/2\n }else{\n matches += (current-1)/2;\n current = (current-1)/2 + 1 ;\n }\n }\n return matches;\n};", "solution_java": "class Solution {\n public int numberOfMatches(int n) {\n\t\t// This is the problem's base case; we know that if n == 1,\n\t\t// the number of matches played must be 0, since the last team left\n\t\t// can't play a match against themselves.\n if (n == 1) return 0;\n \n\t\t// We declare an int to hold our recursive solution.\n int res;\n\t\t\n\t\t// We initialize res using a recursive call, reducing n \n\t\t// as described in the problem.\n if (n % 2 == 0) {\n res = numberOfMatches(n / 2);\n\t\t\t// After the recursive call is executed, we add the appropriate value to \n\t\t\t// our solution variable.\n res += n / 2;\n }\n else {\n res = numberOfMatches((n - 1) / 2 + 1);\n res += (n - 1) / 2;\n }\n \n\t\t// Our initial call to numberOfMatches()\n\t\t// will return the total number of matches \n\t\t// added to res in each recursive call.\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int numberOfMatches(int n) {\n int count=0;\n while(n>1)\n { \n if(n%2==0)\n {\n int a=n/2;\n n=n/2;\n count=count+a;}\n else\n {\n int a=(n-1)/2;\n n=a+1;\n count=count+a;\n } \n }\n return count;\n }\n};" }, { "title": "Remove Duplicates from Sorted Array II", "algo_input": "Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. 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,1,2,2,3]\nOutput: 5, nums = [1,1,2,2,3,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3]\nOutput: 7, nums = [0,0,1,1,2,3,3,_,_]\nExplanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 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-104 <= nums[i] <= 104\n\tnums is sorted in non-decreasing order.\n\n", "solution_py": "class Solution(object):\n def removeDuplicates(self, nums):\n n=len(nums)\n if n==2:\n return 2\n if n==0:\n return 0\n if n==1:\n return 1\n same=0\n start=-1\n end=-1\n i=0\n while i= nums[i - 1] && count <= 2)) nums[i++] = num;\n }\n return i;\n};", "solution_java": "class Solution {\n public int removeDuplicates(int[] nums) {\n int index = 1;\n int count = 0;\n for(int i = 1;i& nums) {\n int l = 1;\n int last_selected = nums[0];\n int count = 1;\n int n = nums.size();\n for(int i = 1;i List[List[int]]:\n n = len(land)\n m = len(land[0])\n\n groups = []\n visited = set()\n\n for y in range(n):\n for x in range(m):\n if land[y][x] == 0:\n continue\n\n if (y, x) in visited:\n continue\n\n q = collections.deque()\n q.append((y, x))\n visited.add((y, x))\n\n while q:\n cy, cx = q.popleft()\n\n for dy, dx in ((0, 1), (1, 0)):\n if (cy + dy, cx + dx) in visited:\n continue\n\n if 0 <= cy + dy < n and 0 <= cx + dx < m:\n if land[cy + dy][cx + dx] == 1:\n q.append((cy + dy, cx + dx))\n visited.add((cy + dy, cx + dx))\n\n groups.append([y, x, cy, cx])\n\n return groups", "solution_js": "var findFarmland = function(land) {\n let height = land.length;\n let width = land[0].length;\n let results = [];\n let endRow = 0;\n let endCol = 0;\n\n let go = (i, j) => {\n if (i < 0 || j < 0 || i >= height || j >= width || land[i][j] === 0) {\n return;\n }\n\n endRow = Math.max(endRow, i);\n endCol = Math.max(endCol, j);\n land[i][j] = 0; // reset everything to 0\n\n go(i + 1, j);\n go(i - 1, j);\n go(i, j + 1);\n go(i, j - 1);\n }\n\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n if (land[i][j] === 1) {\n endRow = 0;\n endCol = 0;\n go(i, j);\n results.push([i, j, endRow, endCol]);\n }\n }\n }\n\n return results;\n};", "solution_java": "class Solution {\n int[] arr;\n public int[][] findFarmland(int[][] land) {\n List res = new ArrayList<>();\n for(int i=0;ii).toArray(int[][] :: new);\n }\n public void dfs(int[][] land, int i,int j){\n if(i<0 || j<0 || i>=land.length || j>= land[0].length || land[i][j] == 0) return;\n arr[2] = Math.max(i,arr[2]);\n arr[3] = Math.max(j,arr[3]);\n land[i][j] = 0;\n dfs(land,i-1,j);\n dfs(land,i,j+1);\n dfs(land,i+1,j);\n dfs(land,i,j-1);\n }\n}", "solution_c": "class Solution {\npublic:\n vector> nbrs = {{0,1},{1,0},{-1,0},{0,-1}};\n pair dfs(vector> &land, int i, int j, vector> &visited) {\n visited[i][j] = true;\n pair res = make_pair(i, j);\n for(auto &nbr: nbrs) {\n int x = i + nbr[0];\n int y = j + nbr[1];\n if(x < 0 || y < 0 || x >= land.size() || y >= land[0].size() || visited[x][y] || land[x][y] != 1)\n continue;\n pair ans = dfs(land, x, y, visited);\n res.first = max(res.first, ans.first);\n res.second = max(res.second, ans.second);\n }\n return res;\n }\n vector> findFarmland(vector>& land) {\n int m = land.size();\n int n = land[0].size();\n vector> visited(m, vector(n, false));\n vector> ans;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < n; j++) {\n if(!visited[i][j] && land[i][j] == 1) {\n pair p = dfs(land, i, j, visited);\n vector res;\n res.push_back(i);\n res.push_back(j);\n res.push_back(p.first);\n res.push_back(p.second);\n ans.push_back(res);\n cout << 1 << endl;\n }\n }\n }\n return ans;\n }\n};" }, { "title": "Maximum Points You Can Obtain from Cards", "algo_input": "There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.\n\nIn one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\n\nYour score is the sum of the points of the cards you have taken.\n\nGiven the integer array cardPoints and the integer k, return the maximum score you can obtain.\n\n \nExample 1:\n\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\n\n\nExample 2:\n\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\n\n\nExample 3:\n\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\n\n\n \nConstraints:\n\n\n\t1 <= cardPoints.length <= 105\n\t1 <= cardPoints[i] <= 104\n\t1 <= k <= cardPoints.length\n\n", "solution_py": "class Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n total_cards = len(cardPoints)\n total = sum(cardPoints)\n window_size = total_cards - k\n window_total = 0\n\n if total_cards == k:\n return total\n\n for i in range(total_cards - k):\n window_total += cardPoints[i]\n max_diff = total - window_total\n for i in range((total_cards - k), total_cards):\n window_total += cardPoints[i]\n window_total -= cardPoints[i-window_size]\n if total - window_total > max_diff:\n max_diff = total - window_total\n return max_diff", "solution_js": "/**\n * @param {number[]} cardPoints\n * @param {number} k\n * @return {number}\n */\n\n// Obtaining k cards from the beginning or end of the row for the largest sum, meaning leaving the\n// array with n-k adjacent cards with the min sum\n// therefore, this transform the problem to finding the minSum of subarray of length n-k\n// we use slide window to calculate the minSubArraySum\nvar maxScore = function(cardPoints, k) {\n const n = cardPoints.length, d = n-k // d is the window length\n let sum = 0\n for (let i = 0; i < d; i++) {\n sum += cardPoints[i]\n }\n let minWindowSum = sum, totalSum = sum\n console.log(sum)\n for (let i = d; i < n; i++) {\n // the sum of the next window will the the sum of previous window + the next card (the end card of the next window) - the beginning card of the previous window\n sum += cardPoints[i] - cardPoints[i-d]\n minWindowSum = Math.min(minWindowSum, sum)\n totalSum += cardPoints[i]\n }\n // the ans will be the sum of all cards - the sum of min subArray\n return totalSum - minWindowSum\n};", "solution_java": "class Solution {\n public int maxScore(int[] cardPoints, int k) {\n int n = cardPoints.length;\n int[] totalSum = new int[n];\n int sum = 0;\n for(int i=0;i& cardPoints, int k) {\n\n int max_s = 0, left =0, right = 0, n = cardPoints.size();\n\n //getting sum of k right elements\n for(int i = 0; i int:\n\t\tmxr = [max(i) for i in grid]\n\t\tmxc = [0 for _ in range(len(grid[0]))]\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[0])):\n\t\t\t\tmxc[j] = max(grid[i][j],mxc[j])\n\t\tans =0 \n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid)):\n\t\t\t\tans+=(min(mxr[i],mxc[j]) - grid[i][j]) \n\t\treturn ans", "solution_js": "/**\n * @param {number[][]} grid\n * @return {number}\n */\nvar maxIncreaseKeepingSkyline = function(grid) {\n let n = grid.length;\n let sum = 0;\n let cache = [];\n\n for (let i = 0; i < n; i++) {\n const rowMax = Math.max(...grid[i]);\n\n for (let j = 0; j < n; j++) {\n let colMax = cache[j];\n\n if (!colMax) {\n let max = Number.MIN_SAFE_INTEGER;\n for (let c = 0; c < n; c++) {\n max = Math.max(max, grid[c][j]);\n }\n cache[j] = max;\n colMax = max;\n }\n\n sum += Math.min(rowMax, colMax) - grid[i][j];\n }\n }\n\n return sum;\n};", "solution_java": "class Solution {\n public int maxIncreaseKeepingSkyline(int[][] grid) {\n int n = grid.length;\n int[] row = new int[n];\n int[] col = new int[n];\n int ans = 0;\n for(int i=0;i>& grid) {\n int n=grid.size();\n //get max for every Column\n vector maxfromcol(n,INT_MIN);\n for(int j=0;j List[str]:\n ans, inComment = [], False\n new_str = \"\"\n for c in source:\n if not inComment: new_str = \"\"\n i, n = 0, len(c)\n # inComment, we find */\n while i < n:\n if inComment:\n if c[i:i + 2] == '*/' and i + 1 < n:\n i += 2\n inComment = False\n continue\n i += 1\n # not in Comment, we find /* // and common character\n else:\n if c[i:i + 2] == '/*' and i + 1 < n:\n i += 2\n inComment = True\n continue\n if c[i:i + 2] == '//' and i + 1 < n:\n break\n new_str += c[i]\n i += 1\n if new_str and not inComment:\n ans.append(new_str)\n \n\n return ans", "solution_js": "var removeComments = function(source) {\n let result = [];\n let multi_line_comment = false;\n let str = \"\";\n\n source.forEach(line => {\n for(let idx=0; idx < line.length; ++idx) {\n // if /* is not ongoing, check for start of a comment or not\n if(!multi_line_comment) {\n // if comment is //, ignore the rest of the line\n if(line[idx] + line[idx+1] === '//') {\n break;\n }\n // if comment if /*, set multi-line flag and move to next index\n else if(line[idx] + line[idx+1] === '/*') {\n multi_line_comment = true;\n ++idx;\n }\n // if not a comment start, add to string to be added to result\n else {\n str += line[idx];\n }\n }\n // if /* comment is ongoing\n else {\n // if closing comment */ is encountered, set multi-line flag off and move to next index\n if(line[idx] + line[idx+1] === '*/') {\n multi_line_comment = false;\n ++idx;\n }\n }\n }\n // if /* comment is not ongoing and str is not empty, add to result as one code line\n if(str.length && !multi_line_comment) {\n result.push(str);\n str = \"\"; //reset the str\n }\n })\n return result;\n}", "solution_java": "class Solution {\n public List removeComments(String[] source) {\n boolean blockActive = false; //We keep track of whether or not we are within a block comment with the blockActive variable. \n\t\t//It is initally set to false since we haven't read anything until now. \n\n\n List result = new ArrayList();\n StringBuilder builder = new StringBuilder();\n \n //Read every line from the source input. \n \n for(String line: source){\n// Each time we move on to reading a new line, we check if it is a part of a block comment. \n//If it is already part of a block comment, it means we should skip the implicit newline characters as mentioned in the problem description. \n//For example if Line 1 was \"int a /*Block comment Started\" and Line 2 was \"Block comment ends here */ b;\", and Line 3 was \"int c;\" \n//we want our output to be \"int ab\", \"int c\" instead of \"int a\", \"b;\", \"int c;\" \n if(!blockActive){ \n builder = new StringBuilder();\n }\n for(int i=0; i removeComments(vector& source) {\n bool commentStart = false;\n vector res;\n \n bool multiComment = false; // are we having a multi-line comment?\n for (string &eachS : source) {\n if (!multiComment) {\n res.emplace_back();\n }\n for (int i = 0; i < eachS.size(); i++) {\n if (!multiComment && eachS[i] == '/') {\n i++;\n if (eachS[i] == '/') {\n break;\n } else if (eachS[i] == '*') {\n multiComment = true;\n } else {\n res.back() += '/';\n res.back() += eachS[i];\n }\n } else if (multiComment && eachS[i] == '*') {\n if (i + 1 < eachS.size() && eachS[i + 1] == '/') {\n i++;\n multiComment = false;\n }\n } else {\n if (!multiComment) {\n res.back() += eachS[i];\n }\n }\n }\n if (!multiComment && res.back().empty()) {\n res.pop_back();\n } \n }\n return res;\n }\n};" }, { "title": "Parse Lisp Expression", "algo_input": "You are given a string expression representing a Lisp-like expression to return the integer value of.\n\nThe syntax for these expressions is given as follows.\n\n\n\tAn expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.\n\t(An integer could be positive or negative.)\n\tA let expression takes the form \"(let v1 e1 v2 e2 ... vn en expr)\", where let is always the string \"let\", then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1 is assigned the value of the expression e1, the second variable v2 is assigned the value of the expression e2, and so on sequentially; and then the value of this let expression is the value of the expression expr.\n\tAn add expression takes the form \"(add e1 e2)\" where add is always the string \"add\", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.\n\tA mult expression takes the form \"(mult e1 e2)\" where mult is always the string \"mult\", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.\n\tFor this question, we will use a smaller subset of variable names. A variable starts with a lowercase letter, then zero or more lowercase letters or digits. Additionally, for your convenience, the names \"add\", \"let\", and \"mult\" are protected and will never be used as variable names.\n\tFinally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.\n\n\n \nExample 1:\n\nInput: expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput: 14\nExplanation: In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.\n\n\nExample 2:\n\nInput: expression = \"(let x 3 x 2 x)\"\nOutput: 2\nExplanation: Assignment in let statements is processed sequentially.\n\n\nExample 3:\n\nInput: expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput: 5\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.\n\n\n \nConstraints:\n\n\n\t1 <= expression.length <= 2000\n\tThere are no leading or trailing spaces in expression.\n\tAll tokens are separated by a single space in expression.\n\tThe answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\n\tThe expression is guaranteed to be legal and evaluate to an integer.\n\n", "solution_py": "class Solution:\n def evaluate(self, expression: str) -> int:\n loc = {}\n stack = []\n for i, x in enumerate(expression): \n if x == \"(\": stack.append(i)\n elif x == \")\": loc[stack.pop()] = i\n \n def fn(lo, hi, mp): \n \"\"\"Return value of given expression.\"\"\"\n if expression[lo] == \"(\": return fn(lo+1, hi-1, mp)\n i = lo\n vals = []\n while i < hi: \n if expression[i:i+3] in (\"let\", \"add\"): \n op = expression[i:i+3]\n i += 3\n elif expression[i:i+4] == \"mult\": \n op = \"mult\"\n i += 4\n elif expression[i].isalpha(): \n x = \"\"\n while i < hi and expression[i].isalnum(): \n x += expression[i]\n i += 1\n if op in (\"add\", \"mult\"): vals.append(mp[x])\n elif expression[i].isdigit() or expression[i] == \"-\": \n v = \"\"\n while i < hi and (expression[i].isdigit() or expression[i] == \"-\"): \n v += expression[i]\n i += 1\n if op == \"let\": mp[x] = int(v)\n else: vals.append(int(v))\n elif expression[i] == \"(\": \n v = fn(i+1, loc[i], mp.copy())\n i = loc[i] + 1\n if op == \"let\": mp[x] = v\n else: vals.append(v)\n else: i += 1\n if op == \"let\": return int(v)\n elif op == \"add\": return sum(vals)\n else: return reduce(mul, vals)\n \n return fn(0, len(expression), {})", "solution_js": "/**\n * @param {string} expression\n * @return {number}\n */\nvar evaluate = function(expression) {\n return helper(expression);\n};\n\nconst helper = (expr, map = {}) => {\n if (expr[0] !== '(')\n return /[0-9]|-/.test(expr[0]) ? +expr : map[expr];\n\n map = Object.assign({}, map);\n const start = expr[1] === 'm' ? 6 : 5;\n const tokens = parse(expr.slice(start, expr.length - 1));\n\n if (expr.startsWith('(m')) return helper(tokens[0], map) * helper(tokens[1], map);\n if (expr.startsWith('(a')) return helper(tokens[0], map) + helper(tokens[1], map);\n\n for (let i = 0; i < tokens.length - 2; i += 2)\n map[tokens[i]] = helper(tokens[i + 1], map);\n\n return helper(tokens.at(-1), map);\n}\n\nconst parse = expr => {\n const tokens = [];\n let [builder, par] = ['', 0];\n\n for (let ch of expr) {\n if (ch === '(') par++;\n if (ch === ')') par--;\n if (!par && ch === ' ') {\n tokens.push(builder);\n builder = '';\n }\n else builder += ch;\n }\n\n return builder ? [...tokens, builder] : tokens;\n}", "solution_java": "class Solution {\n \n String expression;\n int index;\n HashMap> scope; \n //variable may be assigned many times, we use the peek value \n \n public int evaluate(String expression) {\n this.expression=expression;\n index=0;\n scope=new HashMap<>();\n return evaluate();\n }\n \n private int evaluate(){\n \n if(expression.charAt(index)=='('){\n //this is an expression\n index++; //skip '('\n char begin=expression.charAt(index);\n int ret;\n if(begin=='l'){\n //let\n index += 4; //skip let and a blank space\n ArrayList vars=new ArrayList<>();\n while(true){\n if(!Character.isLowerCase(expression.charAt(index))){\n ret=evaluate();\n break;\n }\n String var=parseVar();\n if(expression.charAt(index)==')'){\n ret=scope.get(var).peek();\n break;\n }\n vars.add(var);\n index++;\n int e=evaluate();\n scope.putIfAbsent(var, new LinkedList<>());\n scope.get(var).push(e); //assign a new value\n index++;\n }\n for (String var : vars) {\n scope.get(var).pop(); // remove all values of this scope\n }\n\n } else if(begin=='a') {\n //add\n index += 4;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1+v2;\n } else {\n //multi\n index += 5;\n int v1 = evaluate();\n index++;\n int v2 = evaluate();\n ret = v1*v2;\n }\n index++; // skip ')'\n return ret;\n } else {\n //this is not a expression, this is an integer or a variable\n if(Character.isLowerCase(expression.charAt(index))){\n\t\t\t\t//this is a variable, the current value is peek value\n String var=parseVar();\n return scope.get(var).peek();\n } else {\n\t\t\t\t//this is an integer\n return parseInt();\n }\n }\n }\n \n //read an integer\n private int parseInt(){\n boolean negative=false;\n if(expression.charAt(index)=='-'){\n negative=true;\n index++;\n }\n int ret=0;\n while(Character.isDigit(expression.charAt(index))){\n ret*=10;\n ret+=expression.charAt(index)-'0';\n index++;\n }\n if(negative) return -ret;\n return ret;\n }\n \n //read a variable\n private String parseVar(){\n StringBuilder sb=new StringBuilder();\n char c=expression.charAt(index);\n while(c!=' ' && c!=')'){\n sb.append(c);\n c=expression.charAt(++index);\n }\n return sb.toString();\n }\n}", "solution_c": "class Context {\n unordered_map _map;\n const Context *_parent{};\n public:\n Context(const Context *parent) : _parent{parent}\n {\n ;\n }\n const Context* Parent() const { return _parent; }\n int GetValue(const string_view &key) const\n {\n auto it = _map.find(key);\n if (it != _map.end()) return it->second;\n if (_parent) return _parent->GetValue(key);\n assert(0);\n return numeric_limits::min();\n }\n void AddValue(const string_view &key, int val) {\n auto [it, isInserted] = _map.emplace(key, val);\n if (!isInserted) it->second = val;\n }\n};\nclass Solution {\n string_view symbol(string_view &expr) {\n string_view ret;\n if (expr.empty() || !isalpha(expr[0])) {\n return ret;\n }\n auto pos = expr.find_first_of(\" )\");\n assert(pos != string_view::npos);\n ret = expr.substr(0, pos);\n expr.remove_prefix(pos);\n return ret;\n }\n int evaluate(string_view &expr, Context *context) {\n assert(!expr.empty());\n if (expr[0] == '(') {\n assert(expr.length() >= 4);\n if (expr.substr(0, 4) == \"(add\") {\n assert(expr.length() > 4);\n expr.remove_prefix(4);\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n int l = evaluate(expr, context);\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n int r = evaluate(expr, context);\n assert(!expr.empty() && expr[0] == ')');\n expr.remove_prefix(1);\n return l + r;\n }\n if (expr.substr(0, 4) == \"(mul\") {\n assert(expr.length() > 5);\n expr.remove_prefix(5);\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n int l = evaluate(expr, context);\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n int r = evaluate(expr, context);\n assert(!expr.empty() && expr[0] == ')');\n expr.remove_prefix(1);\n return l * r;\n }\n if (expr.substr(0, 4) == \"(let\") {\n assert(expr.length() > 4);\n expr.remove_prefix(4);\n Context nc(context);\n while (1) {\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n string_view sym = symbol(expr);\n assert(!expr.empty());\n if (sym.empty() || expr[0] == ')') {\n int ret{};\n if (sym.empty()) {\n ret = evaluate(expr, &nc);\n } else {\n ret = nc.GetValue(sym);\n }\n assert(!expr.empty() && expr[0] == ')');\n expr.remove_prefix(1);\n return ret;\n }\n assert(!expr.empty() && expr[0] == ' ');\n expr.remove_prefix(1);\n int value = evaluate(expr, &nc);\n nc.AddValue(sym, value);\n }\n assert(0);\n }\n } \n if (isdigit(expr[0]) || expr[0] == '-') {\n auto pos = expr.find_first_not_of(\"-0123456789\");\n auto len = min(expr.length(), pos);\n int num;\n if (auto [ptr, ec] = from_chars(expr.data(), expr.data()+len, num); ec == errc()) {\n expr.remove_prefix(len);\n } else {\n assert(0);\n }\n return num;\n }\n if (isalpha(expr[0])) {\n string_view sym = symbol(expr);\n assert(!expr.empty() && (expr[0] == ' ' || expr[0] == ')'));\n return context->GetValue(sym);\n }\n assert(0);\n return numeric_limits::min();\n }\npublic:\n int evaluate(string expression) {\n string_view expr(expression);\n Context context(nullptr);\n return evaluate(expr, &context);\n }\n};" }, { "title": "Longest Nice Substring", "algo_input": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not.\n\nGiven a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.\n\n \nExample 1:\n\nInput: s = \"YazaAay\"\nOutput: \"aAa\"\nExplanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.\n\n\nExample 2:\n\nInput: s = \"Bb\"\nOutput: \"Bb\"\nExplanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n\n\nExample 3:\n\nInput: s = \"c\"\nOutput: \"\"\nExplanation: There are no nice substrings.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts consists of uppercase and lowercase English letters.\n\n", "solution_py": "class Solution:\n def longestNiceSubstring(self, s: str) -> str:\n def divcon(s):\n\t\t # string with length 1 or less arent considered nice\n if len(s) < 2:\n return \"\"\n \n pivot = []\n # get every character that is not nice\n for i, ch in enumerate(s):\n if ch.isupper() and ch.lower() not in s:\n pivot.append(i)\n if ch.islower() and ch.upper() not in s:\n pivot.append(i)\n\t\t\t# if no such character return the string\n if not pivot:\n return s\n\t\t\t# divide the string in half excluding the char that makes the string not nice\n else:\n mid = (len(pivot)) // 2\n return max(divcon(s[:pivot[mid]]),divcon(s[pivot[mid]+1:]),key=len)\n \n return divcon(s)", "solution_js": "const swapCase = (str) => str.split('').map((c) => c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()).join('');\n\nvar longestNiceSubstring = function(s) {\n let ans = \"\";\n for (let i = 0; i < s.length; i++) {\n for (let ii = i + 1; ii < s.length + 1; ii++) {\n let substring = s.slice(i, ii); // we take a substring\n\n let invertedCaseChars = [...substring].map(swapCase); // we create an array of chars from the substring and invert case of this chars\n \n if (invertedCaseChars.every(char => substring.includes(char))) { // we check that substring includes every case inverted char (see the illustration above)\n ans = substring.length > ans.length ? substring : ans; // we select the longest substring which satisfies our condition\n }\n } \n }\n return ans \n};", "solution_java": "class Solution {\n public String longestNiceSubstring(String s) {\n String result = \"\";\n // take first index, go from 0 to length-1 of the string\n\t\tfor (int i = 0;i 1 && result.length() < temp.length() && checkNice(temp)) result = temp;\n } \n }\n return result;\n }\n \n\t//validate Nice String check\n public boolean checkNice(String temp){\n //add substring to the set\n\t\tSet s = new HashSet<>();\n for (char ch : temp.toCharArray()) s.add(ch);\n \n\t\t// return false If you do not find both lower case and upper case in the sub string\n\t\t//for e.g 'aAa' substring added to set will have both a and A in the substring which is valid\n\t\t// 'azaA' substring will fail for 'z'\n\t\t// 'aaaaaaaa' will return \"\" as result\n\t\t//make sure that the substring contains both lower and upper case\n for (char ch : s)\n if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch))) return false; \n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n \n string longestNiceSubstring(string s) {\n int arr1[26]={};\n int arr2[26]={};\n if(s.length()<2)\n return \"\";\n for(char ch:s)\n {\n if(ch>='A' && ch<='Z')\n arr1[(ch|32)-'a']++;\n else\n arr2[ch-'a']++;\n }\n vector index;\n index.push_back(-1);\n for(int i=0;i=1 && arr2[(s[i]|32)-'a']==0) || (arr1[(s[i]|32)-'a']==0 && arr2[(s[i]|32)-'a']>=1))\n index.push_back(i);\n }\n //index.push_back(2);\n index.push_back(s.length());\n if(index.size()==2)\n return s;\n string minn=\"\";\n for(int i=0;iminn.length()?temp:minn;\n }\n return minn;\n }\n};" }, { "title": "Smallest Index With Equal Value", "algo_input": "Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.\n\nx mod y denotes the remainder when x is divided by y.\n\n \nExample 1:\n\nInput: nums = [0,1,2]\nOutput: 0\nExplanation: \ni=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.\n\n\nExample 2:\n\nInput: nums = [4,3,2,1]\nOutput: 2\nExplanation: \ni=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,5,6,7,8,9,0]\nOutput: -1\nExplanation: No index satisfies i mod 10 == nums[i].\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t0 <= nums[i] <= 9\n\n", "solution_py": "class Solution:\n def smallestEqual(self, nums: List[int]) -> int:\n for idx, n in enumerate(nums):\n if idx%10==n:\n return idx\n return -1 ", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar smallestEqual = function(nums) {\n return nums.findIndex((n, i) => i % 10 === n)\n};", "solution_java": "class Solution {\n public int smallestEqual(int[] nums) {\n int index = 0;\n for (int i = 0 ; i < nums.length; i++) {\n if (index == nums[i]) {\n return i;\n }\n if (++index== 10) {\n index = 0;\n }\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int smallestEqual(vector& nums) {\n int i = 0;\n while (i < nums.size() && i % 10 != nums[i]) i++;\n return i >= nums.size() ? -1 : i;\n }\n};" }, { "title": "The Skyline Problem", "algo_input": "A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.\n\nThe geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:\n\n\n\tlefti is the x coordinate of the left edge of the ith building.\n\trighti is the x coordinate of the right edge of the ith building.\n\theighti is the height of the ith building.\n\n\nYou may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\n\nThe skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.\n\nNote: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]\n\n \nExample 1:\n\nInput: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:\nFigure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n\n\nExample 2:\n\nInput: buildings = [[0,2,3],[2,5,3]]\nOutput: [[0,3],[5,0]]\n\n\n \nConstraints:\n\n\n\t1 <= buildings.length <= 104\n\t0 <= lefti < righti <= 231 - 1\n\t1 <= heighti <= 231 - 1\n\tbuildings is sorted by lefti in non-decreasing order.\n\n", "solution_py": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n d = collections.defaultdict(list)\n \n for i,(start, end, height) in enumerate(buildings):\n d[start].append(height)\n d[end].append(-height)\n \n l = list(d.keys())\n l.sort()\n \n result = []\n \n active = []\n \n for key in l:\n o = d[key]\n o.sort(reverse=True)\n for j in o:\n if j > 0:\n if not result or not active:\n result.append([key, j])\n active.append(j)\n else:\n if j > active[-1]:\n result.append([key, j])\n active.append(j)\n else:\n active.insert(bisect_left(active, j), j)\n else:\n idx = active.index(-j)\n if idx == len(active) - 1:\n active.pop()\n if active:\n result.append([key, active[-1]])\n else:\n result.append([key, 0])\n else:\n active.pop(idx)\n \n return result\n ", "solution_js": "var getSkyline = function(buildings) {\n \n let results = [];\n \n let points = [];\n \n for (let building of buildings) {\n points.push([building[0],building[2]])\n points.push([building[1],-building[2]])\n }\n \n let heights = [];\n \n points.sort((a,b)=>(b[1]-a[1]))\n points.sort((a,b)=>(a[0]-b[0]))\n \n for (let point of points) {\n if(point[1] >0) {\n heights.push(point[1])\n }\n else {\n heights.splice(heights.indexOf(-point[1]),1)\n }\n let curHeight = (heights.length == 0?0:Math.max(...heights))\n \n if(results.length == 0 || results[results.length-1][1] != curHeight) results.push([point[0], curHeight]);\n }\n \n \n return results;\n};", "solution_java": "class height implements Comparable{\n int val = -1;\n int pos = -1;\n boolean isStart = false;\n height(int a, int b, boolean c){\n val = a;\n pos = b;\n isStart = c;\n }\n public int compareTo(height h){\n if(this.pos != h.pos)\n return this.pos-h.pos;\n if(isStart)\n return -1;\n if(h.isStart)\n return 1;\n \n return this.val-h.val;\n }\n}\nclass Solution {\n public List> getSkyline(int[][] buildings) {\n \n PriorityQueue mQ = new PriorityQueue<>();\n int len = buildings.length;\n for(int[] b: buildings) {\n mQ.add(new height(b[2],b[0],true));\n mQ.add(new height(b[2],b[1],false));\n }\n PriorityQueue heap = new PriorityQueue<>(Collections.reverseOrder());\n heap.add(0);\n int prevHeight = 0;\n List> res = new ArrayList<>();\n List lst;\n while(mQ.size()>0) {\n height h = mQ.poll();\n if(h.isStart){\n heap.offer(h.val);\n } else {\n heap.remove(h.val);\n }\n \n if(prevHeight != heap.peek()){\n lst = new ArrayList<>();\n lst.add(h.pos);\n \n if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){\n lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1)));\n res.remove(res.size()-1);\n } else \n lst.add(heap.peek());\n res.add(lst);\n prevHeight = heap.peek();\n }\n }\n return res;\n }\n}", "solution_c": "/*\n1.mark the starting and ending pt of each building\n -> let height of starting pt be negative and ending pt be positive [2,4,10] -> [[2,-10],[4,10]]\n2.mark all consecutive building\n ->store every pair of x and y in pair sort it acc to x\n3.get max y for all x values\n ->use heap-->(multiset) to store all buildings, insert new height of building else erase buiding height\n4.remove pts of same height and store ans in results\n*/\nclass Solution {\npublic:\n vector> getSkyline(vector>& buildings) {\n\t\t//step1\n vector> coordinate;\n for(auto building: buildings){\n coordinate.push_back({building[0],-building[2]});\n coordinate.push_back({building[1],building[2]});\n }\n\t\t//step2\n sort(coordinate.begin(), coordinate.end());\n \n\t\t//step3\n multiset> pq = {0};\n vector> result;\n int prev = 0;\n for(auto p: coordinate){\n if (p.second<0) pq.insert(-p.second);\n else pq.erase(pq.find(p.second));\n int cur=*pq.begin();\n if (prev!=cur) {\n result.push_back({p.first,cur});\n prev=cur;\n }\n }\n return result;\n }\n};" }, { "title": "Non-overlapping Intervals", "algo_input": "Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.\n\n \nExample 1:\n\nInput: intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput: 1\nExplanation: [1,3] can be removed and the rest of the intervals are non-overlapping.\n\n\nExample 2:\n\nInput: intervals = [[1,2],[1,2],[1,2]]\nOutput: 2\nExplanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.\n\n\nExample 3:\n\nInput: intervals = [[1,2],[2,3]]\nOutput: 0\nExplanation: You don't need to remove any of the intervals since they're already non-overlapping.\n\n\n \nConstraints:\n\n\n\t1 <= intervals.length <= 105\n\tintervals[i].length == 2\n\t-5 * 104 <= starti < endi <= 5 * 104\n\n", "solution_py": "class Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: # Time: O(nlogn) and Space: O(1)\n intervals.sort()\n res = 0\n prevEnd = intervals[0][1]\n\n for start, end in intervals[1:]: # we will start from 1 as we already had taken 0 as a base value\n if start >= prevEnd: # Non overlapping when new interval starts after or from the previous one\n prevEnd = end # prev = [2, prevEnd=3] & new = [start=3, end=4], we have a new end now after checking the new non overlapping interval\n else: # Overlapping when new interval starts in between or from the previous one\n res += 1 # prev = [1, prevEnd=2] & new = [start=1, end=3] --> we will delete new=[1, 3] & set prev = [1, prevEnd=2]\n prevEnd = min(end, prevEnd) # we will delete on the interval on the basis of whose interval ends last\n\n return res", "solution_js": "var eraseOverlapIntervals = function(intervals) {\n // sort by end's small to big\n intervals.sort((a, b) => a[1] - b[1]);\n \n let total = 1;\n let maxEnd = intervals[0][1];\n \n for (let i = 1; i < intervals.length; i++) {\n let [start, end] = intervals[i];\n if (start >= maxEnd) {\n total++;\n maxEnd = end\n }\n }\n \n return intervals.length - total;\n};", "solution_java": "// |-------|\n// |--|\n\n// |-------|\n//. |-------|\n\n// |-------|\n//. |-------|\n\nclass Solution {\n public int eraseOverlapIntervals(int[][] intervals) {\n Arrays.sort(intervals, (a,b) -> a[0] - b[0]);\n \n int start = intervals[0][0];\n int end = intervals[0][1];\n int res = 0;\n \n for (int i = 1; i < intervals.length; i++){\n int[] interval = intervals[i];\n \n if(interval[0] >= start && interval[0] < end){\n res++;\n if (interval[1] >= end)\n continue;\n }\n start = interval[0];\n end = interval[1];\n }\n \n return res;\n }\n}", "solution_c": "class Solution {\n void solve(priority_queue , vector>, greater>> &pq,int e,int &cnt){\n\n while(!pq.empty() && pq.top().first>& grid) {\n priority_queue , \n vector>, greater> > pq;\n\n for(int i =0; i List[int]:\n counter = collections.Counter(changed)\n res = []\n for k in counter.keys():\n \n if k == 0:\n # handle zero as special case\n if counter[k] % 2 > 0:\n return []\n res += [0] * (counter[k] // 2)\n \n elif counter[k] > 0:\n x = k\n \n # walk down the chain\n while x % 2 == 0 and x // 2 in counter:\n x = x // 2\n \n # walk up and process all numbers within the chain. mark the counts as 0\n while x in counter:\n if counter[x] > 0:\n res += [x] * counter[x]\n if counter[x+x] < counter[x]:\n return []\n counter[x+x] -= counter[x]\n counter[x] = 0\n x += x\n return res", "solution_js": "// Idea is to sort the input array first then start traversing the array\n// now if we saw half of the current element before and that half is unmatched then\n// match both of them otherwise note the occurence of current element inorder\n// to match it with its double element in the future\n\n// Time -> O(nlogn) due to sorting\n// Space -> O(n) due to map\n\n/**\n * @param {number[]} changed\n * @return {number[]}\n */\nvar findOriginalArray = function(changed) {\n \n const n = changed.length\n if(n%2 === 1) return []\n \n let original = []\n let map = new Map()\n \n changed.sort((a,b) => {\n return a-b\n })\n \n for(let ele of changed) {\n const half = ele/2\n if(map.has(half) && map.get(half) > 0) {\n original.push(half)\n map.set(half, map.get(half)-1)\n } else {\n map.set(ele, map.has(ele) ? map.get(ele)+1: 1)\n }\n }\n \n if(original.length !== n/2) return []\n \n return original\n};", "solution_java": "class Solution {\n public int[] findOriginalArray(int[] changed) {\n\n Arrays.sort(changed);\n\n if(changed.length%2!=0) return new int[0];\n\n int mid = changed.length/2;\n\n int[] res = new int[mid];\n\n int[] freq = new int[100001];\n\n for(int no : changed)\n freq[no]++;\n\n int idx=0;\n\n for(int no: changed){\n if(freq[no] > 0 && no*2 <= 100000 && freq[no*2]>0){\n freq[no]--;\n freq[no*2]--;\n res[idx++] = no;\n }\n }\n\n for(int i=0; i findOriginalArray(vector& changed) {\n unordered_map freq;\n for (auto num : changed) freq[num]++;\n \n sort(changed.begin(), changed.end());\n \n vector res;\n for (auto num : changed) {\n if (freq[num] && freq[num*2]) {\n freq[num]--;\n freq[num*2]--;\n res.push_back(num);\n }\n }\n \n for (auto [a, b] : freq)\n if (b) return {};\n \n return res;\n }\n};" }, { "title": "Minimum Suffix Flips", "algo_input": "You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.\n\nIn one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.\n\nReturn the minimum number of operations needed to make s equal to target.\n\n \nExample 1:\n\nInput: target = \"10111\"\nOutput: 3\nExplanation: Initially, s = \"00000\".\nChoose index i = 2: \"00000\" -> \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.\n\n\nExample 2:\n\nInput: target = \"101\"\nOutput: 3\nExplanation: Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.\n\n\nExample 3:\n\nInput: target = \"00000\"\nOutput: 0\nExplanation: We do not need any operations since the initial s already equals target.\n\n\n \nConstraints:\n\n\n\tn == target.length\n\t1 <= n <= 105\n\ttarget[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\n def minFlips(self, target: str) -> int:\n flip = False\n res = 0\n for c in target:\n if (c == '1') != flip:\n flip = not flip\n res += 1\n \n return res", "solution_js": "var minFlips = function(target) {\n target = \"0\" + target;\n let count = (target.match(/01/g) || []).length * 2;\n return target[target.length -1] ===\"0\" ? count : count - 1;\n};", "solution_java": "class Solution {\n public int minFlips(String target) {\n\n boolean lastBit = false;\n\n int flips = 0;\n for(int i=0;i int:\n if root is None:\n return 0\n if root.left and is_leaf(root.left):\n left = root.left.val\n else:\n left = self.sumOfLeftLeaves(root.left)\n return left + self.sumOfLeftLeaves(root.right)", "solution_js": "var sumOfLeftLeaves = function(root) {\n let total = 0;\n \n const go = (node, isLeft) => {\n if (isLeft && !node.left && !node.right) {\n total += node.val;\n return;\n }\n if (node.left) go(node.left, true);\n if (node.right) go(node.right, false)\n }\n \n go(root, false)\n \n return total;\n};", "solution_java": "class Solution {\n public int sumOfLeftLeaves(TreeNode root) {\n\n if(root==null)\n return 0;\n\n if(root.left!=null && root.left.left==null && root.left.right==null){\n return root.left.val + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }else{\n return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);\n }\n\n }\n}", "solution_c": "class Solution {\n int sum=0;\npublic:\n bool solve(TreeNode* root){\n if(root==NULL) return false;\n if(root->left==NULL && root->right==NULL) return true;\n if(solve(root->left)) sum+=root->left->val;\n solve(root->right);\n return false;\n }\n int sumOfLeftLeaves(TreeNode* root) {\n solve(root);\n return sum;\n }\n};" }, { "title": "Minimum Initial Energy to Finish Tasks", "algo_input": "You are given an array tasks where tasks[i] = [actuali, minimumi]:\n\n\n\tactuali is the actual amount of energy you spend to finish the ith task.\n\tminimumi is the minimum amount of energy you require to begin the ith task.\n\n\nFor example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.\n\nYou can finish the tasks in any order you like.\n\nReturn the minimum initial amount of energy you will need to finish all the tasks.\n\n \nExample 1:\n\nInput: tasks = [[1,2],[2,4],[4,8]]\nOutput: 8\nExplanation:\nStarting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n\nExample 2:\n\nInput: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput: 32\nExplanation:\nStarting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.\n\nExample 3:\n\nInput: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput: 27\nExplanation:\nStarting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.\n\n\n \nConstraints:\n\n\n\t1 <= tasks.length <= 105\n\t1 <= actual​i <= minimumi <= 104\n\n", "solution_py": "class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x: x[0]-x[1])\n def ok(mid):\n for actual, minimum in tasks:\n if minimum > mid or actual > mid: return False\n if minimum <= mid: mid -= actual\n return True\n l, r = 0, 10 ** 9\n while l <= r:\n mid = (l+r) // 2\n if ok(mid): r = mid - 1\n else: l = mid + 1\n return l", "solution_js": "var minimumEffort = function(tasks) {\n let minimumStartingEnergy = 0;\n let currentEnergy = 0;\n \n tasks.sort((a, b) => (b[1] - b[0]) - (a[1] - a[0]) );\n \n for (let task of tasks) {\n if (task[1] > currentEnergy) {\n minimumStartingEnergy += (task[1] - currentEnergy);\n currentEnergy = task[1];\n }\n currentEnergy -= task[0];\n }\n \n return minimumStartingEnergy;\n};", "solution_java": "import java.util.*;\nclass Solution {\n public int minimumEffort(int[][] tasks)\n {\n Arrays.sort(tasks, new Comparator(){\n @Override\n public int compare(int[] a, int[] b)\n {\n return (b[1]-b[0])-(a[1]-a[0]);\n }\n });\n int sum=0, max=0;\n for(int i=0;i>& tasks) {\n int diff=INT_MAX,ans=0;\n for(auto i : tasks){\n diff=min(diff,i[1]-i[0]);\n ans+=i[0];\n }\n int val=0;\n for(auto i : tasks)\n val=max(val,i[1]);\n return max(ans+diff,val);\n }\n};" }, { "title": "Combination Sum III", "algo_input": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true:\n\n\n\tOnly numbers 1 through 9 are used.\n\tEach number is used at most once.\n\n\nReturn a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.\n\n \nExample 1:\n\nInput: k = 3, n = 7\nOutput: [[1,2,4]]\nExplanation:\n1 + 2 + 4 = 7\nThere are no other valid combinations.\n\nExample 2:\n\nInput: k = 3, n = 9\nOutput: [[1,2,6],[1,3,5],[2,3,4]]\nExplanation:\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\n\n\nExample 3:\n\nInput: k = 4, n = 1\nOutput: []\nExplanation: There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.\n\n\n \nConstraints:\n\n\n\t2 <= k <= 9\n\t1 <= n <= 60\n\n", "solution_py": "class Solution:\n \n def solve(self,k,target,ans,temp,idx,nums):\n \n if idx==len(nums):\n if target==0 and k==0:\n ans.append(list(temp))\n return\n \n if nums[idx]<=target:\n \n temp.append(nums[idx])\n self.solve(k-1,target-nums[idx],ans,temp,idx+1,nums)\n temp.pop()\n \n self.solve(k,target,ans,temp,idx+1,nums)\n \n\n \n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n \n ans = []\n temp = []\n idx = 0\n nums = list(range(1,10))\n \n self.solve(k,n,ans,temp,idx,nums)\n return ans\n ", "solution_js": "/**\n * @param {number} k\n * @param {number} n\n * @return {number[][]}\n */\nvar combinationSum3 = function(k, n) {\n const ans = [];\n const st = [];\n\n function dfs(start, t) {\n if (t === 0 && st.length === k) {\n ans.push(Array.from(st));\n return;\n }\n for (let i = start; i <= 9 && st.length < k; i++) {\n if (i > t) break;\n st.push(i);\n dfs(i + 1, t - i);\n st.pop();\n }\n }\n\n dfs(1, n);\n\n return ans;\n};", "solution_java": "//Recursion\n\nclass Solution {\n public List> combinationSum3(int k, int n) {\n List> ans = new ArrayList>();\n //int[] arr = new int{1,2,3,4,5,6,7,8,9};\n List ds = new ArrayList<>();\n helper(1, n, k, ds, ans);\n return ans;\n }\n private static void helper(int i, int tar, int k, List ds, List> ans){\n //base\n if(k == 0) {\n if(tar == 0){\n ans.add(new ArrayList<>(ds));\n }\n return;\n }\n if(tar == 0) return; //bcz if k is not zero and tar is zero then no possible valid combination\n if(i > tar) return;\n if(i > 9) return;\n\n //Take\n if(i <= tar) {\n ds.add(i);\n helper(i+1, tar - i, k-1 , ds, ans);\n ds.remove(ds.size()-1);\n }\n // Not take\n helper(i+1 , tar, k , ds, ans);\n\n return;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> ans;\n //declare temp global vector in this vector we will store temprary combinations\n vector temp;\n void solve(int k,int n,int order){\n //check if our target became zero and combination size became zero then push temp vector inside the ans it means this temp vector combination having sum is equal to target and size of vector is equal to k\n if(n==0 && k==0){\n ans.push_back(temp);\n return;\n }\n //check if our target is less than zero then return \n if(n<0) return;\n // take for loop and check for all posibility ahead of order\n for(int i=order;i<=9;i++){\n //push current index value\n temp.push_back(i);\n // call solve function for further posiblity\n solve(k-1,n-i,i+1);\n //Pop last push value \n temp.pop_back();\n }\n }\n vector> combinationSum3(int k, int n) {\n solve(k,n,1);\n return ans;\n }\n};" }, { "title": "Minimum Value to Get Positive Step by Step Sum", "algo_input": "Given an array of integers nums, you start with an initial positive value startValue.\n\nIn each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).\n\nReturn the minimum positive value of startValue such that the step by step sum is never less than 1.\n\n \nExample 1:\n\nInput: nums = [-3,2,-3,4,2]\nOutput: 5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2\n\n\nExample 2:\n\nInput: nums = [1,2]\nOutput: 1\nExplanation: Minimum start value should be positive. \n\n\nExample 3:\n\nInput: nums = [1,-2,-3]\nOutput: 5\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 100\n\t-100 <= nums[i] <= 100\n\n", "solution_py": "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n return max(1, 1 - min(accumulate(nums)))", "solution_js": "var minStartValue = function(nums) {\n var min = 1;\n var sum = 0;\n\t\n for(var i=0;i sum) {\n lowest_sum = sum;\n }\n }\n return 1-lowest_sum;\n }\n}", "solution_c": "class Solution {\npublic:\n int minStartValue(vector& nums) {\n int result=min(nums[0],0);\n for(int i=1;i int:\n nums.sort()\n dict1={}\n s=0\n res=[]\n for n in nums:\n if dict1.get(n,None) is not None:\n res.append(n)\n dict1[n+k]=n\n res=list(set(res))\n return len(res)", "solution_js": "var findPairs = function(nums, k) {\n\tnums.sort((a, b) => b - a);\n\tconst { length } = nums;\n\tconst hash = new Set();\n\tlet left = 0;\n\tlet right = 1;\n\n\twhile (left < length - 1) {\n\t\twhile (right < length) {\n\t\t\tconst diff = nums[left] - nums[right];\n\n\t\t\tdiff === k && hash.add(`${nums[left]},${nums[right]}`);\n\t\t\tdiff > k\n\t\t\t\t? right = length\n\t\t\t\t: right += 1;\n\t\t}\n\t\tleft += 1;\n\t\tright = left + 1;\n\t}\n\treturn hash.size;\n};", "solution_java": " // O(n) Time Solution\n\n class Solution {\n \t\tpublic int findPairs(int[] nums, int k) {\n \t\t\tMap map = new HashMap();\n \t\t\tfor (int num : nums)\n \t\t\t\tmap.put(num, map.getOrDefault(num, 0) + 1);\n\n \t\t\tint result = 0;\n \t\t\tfor (int i : map.keySet())\n \t\t\t\tif (k > 0 && map.containsKey(i + k) || k == 0 && map.get(i) > 1)\n \t\t\t\t\tresult++;\n \t\t\treturn result;\n \t\t}\n \t}", "solution_c": "class Solution {\npublic:\n int findPairs(vector& nums, int k) {\n unordered_map a;\n for(int i:nums)\n a[i]++;\n int ans=0;\n for(auto x:a)\n {\n if(k==0)\n { \n if(x.second>1)\n ans++;\n }\n else if(a.find(x.first+k)!=a.end())\n ans++;\n }\n \n return ans;\n }\n};" }, { "title": "Binary Tree Preorder Traversal", "algo_input": "Given the root of a binary tree, return the preorder traversal of its nodes' values.\n\n \nExample 1:\n\nInput: root = [1,null,2,3]\nOutput: [1,2,3]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [1]\nOutput: [1]\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\n \nFollow up: Recursive solution is trivial, could you do it iteratively?\n", "solution_py": "from collections import deque\nfrom typing import List, Optional\n\nclass Solution:\n \"\"\"\n Time: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n if root is None:\n return []\n\n queue = deque([root])\n preorder = []\n\n while queue:\n node = queue.pop()\n preorder.append(node.val)\n\n if node.right is not None:\n queue.append(node.right)\n if node.left is not None:\n queue.append(node.left)\n\n return preorder\n\nclass Solution:\n \"\"\"\n Time: O(n)\n \"\"\"\n\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n return list(self.preorder_generator(root))\n\n @classmethod\n def preorder_generator(cls, tree: Optional[TreeNode]):\n if tree is not None:\n yield tree.val\n yield from cls.preorder_generator(tree.left)\n yield from cls.preorder_generator(tree.right)", "solution_js": "var preorderTraversal = function(root) {\n let res = []\n \n const check = node => {\n if(node === null) return\n else res.push(node.val)\n \n if(node.left !== null) check(node.left)\n if(node.right !== null) check(node.right)\n }\n \n check(root)\n \n return res\n};", "solution_java": "class Solution {\n public List preorderTraversal(TreeNode root) {\n List result = new ArrayList<>();\n preorderTraversal2(root, result);\n return result;\n }\n\n\n public List preorderTraversal2(TreeNode root,List result) {\n if(root!=null){\n result.add(root.val);\n if(root.left!=null){\n preorderTraversal2(root.left,result);\n }\n if(root.right!=null){\n preorderTraversal2(root.right,result);\n }\n }\n return result;\n }\n}", "solution_c": "class Solution {\n void solve(TreeNode *root, vector &ans){\n if(root == NULL) return;\n ans.push_back(root->val);\n solve(root->left, ans);\n solve(root->right, ans);\n }\npublic:\n vector preorderTraversal(TreeNode* root) {\n vector ans;\n solve(root, ans);\n return ans;\n }\n};" }, { "title": "Process Restricted Friend Requests", "algo_input": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.\n\nYou are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.\n\nInitially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.\n\nA friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.\n\nReturn a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.\n\nNote: If uj and vj are already direct friends, the request is still successful.\n\n \nExample 1:\n\nInput: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).\n\n\nExample 2:\n\nInput: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).\n\n\nExample 3:\n\nInput: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput: [true,false,true,false]\nExplanation:\nRequest 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).\n\n\n \nConstraints:\n\n\n\t2 <= n <= 1000\n\t0 <= restrictions.length <= 1000\n\trestrictions[i].length == 2\n\t0 <= xi, yi <= n - 1\n\txi != yi\n\t1 <= requests.length <= 1000\n\trequests[j].length == 2\n\t0 <= uj, vj <= n - 1\n\tuj != vj\n\n", "solution_py": "class UnionFindSet(object):\n def __init__(self, n):\n self.data = range(n)\n\n def find(self, x):\n while x <> self.data[x]:\n x = self.data[x]\n return x\n\n def union(self, x, y):\n self.data[self.find(x)] = self.find(y)\n\n def speedup(self):\n for i in range(len(self.data)):\n self.data[i] = self.find(i)\n\n\nclass Solution(object):\n def friendRequests(self, n, restrictions, requests):\n uf = UnionFindSet(n)\n ret = [True] * len(requests)\n for k, [x, y] in enumerate(requests): # Process Requests Sequentially\n xh = uf.find(x) # backup the head of x for undo\n uf.union(x, y) # link [x, y] and verify if any restriction triggers\n for [i, j] in restrictions:\n if uf.find(i) == uf.find(j):\n ret[k] = False\n break\n if not ret[k]: # if any restriction triggers, undo\n uf.data[xh] = xh\n else:\n uf.speedup()\n return ret", "solution_js": "/*\nDSU Class Template\n*/\nclass DSU {\n constructor() {\n this.parents = new Map();\n this.rank = new Map();\n }\n\n add(x) {\n this.parents.set(x, x);\n this.rank.set(x, 0);\n }\n\n find(x) {\n const parent = this.parents.get(x);\n if (parent === x) return x;\n const setParent = this.find(parent);\n this.parents.set(x, setParent);\n return setParent;\n }\n\n union(x, y) {\n const xParent = this.find(x), yParent = this.find(y);\n const xRank = this.rank.get(xParent), yRank = this.rank.get(yParent);\n if (xParent === yParent) return;\n if (xRank > yRank) {\n this.parents.set(yParent, xParent);\n } else if (yRank > xRank) {\n this.parents.set(xParent, yParent);\n } else {\n this.parents.set(xParent, yParent);\n this.rank.set(yParent, yRank + 1);\n }\n }\n}\n\n/*\nFriend Requests\n*/\nvar friendRequests = function(n, restrictions, requests) {\n const dsu = new DSU(), result = [];\n for (let i = 0; i < n; i++) dsu.add(i);\n\n for (let [friend1, friend2] of requests) {\n const parent1 = dsu.find(friend1), parent2 = dsu.find(friend2);\n let friendshipPossible = true;\n for (let [enemy1, enemy2] of restrictions) {\n const enemyParent1 = dsu.find(enemy1), enemyParent2 = dsu.find(enemy2);\n const condition1 = (enemyParent1 === parent1 && enemyParent2 === parent2);\n const condition2 = (enemyParent1 === parent2 && enemyParent2 === parent1);\n if (condition1 || condition2) {\n friendshipPossible = false;\n break;\n }\n }\n if (friendshipPossible) dsu.union(friend1, friend2);\n result.push(friendshipPossible);\n }\n return result;\n};", "solution_java": "class Solution {\n int[] parent;\n boolean[] result;\n \n public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) {\n parent = new int[n];\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n result = new boolean[requests.length];\n \n for (int i = 0; i < requests.length; i++) {\n // personA and personB can become friends if for all restrictions\n // person x_i and person y_i are not in the same set as personA and personB\n // and vice versa\n int personA = requests[i][0];\n int personB = requests[i][1];\n int personASetRepresentative = find(personA);\n int personBSetRepresentative = find(personB);\n boolean flag = true;\n for (int[] restriction : restrictions) {\n int blackListPersonARepresentative = find(restriction[0]);\n int blackListPersonBRepresentative = find(restriction[1]);\n if (personASetRepresentative == blackListPersonARepresentative && personBSetRepresentative == blackListPersonBRepresentative) {\n flag = false;\n }\n if (personASetRepresentative == blackListPersonBRepresentative && personBSetRepresentative == blackListPersonARepresentative) {\n flag = false;\n }\n }\n if (flag) {\n union(personA, personB);\n }\n result[i] = flag;\n }\n return result;\n }\n \n private int find(int node) {\n int root = node;\n while (parent[root] != root) {\n root = parent[root];\n }\n \n //path compression\n int curr = node;\n while (parent[curr] != root) {\n int next = parent[curr];\n parent[curr] = root;\n curr = next;\n }\n return root;\n }\n \n private boolean union(int node1, int node2) {\n int root1 = find(node1);\n int root2 = find(node2);\n if (root1 == root2) {\n return false;\n }\n parent[root2] = root1;\n return true;\n }\n}", "solution_c": "/ Standard DSU Class\nclass DSU {\n vector parent, size;\npublic:\n\n DSU(int n) {\n for(int i=0; i<=n; i++) {\n parent.push_back(i);\n size.push_back(1);\n }\n }\n\n int findParent(int num) {\n if(parent[num] == num) return num;\n return parent[num] = findParent(parent[num]);\n }\n\n // Directly getting parents of u and v\n // To avoid finding parent multiple times\n void unionBySize(int parU, int parV) {\n\n if(size[parU] < size[parV]) {\n size[parV] += size[parU];\n parent[parU] = parV;\n }\n else {\n size[parU] += size[parV];\n parent[parV] = parU;\n }\n }\n};\n\nclass Solution {\npublic:\n vector friendRequests(int n, vector>& restrictions, vector>& requests) {\n\n DSU dsu(n);\n\n vector successful;\n\n for(auto& request : requests) {\n\n int u = request[0], v = request[1];\n\n int parU = dsu.findParent(u), parV = dsu.findParent(v);\n\n bool flag = true;\n\n if(parU != parV) {\n\n // Check if current friend requested is restricted or not.\n for(auto& restriction : restrictions) {\n int restricted_U = restriction[0], restricted_V = restriction[1];\n\n int restricted_parU = dsu.findParent(restricted_U);\n int restricted_parV = dsu.findParent(restricted_V);\n\n if((parU == restricted_parU && parV == restricted_parV) || (parU == restricted_parV && parV == restricted_parU)) {\n flag = false;\n break;\n }\n }\n\n // Union u and v by passing parents\n // Since it is already calculated above\n if(flag) {\n dsu.unionBySize(parU, parV);\n }\n }\n\n successful.push_back(flag);\n }\n\n return successful;\n }\n};" }, { "title": "Maximum Number of Consecutive Values You Can Make", "algo_input": "You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.\n\nReturn the maximum number of consecutive integer values that you can make with your coins starting from and including 0.\n\nNote that you may have multiple coins of the same value.\n\n \nExample 1:\n\nInput: coins = [1,3]\nOutput: 2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.\n\nExample 2:\n\nInput: coins = [1,1,1,4]\nOutput: 8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.\n\nExample 3:\n\nInput: nums = [1,4,10,3,1]\nOutput: 20\n\n \nConstraints:\n\n\n\tcoins.length == n\n\t1 <= n <= 4 * 104\n\t1 <= coins[i] <= 4 * 104\n\n", "solution_py": "class Solution:\n def getMaximumConsecutive(self, coins: List[int]) -> int:\n coins.sort()\n \n res = 1\n \n for coin in coins:\n if (res >= coin):\n res += coin\n \n return res", "solution_js": "// we iterate from the smallest number while maintaining an integer sum. sum means that we can produce all number from 0 to sum.\n// when we can make numbers from 0 to sum, and we encounter a new number, lets say arr[2].\n// it is obvious that we can create all numbers from sum to sum + arr[2].\n// if there is a gap if(arr[i] > sum+1) it means no combinations could create that number and we stop.\nvar getMaximumConsecutive = function(coins) {\n coins.sort((a,b) => a-b);\n let sum = 1;\n for(let i = 0; i < coins.length; i++) {\n if(coins[i] <= sum) {\n sum += coins[i];\n } else {\n break;\n }\n }\n return sum;\n};", "solution_java": "class Solution {\n public int getMaximumConsecutive(int[] coins) {\n if(coins.length==0 && coins==null)\n return 0;\n TreeMap map=new TreeMap();\n for(int i:coins)\n map.put(i,map.getOrDefault(i,0)+1);\n int range=0;\n for(int i:map.keySet()){\n if(range==0 && i==1)\n range=i*map.get(i);\n else if(range!=0 && range+1>=i)\n range+=i*map.get(i);\n else \n break;\n }\n return range+1;\n }\n}", "solution_c": "class Solution {\npublic:\n int getMaximumConsecutive(vector& coins) {\n sort(coins.begin(), coins.end());\n int n = coins.size();\n int ans = 1;\n for(int i = 0; i < n; i++) {\n if(coins[i] > ans) return ans;\n ans += coins[i]; \n }\n return ans;\n }\n};" }, { "title": "Ways to Split Array Into Three Subarrays", "algo_input": "A split of an integer array is good if:\n\n\n\tThe array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.\n\tThe sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.\n\n\nGiven nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: nums = [1,1,1]\nOutput: 1\nExplanation: The only good way to split nums is [1] [1] [1].\n\nExample 2:\n\nInput: nums = [1,2,2,2,5,0]\nOutput: 3\nExplanation: There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]\n\n\nExample 3:\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: There is no good way to split nums.\n\n \nConstraints:\n\n\n\t3 <= nums.length <= 105\n\t0 <= nums[i] <= 104\n", "solution_py": "class Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007", "solution_js": "var waysToSplit = function(nums) {\n const mod = 1000000007;\n const lastIndex = nums.length - 2;\n const total = nums.reduce((sum, num) => sum + num)\n\n let midLeftPtr = -1;\n let midRightPtr = -1;\n \n let leftSum = 0;\n let midLeftSum = 0;\n let midRightSum = 0;\n \n let numWaysToSplit = 0;\n \n for (let leftPtr = 0; leftPtr < nums.length; leftPtr++) {\n leftSum += nums[leftPtr]; \n midLeftSum -= nums[leftPtr];\n midRightSum -= nums[leftPtr];\n\n // find the first index that satisfies the middle sum\n\t // being greater than or equal to the left sum\n while (midLeftPtr <= lastIndex && \n (midLeftPtr <= leftPtr || midLeftSum < leftSum)) {\n midLeftPtr++;\n midLeftSum += nums[midLeftPtr]\n }\n\n // find the first index that makes the middle sum greater than the right sum\n while (midRightPtr <= lastIndex && \n (midLeftPtr > midRightPtr || midRightSum <= total - midRightSum - leftSum)) {\n midRightPtr++\n midRightSum += nums[midRightPtr]\n }\n numWaysToSplit = (numWaysToSplit + midRightPtr - midLeftPtr) % mod;\n }\n return numWaysToSplit\n};", "solution_java": "class Solution {\n public int waysToSplit(int[] nums) {\n int size = nums.length;\n for (int i = 1; i < size; ++i) {\n nums[i] += nums[i - 1];\n }\n int res = 0;\n int mod = 1_000_000_007;\n for (int i = 0; i < size - 2; ++i) {\n int left = searchLeft(nums, i, size - 1);\n int right = searchRight(nums, i, size - 1);\n if (left == -1 || right == -1) {\n continue;\n }\n res = (res + right - left + 1) % mod;\n }\n return res;\n }\n \n private int searchLeft(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n hi = mi - 1;\n }\n }\n return pos;\n }\n \n private int searchRight(int[] nums, int left, int right) {\n int pos = -1;\n int min = nums[left];\n int lo = left + 1, hi = right - 1;\n while (lo <= hi) {\n int mi = lo + (hi - lo) / 2;\n int mid = nums[mi] - min;\n int max = nums[right] - nums[mi];\n if (mid < min) {\n lo = mi + 1;\n } else if (max < mid){\n hi = mi - 1;\n } else {\n pos = mi;\n lo = mi + 1;\n }\n }\n return pos;\n }\n \n}", "solution_c": "class Solution {\npublic:\n int waysToSplit(vector& nums) {\n int n = nums.size(), mod = 1e9 + 7; long long ans = 0;\n vector prefix(n);\n partial_sum(nums.begin(), nums.end(),prefix.begin());\n for (int i = 0; i < n - 2; i++) {\n int left = prefix[i], remain = (prefix[n - 1] - prefix[i]);\n if (remain < left * 2) break;\n int leftPtr = lower_bound(prefix.begin() + i + 1, prefix.end() - 1, left * 2) - prefix.begin();\n int rightPtr = upper_bound(prefix.begin() + i + 1, prefix.end() - 1, left + remain / 2) - prefix.begin() - 1;\n\n if (rightPtr - leftPtr + 1 > 0) ans += rightPtr - leftPtr + 1;\n }\n \n return ans % mod;\n }\n};" }, { "title": "Maximum Points in an Archery Competition", "algo_input": "Alice and Bob are opponents in an archery competition. The competition has set the following rules:\n\n\n\tAlice first shoots numArrows arrows and then Bob shoots numArrows arrows.\n\tThe points are then calculated as follows:\n\t\n\t\tThe target has integer scoring sections ranging from 0 to 11 inclusive.\n\t\tFor each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points.\n\t\tHowever, if ak == bk == 0, then nobody takes k points.\n\t\n\t\n\n\n\n\t\n\tFor example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.\n\t\n\n\nYou are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.\n\nReturn the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.\n\nIf there are multiple ways for Bob to earn the maximum total points, return any one of them.\n\n \nExample 1:\n\nInput: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\nOutput: [0,0,0,0,1,1,0,0,1,2,3,1]\nExplanation: The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.\n\n\nExample 2:\n\nInput: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\nOutput: [0,0,0,0,0,0,0,0,1,1,1,0]\nExplanation: The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.\n\n\n \nConstraints:\n\n\n\t1 <= numArrows <= 105\n\taliceArrows.length == bobArrows.length == 12\n\t0 <= aliceArrows[i], bobArrows[i] <= numArrows\n\tsum(aliceArrows[i]) == numArrows\n\n", "solution_py": "class Solution:\n def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n self.bestScore = 0\n self.bestBobArrows = None\n \n def backtracking(k, remainArrows, score, bobArrows):\n if k == 12:\n if score > self.bestScore:\n self.bestScore = score\n self.bestBobArrows = bobArrows[::]\n return\n \n backtracking(k+1, remainArrows, score, bobArrows) # Bob loses\n \n # Bob wins\n arrowsNeeded = aliceArrows[k] + 1\n if remainArrows >= arrowsNeeded:\n old = bobArrows[k]\n bobArrows[k] = arrowsNeeded # set new\n backtracking(k+1, remainArrows - arrowsNeeded, score + k, bobArrows)\n bobArrows[k] = old # backtrack\n \n backtracking(0, numArrows, 0, [0] * 12)\n\t\t# In case of having remain arrows then it means in all sections Bob always win \n # then we can distribute the remain to any section, here we simple choose first section.\n self.bestBobArrows[0] += numArrows - sum(self.bestBobArrows)\n return self.bestBobArrows", "solution_js": "var maximumBobPoints = function(numArrows, aliceArrows) {\n let max = 0, n = aliceArrows.length, res;\n backtrack(numArrows, 0, 0, Array(n).fill(0));\n return res;\n\n function backtrack(arrows, idx, points, bobArrows) {\n if (idx === n || arrows === 0) {\n let origVal = bobArrows[n - 1];\n if (arrows > 0) bobArrows[n - 1] += arrows; // put extra arrows in any slot\n if (points > max) {\n max = points;\n res = [...bobArrows]; \n }\n bobArrows[n - 1] = origVal;\n return;\n }\n\n backtrack(arrows, idx + 1, points, bobArrows); // don't use any arrows\n if (aliceArrows[idx] + 1 <= arrows) { // use aliceArrows[idx] + 1 arrows to gain idx points\n bobArrows[idx] = aliceArrows[idx] + 1;\n backtrack(arrows - (aliceArrows[idx] + 1), idx + 1, points + idx, bobArrows);\n bobArrows[idx] = 0;\n }\n } \n};", "solution_java": " class Solution {\n int bobPoint = 0;\n int[] maxbob = new int[12];\n public int[] maximumBobPoints(int numArrows, int[] aliceArrows) {\n int[] bob = new int[12];\n calculate(aliceArrows, bob, 11, numArrows, 0); //Start with max point that is 11\n return maxbob;\n }\n public void calculate(int[] alice, int[] bob, int index, int remainArr, int point) {\n if(index < 0 || remainArr <= 0) {\n if(remainArr > 0)\n bob[0] += remainArr;\n if(point > bobPoint) { // Update the max points and result output\n bobPoint = point;\n maxbob = bob.clone();\n }\n return;\n }\n //part 1: assign 1 more arrow than alice\n if(remainArr >= alice[index]+1) {\n bob[index] = alice[index] + 1;\n calculate(alice, bob, index-1, remainArr-(alice[index]+1), point + index);\n bob[index] = 0;\n }\n //part 2: assign no arrow and move to next point\n calculate(alice, bob, index-1, remainArr, point);\n bob[index] = 0;\n }\n }", "solution_c": "class Solution {\npublic:\n int maxscore; \n vector ans;\n \n void helper(vector &bob, int i, vector& alice, int remarrows, int score)\n {\n if(i == -1 or remarrows <= 0)\n {\n if(score >= maxscore)\n {\n maxscore = score; \n ans = bob; \n }\n return; \n }\n \n helper(bob, i-1, alice, remarrows, score);\n if(remarrows > alice[i])\n {\n bob[i] = alice[i] + 1;\n remarrows -= (alice[i] + 1);\n score += i; \n helper(bob, i-1, alice, remarrows, score);\n bob[i] = 0;\n } \n }\n \n vector maximumBobPoints(int numArrows, vector& aliceArrows) {\n vector bob(12, 0);\n maxscore = INT_MIN; \n helper(bob, 11, aliceArrows, numArrows, 0);\n \n int arrows_used = 0; \n for(int a : ans)\n arrows_used += a; \n if(arrows_used < numArrows)\n ans[0] += (numArrows - arrows_used);\n return ans; \n }\n};" }, { "title": "Sum of Mutated Array Closest to Target", "algo_input": "Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.\n\nIn case of a tie, return the minimum such integer.\n\nNotice that the answer is not neccesarilly a number from arr.\n\n \nExample 1:\n\nInput: arr = [4,9,3], target = 10\nOutput: 3\nExplanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\n\n\nExample 2:\n\nInput: arr = [2,3,5], target = 10\nOutput: 5\n\n\nExample 3:\n\nInput: arr = [60864,25176,27249,21296,20204], target = 56803\nOutput: 11361\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 104\n\t1 <= arr[i], target <= 105\n\n", "solution_py": "class Solution:\n def findBestValue(self, arr: List[int], t: int) -> int:\n def getsum(x):\n s = 0\n for i in range(n):\n if arr[i] > x:\n s += x*(n-i)\n break\n else:\n s += arr[i]\n return s\n\t\t\t\n\t\tarr.sort()\n n = len(arr)\n l, r = 0, max(arr)\n ans = [inf, inf]\n while l <= r:\n m = l+(r-l)//2\n if abs(getsum(m)-t) <= ans[0]:\n if abs(getsum(m)-t) == ans[0]:\n ans[1] = min(m, ans[1])\n else:\n ans = [abs(getsum(m)-t), m]\n if getsum(m) > t:\n r = m-1\n else:\n l = m+1\n \n return ans[1]", "solution_js": "/**\n * @param {number[]} arr\n * @param {number} target\n * @return {number}\n */\nvar findBestValue = function(arr, target) {\n const sortedArr = [...arr].sort(function (a, b) { return a - b; });\n var lowestValue = Math.min(sortedArr[arr.length-1], Math.floor(target/arr.length));\n var higestValue = Math.min(sortedArr[arr.length-1], target);\n var value, deltaLeft, deltaRight;\n \n while (true) {\n candidateRight = Math.ceil((lowestValue + higestValue)/2)\n candidateLeft = candidateRight - 1\n deltaLeft = calculateDeltaForCandidate(sortedArr, target, candidateLeft)\n if (deltaLeft == 0) {\n return candidateLeft\n }\n deltaRight = calculateDeltaForCandidate(sortedArr, target, candidateRight)\n if (deltaRight == 0) {\n return candidateRight\n }\n if (deltaRight == 0) {\n return candidateRight\n }\n if (candidateRight == higestValue) {\n return deltaLeft <= deltaRight ? candidateLeft : candidateRight;\n }\n if (deltaLeft <= deltaRight) {\n higestValue = candidateLeft\n } else {\n lowestValue = candidateRight\n }\n }\n};\n\nvar calculateDeltaForCandidate = function(sArr, target, candidate) {\n var sum\n //find idx lover then candidate\n for (var i=0; i < sArr.length; i++) {\n if (sArr[i] >= candidate) {\n sum = sArr.slice(0, i).reduce((partialSum, a) => partialSum + a, 0) + (sArr.length - i) * candidate;\n return Math.abs(sum - target)\n };\n }\n return NaN\n};", "solution_java": "class Solution {\n int max = 0;\n int len;\n public int findBestValue(int[] arr, int target) {\n this.len = arr.length;\n\n for (int i = 0; i < len; i++)\n max = Math.max(max, arr[i]);\n\n int l = 0;\n int r = max;\n while(l < r){\n int mid = l + (r-l) / 2;\n\n if(check(arr, mid, target) <= check(arr, mid+1, target))\n r = mid;\n else\n l = mid + 1;\n }\n return l;\n }\n\n private int check(int[] arr, int value, int target){\n int sum = 0;\n for(int e : arr){\n if(e > value)\n sum += value;\n else\n sum += e;\n }\n\n return Math.abs(sum-target);\n }\n}", "solution_c": "// This Question Includes Both Binary Search And bit of Greedy Concept also.\n// See We Know Ans Always Lies Between 0 and maximum element according to given question condition Because\n// sum value at maximum element is same as any other element greater than it.\n// So we get our sum from getval function after that you need to choose as to move forward(l = mid+1) or backward\n// i.e.(h = mid-1) so if sum value we obtain is less than target then l = mid+1 why so??\n// Because 2 3 5 lets suppose you are having this array if we pick 2 as mid then sum value will be 6 whereas if we pick 3 then sum value will be 8 and 10 when we pick 5 so notice that sum will increase when we increase value and\n// correspondingly decrease when we decrease value...So yess This is all what we did and got Accepted.\nclass Solution {\npublic:\n int getval(int mid , vector&arr)\n {\n int sum = 0;\n for(int i = 0 ; i < arr.size() ; i++)\n {\n if(arr[i] > mid)\n sum+=mid;\n else\n sum+=arr[i];\n }\n return sum;\n }\n int findBestValue(vector& arr, int target) {\n int n = arr.size();\n int l = 0 , h = *max_element(arr.begin(),arr.end());\n int ans = 0, min1 = INT_MAX;\n while(l<=h)\n {\n int mid = l + (h-l)/2;\n int k = getval(mid,arr);\n if(k==target)\n {\n return mid;\n }\n else if(k bool:\n\t\treturn all(v < 4 for v in ((Counter(w1) - Counter(w2)) + (Counter(w2) - Counter(w1))).values())", "solution_js": "var checkAlmostEquivalent = function(word1, word2) {\n const hm = new Map()\n const addToHm = (ch, add) => {\n if (hm.has(ch)) \n hm.set(ch, hm.get(ch) + (add ? +1 : -1))\n else \n hm.set(ch, (add ? +1 : -1)) \n }\n \n for (let i = 0; i < word1.length; i++) {\n addToHm(word1[i], true) \n addToHm(word2[i], false) \n }\n \n for (const val of hm.values())\n if (Math.abs(val) > 3)\n\t\t\treturn false\n \n return true\n};", "solution_java": "class Solution { \n public boolean checkAlmostEquivalent(String word1, String word2) {\n Map map = new HashMap();\n for (int i = 0; i < word1.length(); i++) {\n map.put(word1.charAt(i), map.getOrDefault(word1.charAt(i), 0) + 1);\n map.put(word2.charAt(i), map.getOrDefault(word2.charAt(i), 0) - 1);\n }\n for (int i : map.values()) { //get value set\n if (i > 3 || i < -3) { \n return false;\n }\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool checkAlmostEquivalent(string word1, string word2) {\n\t\tunordered_map m;\n\t\tfor(int i = 0; i < word1.size(); i++){\n\t\t\tm[word1[i]]++;\n\t\t}\n\t\tfor(int i = 0; i < word2.size(); i++){\n\t\t\tm[word2[i]]--;\n\t\t}\n\t\tfor(auto i : m){\n\t\t\tif(abs(i.second) > 3){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};" }, { "title": "Minimum Window Substring", "algo_input": "Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\".\n\nThe testcases will be generated such that the answer is unique.\n\nA substring is a contiguous sequence of characters within the string.\n\n \nExample 1:\n\nInput: s = \"ADOBECODEBANC\", t = \"ABC\"\nOutput: \"BANC\"\nExplanation: The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.\n\n\nExample 2:\n\nInput: s = \"a\", t = \"a\"\nOutput: \"a\"\nExplanation: The entire string s is the minimum window.\n\n\nExample 3:\n\nInput: s = \"a\", t = \"aa\"\nOutput: \"\"\nExplanation: Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.\n\n\n \nConstraints:\n\n\n\tm == s.length\n\tn == t.length\n\t1 <= m, n <= 105\n\ts and t consist of uppercase and lowercase English letters.\n\n\n \nFollow up: Could you find an algorithm that runs in O(m + n) time?", "solution_py": "# Added on 2022-08-18 15:51:55.963915\n\nvar minWindow = function(s, t) {\n const tf = {}, sf = {};\n for(let c of t) {\n tf[c] = (tf[c] || 0) + 1;\n }\n let l = 0, r = 0, rs = t.length;\n let ml = -1, mr = -1;\n for(; r < s.length; r++) {\n const c = s[r];\n\n if(!tf[c]) continue;\n\n const sc = sf[c] || 0;\n sf[c] = sc + 1;\n if(sf[c] <= tf[c]) {\n rs--;\n }\n\n if(rs == 0) {\n while(true) {\n if(mr == -1 || mr - ml > r - l) {\n [mr, ml] = [r, l];\n }\n\n const c = s[l];\n if(!tf[c]) {\n l++;\n }\n else if(sf[c] - 1 < tf[c]) {\n sf[c]--, l++, rs++;\n break;\n } else {\n sf[c]--;\n l++;\n }\n }\n }\n }\n if(mr == -1) return '';\n return s.slice(ml, mr + 1);\n};", "solution_js": "var minWindow = function(s, t) {\n const tf = {}, sf = {};\n for(let c of t) {\n tf[c] = (tf[c] || 0) + 1;\n }\n let l = 0, r = 0, rs = t.length;\n let ml = -1, mr = -1;\n for(; r < s.length; r++) {\n const c = s[r];\n\n if(!tf[c]) continue;\n\n const sc = sf[c] || 0;\n sf[c] = sc + 1;\n if(sf[c] <= tf[c]) {\n rs--;\n }\n\n if(rs == 0) {\n while(true) {\n if(mr == -1 || mr - ml > r - l) {\n [mr, ml] = [r, l];\n }\n\n const c = s[l];\n if(!tf[c]) {\n l++;\n }\n else if(sf[c] - 1 < tf[c]) {\n sf[c]--, l++, rs++;\n break;\n } else {\n sf[c]--;\n l++;\n }\n }\n }\n }\n if(mr == -1) return '';\n return s.slice(ml, mr + 1);\n};", "solution_java": "class Solution {\n public String minWindow(String s, String t) {\n HashMap child = new HashMap<>();\n HashMap parent = new HashMap<>();\n\n int left = -1, right = -1, match = 0;\n String window = \"\";\n\n for(int i = 0; i < t.length(); i++){\n char c = t.charAt(i);\n child.put(c, child.getOrDefault(c, 0) + 1); //Child frequency map\n }\n\n while(true){\n boolean f1 = false, f2 = false;\n\n while(right < s.length() - 1 && match < t.length()){\n right++;\n char c = s.charAt(right);\n parent.put(c, parent.getOrDefault(c, 0) + 1); // Acquiring characters till\n if(parent.getOrDefault(c, 0) <= child.getOrDefault(c, 0)) // match count is equal\n match++;\n\n f1 = true;\n }\n while(left < right && match == t.length()){\n String potstring = s.substring(left + 1, right + 1);\n if(window.length() == 0 || window.length() > potstring.length())\n window = potstring; //Calculating length of window\n\n left++;\n char c = s.charAt(left);\n parent.put(c, parent.getOrDefault(c, 0) - 1);\n if(parent.get(c) == 0) //Releasing characters by\n parent.remove(c); //left pointer for finding smallest window\n\n if(parent.getOrDefault(c, 0) < child.getOrDefault(c, 0))\n match--;\n\n f2 = true;\n }\n\n if(f1 == false && f2 == false)\n break;\n }\n\n return window;\n }\n}", "solution_c": "class Solution {\npublic:\n string minWindow(string s, string t) {\n unordered_map ump;\n for(auto i:t){\n ump[i]++;\n }\n\n int i =0,j =0,count =0;\n int ans =INT_MAX,answer =0;\n for (;j < s.size();j++)\n {\n if(ump[s[j]]>0) {\n count++;\n }\n ump[s[j]]--;\n if(count==t.size()){\n\n while (i < j && ump[s[i]]<0)\n {\n ump[s[i]]++;\n i++;\n }\n if(ans > j-i+1){\n ans = j-i+1;\n answer = i;\n }\n ump[s[i]]++;\n i++;\n count--;\n }\n }\n return ans==INT_MAX?\"\":s.substr(answer,ans);\n }\n};" }, { "title": "Incremental Memory Leak", "algo_input": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.\n\nAt the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.\n\nReturn an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.\n\n \nExample 1:\n\nInput: memory1 = 2, memory2 = 2\nOutput: [3,1,0]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n\n\nExample 2:\n\nInput: memory1 = 8, memory2 = 11\nOutput: [6,0,4]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n\n\n \nConstraints:\n\n\n\t0 <= memory1, memory2 <= 231 - 1\n\n", "solution_py": "class Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n \n inverted = False \n if memory2>memory1:\n memory2, memory1 = memory1, memory2\n inverted = True \n\n\t\t#Compute the number of steps in first stage - 1\n i_start = solve_quadratic(1,2*(memory1-memory2))\n \n memory1-= i_start*(i_start+1)//2\n\t\t\n\t\tif memory1 == memory2: #Special case (if we end up with equal numbers after stage - 1 - undo inversion)\n inverted = False \n \n #Compute number of steps in stage - 2\n n_end = solve_quadratic((i_start+1), memory2)\n \n\t\t#Compute sums of respective arithmetic sequences\n i_end_1 = i_start - 1 + 2*n_end\n i_end_2 = i_start + 2*n_end\n \n sum1 = n_end * (i_start+1 + i_end_1)//2\n sum2 = n_end * (i_start+2 + i_end_2)//2\n \n\t\t#Compute updated memories \n memory1-=sum1\n memory2-=sum2\n \n full_cnt=2*n_end+i_start\n \n if memory1>=i_end_2+1: #If we can still make one removal from the first stick - perform it.\n memory1-=(i_end_2+1)\n full_cnt+=1\n \n return [full_cnt+1, memory2, memory1] if inverted else [full_cnt+1, memory1, memory2]\n \n\t\t ```", "solution_js": "var memLeak = function(memory1, memory2) {\n var count=1;\n while(true)\n {\n if(memory1>=memory2 && memory1>=count)\n memory1-=count;\n else if(memory2>=memory1 && memory2>=count)\n memory2-=count\n else\n return [count, memory1, memory2];\n count++;\n }\n};", "solution_java": "class Solution {\n public int[] memLeak(int memory1, int memory2) {\n int i = 1;\n while(Math.max(memory1, memory2) >= i){\n if(memory1 >= memory2)\n memory1 -= i;\n else\n memory2 -= i;\n i++;\n }\n return new int[]{i, memory1, memory2};\n }\n}", "solution_c": "class Solution {\npublic:\n vector memLeak(int memory1, int memory2) {\n int time = 1;\n while (max(memory1, memory2) >= time) {\n if (memory1 >= memory2) {\n memory1 -= time;\n } else {\n memory2 -= time;\n }\n ++time;\n }\n return {time, memory1, memory2};\n }\n};" }, { "title": "Sliding Puzzle", "algo_input": "On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\n\nThe state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\n\nGiven the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n\n \nExample 1:\n\nInput: board = [[1,2,3],[4,0,5]]\nOutput: 1\nExplanation: Swap the 0 and the 5 in one move.\n\n\nExample 2:\n\nInput: board = [[1,2,3],[5,4,0]]\nOutput: -1\nExplanation: No number of moves will make the board solved.\n\n\nExample 3:\n\nInput: board = [[4,1,2],[5,0,3]]\nOutput: 5\nExplanation: 5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\n\n\n \nConstraints:\n\n\n\tboard.length == 2\n\tboard[i].length == 3\n\t0 <= board[i][j] <= 5\n\tEach value board[i][j] is unique.\n\n", "solution_py": "class Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n def findNei(board):\n directs = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n boards = []\n for i in range(2):\n for j in range(3):\n if board[i][j] == 0:\n for dr, dc in directs:\n tmp = [row.copy() for row in board]\n r, c = i + dr, j + dc\n if r in range(2) and c in range(3):\n tmp[r][c], tmp[i][j] = tmp[i][j], tmp[r][c]\n boards.append(tmp)\n return boards\n\n visited = set()\n target = [[1, 2, 3], [4, 5, 0]]\n if board == target:\n return 0\n rows, cols = len(board), len(board[0])\n q = collections.deque()\n step = 1\n\n for row in range(rows):\n for col in range(cols):\n if board[row][col] == 0:\n boards = findNei(board)\n for b in boards:\n if b == target:\n return step\n visited.add(tuple([tuple(row) for row in b]))\n q.append(b)\n break\n\n while q:\n step += 1\n for _ in range(len(q)):\n b = q.popleft()\n boards = findNei(b)\n for b in boards:\n if b == target:\n return step\n t = tuple([tuple(row) for row in b])\n if t not in visited:\n visited.add(t)\n q.append(b)\n\n return -1", "solution_js": "/**\n * @param {number[][]} board\n * @return {number}\n */\n\nclass BoardState {\n constructor(board, currStep) {\n this.board = this.copyBoard(board);\n this.boardString = this.flatToString(board);\n this.emptyIndex = this.findIndexOf0(board);\n this.currStep = currStep;\n }\n findIndexOf0(board) {\n for(let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n if(board[i][j] === 0) return [i, j];\n }\n }\n return null;\n }\n copyBoard(board) {\n const newBoard = [];\n board.forEach((row) => {\n newBoard.push([...row]);\n });\n return newBoard;\n }\n flatToString(board) {\n let str = '';\n for(let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n str += board[i][j];\n }\n }\n return str;\n }\n}\nvar slidingPuzzle = function(board) {\n let queue = [new BoardState(board, 0)];\n let set = new Set();\n const x = board.length, y = board[0].length;\n const switchMoves = [[1, 0], [0, 1], [-1, 0], [0, -1]];\n let slide = (i, j, newi, newj, currBoardState) => {\n if (newi < 0 || newj < 0 || newi >= x || newj >= y) {\n return null;\n }\n const newBoard = currBoardState.copyBoard(currBoardState.board);\n const temp = newBoard[i][j];\n newBoard[i][j] = newBoard[newi][newj];\n newBoard[newi][newj] = temp;\n const newBoardState = new BoardState(newBoard, currBoardState.currStep + 1);\n return newBoardState\n }\n while(queue.length > 0) {\n const currBoardState = queue.shift();\n set.add(currBoardState.boardString);\n if(currBoardState.boardString === '123450') {\n return currBoardState.currStep;\n }\n const [i, j] = currBoardState.emptyIndex;\n switchMoves.forEach((move) => {\n const newBoardState = slide(i, j, i + move[0], j + move[1], currBoardState);\n if (newBoardState && !set.has(newBoardState.boardString)) {\n queue.push(newBoardState);\n }\n });\n }\n return -1;\n};", "solution_java": "class Solution {\n int [][] dir={{1,3},{0,2,4},{1,5},{0,4},{1,3,5},{2,4}};\n public int slidingPuzzle(int[][] board) {\n\n String tar=\"123450\";\n\n String src=\"\";\n\n for(int i =0;i visited=new HashSet<>();\n\n visited.add(src);\n int level=0;\n ArrayDeque q=new ArrayDeque<>();\n q.add(src);\n while(q.size()!=0){\n int t=q.size();\n\n while(t-->0){\n String rem=q.remove();\n\n if(rem.equals(tar)){\n return level;\n }\n\n int idx=-1;\n\n for(int i=0;i>state;\n };\n\nclass Solution {\npublic:\n\nint slidingPuzzle(vector>& board) {\n\n vector>target={{1,2,3},{4,5,0}};\n queueq;\n int n=2;\n int m=3;\n vector>dir={{1,0},{-1,0},{0,1},{0,-1}};\n\n for(int i=0;i>>set;\n set.insert(q.front().state);\n int ladder=0;\n while(!q.empty()){\n int size=q.size();\n for(int i=0;i=0 && c=0 ){\n swap(curr.state[r][c],curr.state[row][col]) ;\n if(set.find(curr.state)==set.end()){\n set.insert(curr.state);\n q.push({r,c,curr.state});\n }\n swap(curr.state[r][c],curr.state[row][col]) ;\n\n }\n\n }\n\n }\n ladder++;\n\n }\n return -1;\n\n}\n};" }, { "title": "Gray Code", "algo_input": "An n-bit gray code sequence is a sequence of 2n integers where:\n\n\n\tEvery integer is in the inclusive range [0, 2n - 1],\n\tThe first integer is 0,\n\tAn integer appears no more than once in the sequence,\n\tThe binary representation of every pair of adjacent integers differs by exactly one bit, and\n\tThe binary representation of the first and last integers differs by exactly one bit.\n\n\nGiven an integer n, return any valid n-bit gray code sequence.\n\n \nExample 1:\n\nInput: n = 2\nOutput: [0,1,3,2]\nExplanation:\nThe binary representation of [0,1,3,2] is [00,01,11,10].\n- 00 and 01 differ by one bit\n- 01 and 11 differ by one bit\n- 11 and 10 differ by one bit\n- 10 and 00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n- 00 and 10 differ by one bit\n- 10 and 11 differ by one bit\n- 11 and 01 differ by one bit\n- 01 and 00 differ by one bit\n\n\nExample 2:\n\nInput: n = 1\nOutput: [0,1]\n\n\n \nConstraints:\n\n\n\t1 <= n <= 16\n\n", "solution_py": "import math\nclass Solution(object):\n def grayCode(self, n):\n \"\"\"\n :type n: int\n :rtype: List[int]\n \"\"\"\n allowedDiffs = [int(1*math.pow(2,i)) for i in range(0,n)]\n grayCodes = [0]\n for diff in allowedDiffs:\n grayCodes += [code + diff for code in reversed(grayCodes)]\n return grayCodes", "solution_js": "/**\n * @param {number} n\n * @return {number[]}\n */\nvar grayCode = function(n) {\n return binaryToInt(dfs(n, ['0', '1']))\n};\n\nconst dfs = (n, arr) => {\n if (n === 1) return arr\n\n const revArr = [...arr].reverse()\n\n addOneBefore('0', arr)\n addOneBefore('1', revArr)\n\n return dfs(n - 1, [...arr, ...revArr])\n}\n\nconst addOneBefore = (e, arr) => {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = e + arr[i]\n }\n}\n\nconst binaryToInt = (arr) => {\n for (let i = 0; i < arr.length; i++){\n arr[i] = parseInt(arr[i], 2)\n }\n return arr\n}", "solution_java": "class Solution {\n public List grayCode(int n) {\n ArrayList list=new ArrayList();\n for(int i=0;i<(1<>1));\n }\n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n vector grayCode(int n) {\n vector dp = {0,1};\n int cnt = 1;\n for(int i = 2; i < n+1; i++) {\n int mod = pow(2, cnt);\n int index = dp.size()-1;\n while(index >= 0) {\n dp.push_back(dp[index] + mod);\n index--;\n }\n cnt++;\n }\n return dp;\n }\n};" }, { "title": "Broken Calculator", "algo_input": "There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:\n\n\n\tmultiply the number on display by 2, or\n\tsubtract 1 from the number on display.\n\n\nGiven two integers startValue and target, return the minimum number of operations needed to display target on the calculator.\n\n \nExample 1:\n\nInput: startValue = 2, target = 3\nOutput: 2\nExplanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n\n\nExample 2:\n\nInput: startValue = 5, target = 8\nOutput: 2\nExplanation: Use decrement and then double {5 -> 4 -> 8}.\n\n\nExample 3:\n\nInput: startValue = 3, target = 10\nOutput: 3\nExplanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n\n\n \nConstraints:\n\n\n\t1 <= startValue, target <= 109\n\n", "solution_py": "class Solution(object):\n def brokenCalc(self, startValue, target):\n \"\"\"\n :type startValue: int\n :type target: int\n :rtype: int\n \"\"\"\n res = 0\n while target > startValue:\n res += 1\n if target % 2:\n target += 1\n else:\n target //= 2\n return res + startValue - target", "solution_js": "/**\n * @param {number} startValue\n * @param {number} target\n * @return {number}\n */\nvar brokenCalc = function(startValue, target) {\n let steps = 0;\n\n while(target !== startValue){\n\n if(startValue > target){\n return steps + startValue - target;\n }\n if(target %2 === 0){\n target /= 2;\n }else {\n target += 1;\n\n }\n steps++;\n }\n return steps\n};", "solution_java": "class Solution {\n public int brokenCalc(int startValue, int target) {\n if(startValue >= target) return startValue - target;\n if(target % 2 == 0){\n return 1 + brokenCalc(startValue, target / 2);\n }\n return 1 + brokenCalc(startValue, target + 1);\n }\n}", "solution_c": "class Solution {\npublic:\n int brokenCalc(int startValue, int target) {\n int result=0;\n while(target>startValue)\n {\n result++;\n if(target%2==0)\n target=target/2;\n else\n target+=1;\n }\n result=result+(startValue-target);\n return result;\n }\n};" }, { "title": "Maximum Swap", "algo_input": "You are given an integer num. You can swap two digits at most once to get the maximum valued number.\n\nReturn the maximum valued number you can get.\n\n \nExample 1:\n\nInput: num = 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\n\n\nExample 2:\n\nInput: num = 9973\nOutput: 9973\nExplanation: No swap.\n\n\n \nConstraints:\n\n\n\t0 <= num <= 108\n\n", "solution_py": "class Solution:\n def maximumSwap(self, num: int) -> int:\n digits = [int(x) for x in str(num)]\n n = len(digits)\n \n for i in range(n):\n maxx = digits[i]\n indx = i\n \n for j in range(i+1,n):\n if digits[j]>=maxx and digits[j]!=digits[i]:\n maxx = digits[j]\n indx = j\n \n if indx!=i:\n digits[i],digits[indx] = digits[indx],digits[i]\n \n #only one swap allowed\n return \"\".join([str(x) for x in digits])\n \n #already sorted\n return num", "solution_js": "var maximumSwap = function(num) {\n\tconst nums = `${num}`.split('');\n\n\tfor (let index = 0; index < nums.length - 1; index++) {\n\t\tconst current = nums[index];\n\t\tconst diff = nums.slice(index + 1);\n\t\tconst max = Math.max(...diff);\n\n\t\tif (current >= max) continue;\n\t\tconst swapIndex = index + diff.lastIndexOf(`${max}`) + 1;\n\t\t[nums[index], nums[swapIndex]] = [nums[swapIndex], nums[index]];\n\t\tbreak;\n\t}\n\treturn nums.join('');\n};", "solution_java": "class Solution {\n public int maximumSwap(int num) {\n char str[]=String.valueOf(num).toCharArray();\n char arr[]=str.clone();\n Arrays.sort(arr);\n int i=0;\n int j=str.length-1;\n while(i=0 && arr[j]==str[i]){i++;j--;}\n int search=j;\n if(i==str.length) return num;\n j=str.length-1;\n while(arr[search]!=str[j]){j--;}\n\n char c=str[i];\n str[i]=str[j];\n str[j]=c;\n return Integer.parseInt(new String(str));\n }\n}", "solution_c": "class Solution {\npublic:\n int maximumSwap(int num) {\n string st_n=to_string(num);\n int maxNum=-1,maxIdx=-1;\n int leftidx=-1,rightidx=-1;\n for(int i=st_n.size()-1;i>=0;i--)\n {\n if(st_n[i]>maxNum)\n {\n maxNum=st_n[i];\n maxIdx=i;\n continue;\n }\n\n if(st_n[i] Optional[ListNode]:\n if head is None:\n return \n odd, even_start, even = head, head.next, head.next\n while odd is not None and even is not None:\n odd.next = even.next\n if odd.next is not None:\n odd = odd.next\n even.next = odd.next\n even = even.next\n else:\n break\n odd.next = even_start\n return head", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {ListNode}\n */\nvar oddEvenList = function(head) {\n if (!head || !head.next) return head;\n let oddNode = head;\n const evenHead = head.next;\n let evenNode = head.next;\n \n while(evenNode?.next) {\n oddNode.next = evenNode.next;\n oddNode = oddNode.next;\n evenNode.next = oddNode.next;\n evenNode = evenNode.next;\n }\n \n oddNode.next = evenHead;\n \n return head;\n};", "solution_java": "class Solution {\n public ListNode oddEvenList(ListNode head) {\n if(head == null) {\n return head;\n }\n ListNode result = head, evenHalf = new ListNode(0), evenHalfPtr = evenHalf;\n for(; head.next != null; head = head.next) {\n evenHalfPtr = evenHalfPtr.next = head.next;\n head.next = head.next.next;\n evenHalfPtr.next = null;\n if(head.next == null) {\n break;\n }\n }\n head.next = evenHalf.next;\n return result;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode* oddEvenList(ListNode* head) {\n if(head == NULL || head->next == NULL || head->next->next == NULL){\n return head;\n }\n ListNode *first = head;\n ListNode *second = head->next;\n ListNode *last = head;\n int count = 1;\n while(last->next != NULL){\n last = last->next;\n count++;\n }\n\n int n = count/2;\n while(n != 0){\n first->next = second->next;\n last->next = second;\n second->next = NULL;\n first = first->next;\n last = second;\n second = first->next;\n n--;\n }\n return head;\n }\n};" }, { "title": "Richest Customer Wealth", "algo_input": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.\n\nA customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.\n\n \nExample 1:\n\nInput: accounts = [[1,2,3],[3,2,1]]\nOutput: 6\nExplanation:\n1st customer has wealth = 1 + 2 + 3 = 6\n2nd customer has wealth = 3 + 2 + 1 = 6\nBoth customers are considered the richest with a wealth of 6 each, so return 6.\n\n\nExample 2:\n\nInput: accounts = [[1,5],[7,3],[3,5]]\nOutput: 10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.\n\nExample 3:\n\nInput: accounts = [[2,8,7],[7,1,3],[1,9,5]]\nOutput: 17\n\n\n \nConstraints:\n\n\n\tm == accounts.length\n\tn == accounts[i].length\n\t1 <= m, n <= 50\n\t1 <= accounts[i][j] <= 100\n\n", "solution_py": "class Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max(map(sum, accounts))", "solution_js": "var maximumWealth = function(accounts) {\n var res = 0;\n for(var i =0;i>& accounts) {\n int maxWealth = 0;\n for (auto account : accounts) {\n int currentSum = 0;\n for (int x : account) currentSum += x;\n if (currentSum > maxWealth) maxWealth = currentSum;\n }\n return maxWealth;\n }\n};" }, { "title": "Longest Binary Subsequence Less Than or Equal to K", "algo_input": "You are given a binary string s and a positive integer k.\n\nReturn the length of the longest subsequence of s that makes up a binary number less than or equal to k.\n\nNote:\n\n\n\tThe subsequence can contain leading zeroes.\n\tThe empty string is considered to be equal to 0.\n\tA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n\n\n \nExample 1:\n\nInput: s = \"1001010\", k = 5\nOutput: 5\nExplanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.\n\n\nExample 2:\n\nInput: s = \"00101001\", k = 1\nOutput: 6\nExplanation: \"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts[i] is either '0' or '1'.\n\t1 <= k <= 109\n\n", "solution_py": "class Solution:\n def longestSubsequence(self, s: str, k: int) -> int:\n \n end, n = len(s)-1, s.count(\"0\") \n while end >=0 and int(s[end:], 2)<= k:\n end-=1\n return n+ s[end+1:].count(\"1\")\n ", "solution_js": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\n\nvar longestSubsequence = function(s, k) {\n let count = 0;\n let j = s.length - 1; // starting from the last digit\n let i = 0; // binary number position\n let acc = 0;\n\n while(j >= 0){\n let positionNumber = Number(s[j]) * Math.pow(2, i);\n j--;\n i++;\n if(acc + positionNumber > k) continue;\n\n acc += positionNumber;\n count++;\n }\n\n return count;\n};", "solution_java": "class Solution {\n public int longestSubsequence(String s, int k) {\n int numOfZeros = 0;\n int numOfOnes = 0;\n \n for(int i = 0; i < s.length(); i++){\n char ch = s.charAt(i);\n if(ch == '0'){\n numOfZeros++;\n }\n }\n int sum = 0;\n for(int i = s.length() - 1; i >= 0; i--){\n char ch = s.charAt(i);\n if(ch == '1'){\n double val = Math.pow(2, s.length() - i - 1);\n sum += val;\n if(sum <= k){\n numOfOnes++;\n }\n }\n }\n return numOfZeros + numOfOnes;\n }\n}", "solution_c": "class Solution {\npublic:\n int ans = 0;\n int f(int i,int size, int sum, string &s, vector>&dp){\n if(i<0){\n return 0;\n }\n if(dp[i][size] != -1){\n return dp[i][size];\n }\n int no = f(i-1,size,sum,s,dp);\n int yes = 0;\n if((sum-(s[i]-'0')*pow(2,size)) >=0){\n yes = 1+ f(i-1,size+1,(sum-(s[i]-'0')*pow(2,size)),s,dp);\n }\n return dp[i][size]=max(no,yes);\n }\n int longestSubsequence(string s, int k) {\n\n int n = s.size();\n vector>dp(n,vector(n,-1));\n return f(n-1,0,k,s,dp);\n\n }\n};" }, { "title": "Defanging an IP Address", "algo_input": "Given a valid (IPv4) IP address, return a defanged version of that IP address.\n\nA defanged IP address replaces every period \".\" with \"[.]\".\n\n \nExample 1:\nInput: address = \"1.1.1.1\"\nOutput: \"1[.]1[.]1[.]1\"\nExample 2:\nInput: address = \"255.100.50.0\"\nOutput: \"255[.]100[.]50[.]0\"\n\n \nConstraints:\n\n\n\tThe given address is a valid IPv4 address.\n", "solution_py": "class Solution:\n\tdef defangIPaddr(self, address: str) -> str:\n\t\treturn address.replace('.', '[.]')", "solution_js": "var defangIPaddr = function(address) {\n return address.split(\"\").map((x)=>{\n if(x=='.')\n return \"[.]\"\n else return x\n }).join(\"\")\n};", "solution_java": "class Solution {\n public String defangIPaddr(String address) {\n return address.replace(\".\",\"[.]\");\n }\n}", "solution_c": "class Solution {\npublic:\n string defangIPaddr(string address) {\n string res;\n for(int i=0;i bool:\n mid, ans = len(S) // 2, 0\n for i in range(mid):\n if S[i] in vowels: ans += 1\n if S[mid+i] in vowels: ans -=1\n return ans == 0", "solution_js": "var halvesAreAlike = function(s) {\n let isVowel = [\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"];\n let count = 0;\n for (let i = 0; i < s.length / 2; i++) {\n if (isVowel.indexOf(s[i]) !== -1) {\n count++;\n }\n }\n for (let i = s.length / 2; i < s.length; i++) {\n if (isVowel.indexOf(s[i]) !== -1) {\n count--;\n }\n }\n return count === 0;\n};", "solution_java": "class Solution {\n public boolean halvesAreAlike(String s) {\n //add vowels to the set\n Set set = new HashSet<>();\n set.add('a');\n set.add('e');\n set.add('i');\n set.add('o');\n set.add('u');\n set.add('A');\n set.add('E');\n set.add('I');\n set.add('O');\n set.add('U');\n\n //find the mid\n int mid = s.length() / 2;\n int count = 0;\n //increment the count for left half, decrement count for the second half if its a vowel\n for (int i = 0; i < s.length(); i++)\n count += (set.contains(s.charAt(i))) ? ((i < mid) ? 1 : -1) : 0;\n //finally count should be 0 to match left and right half\n return count == 0;\n }\n}", "solution_c": "class Solution {\npublic:\n bool halvesAreAlike(string s) {\n unordered_set set = {'a', 'e', 'i', 'o', 'u','A','I','E','O','U'};\n int i=0,j=s.size()/2,cnt=0;\n while(j List[List[int]]:\n res = []\n self.explore(graph, graph[0], [0], res)\n return res\n \n def explore(self, graph, candidates, step, res):\n if step[-1] == len(graph)-1:\n res.append(list(step))\n else:\n for i in range(len(candidates)):\n step.append(candidates[i])\n self.explore(graph, graph[candidates[i]], step, res)\n step.pop()", "solution_js": "/**\n * @param {number[][]} graph\n * @return {number[][]}\n */\nconst allPathsSourceTarget = function(graph) {\n const n = graph.length;\n const result = [];\n const dfs = (node, path) => {\n if (node === n-1) {\n result.push([...path, node]); // Add the current path to the result if we have reached the target node\n return;\n }\n for (const neighbor of graph[node]) {\n dfs(neighbor, [...path, node]); // Recursively explore all neighbors of the current node\n }\n };\n dfs(0, []); // Start the DFS from the source node\n return result;\n};", "solution_java": "Approach : Using dfs+ backtracking we can solve it\t\n\t\n\tclass Solution {\n\t\tpublic List> allPathsSourceTarget(int[][] graph) {\n\t\t\tList> ans=new ArrayList<>();\n\t\t\tList temp=new ArrayList<>();\n\t\t\t boolean []visit=new boolean [graph.length];\n\t\t\thelper(graph,0,graph.length-1,ans,temp,visit);\n\n\t\t\treturn ans;\n\t\t}\n\t\tpublic void helper(int[][] graph, int src,int dest,List> ans,List temp,boolean[]vis)\n\t\t{\n\n\t\t\tvis[src]=true;\n\t\t\ttemp.add(src);\n\t\t\tif(src==dest)\n\t\t\t{\n\t\t\t\tList b =new ArrayList<>();\n\t\t\t\tfor(int h:temp){\n\t\t\t\t\tb.add(h);\n\t\t\t\t}\n\t\t\t\tans.add(b);\n\t\t\t}\n\n\t\t\tfor(int i:graph[src])\n\t\t\t{\n\t\t\t\tif(vis[i]!=true)\n\t\t\t\t{\n\t\t\t\t\thelper(graph,i,dest,ans,temp,vis);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tvis[src]=false;\n\t\t\ttemp.remove(temp.size()-1);\n\t\t}\n\t}", "solution_c": "class Solution {\npublic:\n // setting a few class variables, so that we do not have to pass them down all the time in the recursive dfs calls\n int target;\n vector> res;\n vector tmp;\n void dfs(vector>& graph, int currNode = 0) {\n\t // updating tmp\n tmp.push_back(currNode);\n\t\t// and either updating res with it if target is met\n if (currNode == target) res.push_back(tmp);\n\t\t// or callling dfs again recursively\n else for (int node: graph[currNode]) {\n dfs(graph, node);\n }\n // backtracking with tmp\n\t\ttmp.pop_back();\n }\n vector> allPathsSourceTarget(vector>& graph) {\n target = graph.size() - 1;\n dfs(graph);\n return res;\n }\n};" }, { "title": "Simplified Fractions", "algo_input": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.\n\n \nExample 1:\n\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\n\n\nExample 2:\n\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\n\n\nExample 3:\n\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\n\n\n \nConstraints:\n\n\n\t1 <= n <= 100\n\n", "solution_py": "class Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n \n collect = {}\n for b in range(2, n+1):\n for a in range(1, b):\n if a/b not in collect:\n collect[a/b] = f\"{a}/{b}\" \n return list(collect.values())", "solution_js": "var simplifiedFractions = function(n) {\n const res = [];\n const checkValid = (a, b) => {\n if(a === 1) return 1;\n let num = 2;\n while(num <= a) {\n if(b % num === 0 && a % num === 0) return num;\n num++;\n }\n return 1;\n }\n let i = 1;\n while(i / n < 1) {\n let j = i + 1;\n while(j <= n) {\n if(checkValid(i, j) < 2) {\n res.push(`${i}/${j}`); \n }\n j++;\n }\n i++;\n }\n return res;\n};", "solution_java": "class Solution {\n public List simplifiedFractions(int n) {\n List list = new ArrayList<>() ;\n\n for(int numerator = 1; numerator< n ; numerator++) {\n for(int denominator = numerator+1; denominator<=n; denominator++) {\n if(gcd(numerator,denominator) == 1) {\n list.add(numerator+\"/\"+denominator);\n// System.out.println(numerator+\"/\"+denominator);\n }\n }\n }\n return list ;\n }\n\n static int gcd(int a, int b)\n {\n// euclidean algo\n\n if(a==0) {\n return b ;\n }\n return gcd(b%a,a);\n }\n}", "solution_c": "class Solution {\npublic:\n bool simplified(int n, int i){\n while(i>0){\n n-=i;\n if(i>n)swap(n,i);\n }\n if(n>1) return false;\n else return true;\n }\n\n vector simplifiedFractions(int n) {\n vector ans;\n while(n>1){\n int i=1;\n while(i0){\n fraction.push_back(num%10+'0');\n num/=10;\n }\n fraction.push_back('/');\n num = n;\n while(num>0){\n fraction.push_back(num%10+'0');\n num/=10;\n }\n if(i>9) swap(fraction[0],fraction[1]);\n if(n>99) swap(fraction[fraction.size()-1],fraction[fraction.size()-3]);\n else if(n>9) swap(fraction[fraction.size()-1],fraction[fraction.size()-2]);\n ans.push_back(fraction);\n }\n i++;\n }\n n--;\n }\n return ans;\n }\n};" }, { "title": "Isomorphic Strings", "algo_input": "Given two strings s and t, determine if they are isomorphic.\n\nTwo strings s and t are isomorphic if the characters in s can be replaced to get t.\n\nAll occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.\n\n \nExample 1:\nInput: s = \"egg\", t = \"add\"\nOutput: true\nExample 2:\nInput: s = \"foo\", t = \"bar\"\nOutput: false\nExample 3:\nInput: s = \"paper\", t = \"title\"\nOutput: true\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 * 104\n\tt.length == s.length\n\ts and t consist of any valid ascii character.\n\n", "solution_py": "class Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n dict1={}\n m=\"\"\n\t\t#creating a dictionary by mapping each element from string S to string T\n for i,j in zip(s,t):\n\t\t# this for the cases like \"badc\" and \"baba\" so we dont want two keys mapping to same value hence we can reject directly\n if j in dict1.values() and i not in dict1.keys():\n return False\n dict1[i]=j \n \n\t\t#now take each letter from string s and using dictionary values replace it with that specific character\n for k in s:\n m=m+dict1[k]\n\t\t\t\n\t\t#now if newly formed string m == T is same then the strings are Isomorphic\n if(m==t):\n return True\n else:\n return False", "solution_js": "/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isIsomorphic = function(s, t) {\n const obj = {};\n const setValues = new Set();\n let isIso = true;\n\n for(var indexI=0; indexIlist1 = new ArrayList<>();\n ArrayListlist2 = new ArrayList<>();\n for(int i=0;imp;\n for(int i=0;i int:\n i = j = res = 0\n while i < len(n1) and j < len(n2):\n if n1[i] > n2[j]:\n i += 1\n else:\n res = max(res, j - i)\n j += 1\n return res", "solution_js": "var maxDistance = function(nums1, nums2) {\n let i = 0, j = 0;\n \n let ans = 0;\n while (i < nums1.length && j < nums2.length) {\n // maintain the i <= j invariant\n j = Math.max(j, i);\n \n // we want to maximize j so move it forward whenever possible\n while (nums1[i] <= nums2[j]) {\n ans = Math.max(ans, j - i);\n j++;\n }\n \n // we want to minimize i so move it forward only to maintain invariants\n i++;\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public int maxDistance(int[] nums1, int[] nums2) {\n int max = 0;\n for (int i = 0; i < nums1.length; i++) {\n int r = nums2.length - 1;\n int l = i;\n int m = i;\n while (l <= r) {\n m = l + (r - l) / 2;\n if (nums1[i] > nums2[m]) {\n r = m - 1;\n } else if (nums1[i] == nums2[m]) {\n l = m + 1;\n } else {\n l = m + 1;\n }\n }\n if (r < 0) {\n continue;\n }\n max = Math.max(max, r - i);\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxDistance(vector& nums1, vector& nums2) {\n\n reverse(nums2.begin(),nums2.end());\n int ans = 0;\n for(int i=0;i int:\n inventory.sort(reverse=True) \n inventory += [0]\n res = 0\n k = 1\n \n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i]-inventory[i+1]) < orders:\n diff = inventory[i]-inventory[i+1]\n res += k*(inventory[i]+inventory[i+1]+1)*(diff)//2\n orders -= k*diff\n else: \n q, r = divmod(orders, k)\n res += k*(inventory[i]+(inventory[i]-q+1))*q//2\n res += r*(inventory[i]-q)\n return res%(10**9+7)\n k += 1", "solution_js": "var maxProfit = function(A, k) {\n //rangeSum Formula\n let rangesum=(i,j)=>{\n i=BigInt(i),j=BigInt(j)\n return ((j*((j+1n))/2n)-(i*(i+1n)/2n))\n }\n A.unshift(0) //prepend the sentinel 0 \n A.sort((a,b)=>a-b)\n let n=A.length,result=0n,mod=BigInt(1e9+7),i=n-1\n // can use all current levels\n while((k>=(n-i)*(A[i]-A[i-1]))&&i>0){\n if(A[i]!=A[i-1])\n result=(result+(rangesum(A[i-1],A[i])*BigInt(n-i)))%mod,\n k-=(n-i)*(A[i]-A[i-1])\n i--\n }\n //can use some of the current levels\n if(k>0&&k>=n-i){\n let levels=Math.floor(k/(n-i)) //the levels i can use \n result=(result+(BigInt(n-i)*rangesum(A[i]-levels,A[i])))%mod\n k-=levels*(n-i)\n A[i]-=levels\n }\n // can use some of the items OF the first level\n if(k>0&&k pq = new PriorityQueue<>((x, y) -> Long.compare(y, x));\n pq.offer(0L);\n\t\t\n // we use map to count the balls\n Map map = new HashMap<>();\n map.put(0L, 0L);\n \n for (int j : inventory) {\n long i = (long)j;\n if (map.containsKey(i)) {\n map.put(i, map.get(i) + 1);\n }\n else {\n pq.offer(i);\n map.put(i, 1L);\n }\n }\n \n long res = 0;\n while (orders > 0) {\n long ball = pq.poll(), nextBall = pq.peek();\n long times = map.get(ball);\n long diff = Math.min(ball - nextBall, orders / times);\n if (diff == 0) {\n res = (res + orders * ball) % mod;\n break;\n }\n long sum = (ball * 2 + 1 - diff) * diff / 2 * times;\n res = (res + sum) % mod;\n orders -= diff * times;\n if (!map.containsKey(ball - diff)) {\n map.put(ball - diff, map.get(ball));\n pq.offer(ball - diff);\n }\n else {\n map.put(ball - diff, map.get(ball - diff) + map.get(ball));\n }\n map.remove(ball);\n }\n return (int) res;\n }\n}", "solution_c": "#define ll long long\nconst int MOD = 1e9+7; \n\nclass Solution {\npublic:\n \n ll summation(ll n) {\n return (n*(n+1)/2);\n }\n \n int maxProfit(vector& inventory, int orders) {\n ll n = inventory.size(), i = 0, ans = 0;\n inventory.push_back(0);\n sort(inventory.rbegin(), inventory.rend());\n while(orders and i < n) {\n if(inventory[i] != inventory[i+1]) {\n ll width = i+1, h = inventory[i] - inventory[i+1];\n ll available = width * h, gain = 0;\n if(available <= orders) {\n orders -= available;\n\t\t\t\t\t// from each of the first i+1 inventories, we gain (inventory[i+1] + 1) + ... + inventory[i] value\n gain = (width * (summation(inventory[i]) - summation(inventory[i+1]))) % MOD; \n } else {\n ll q = orders / width, r = orders % width;\n\t\t\t\t\t// q balls picked from each of the first i+1 inventories\n gain = (width * (summation(inventory[i]) - summation(inventory[i]-q))) % MOD;\n\t\t\t\t\t// 1 ball picked from r inventories providing value (inventory[i]-q)\n gain = (gain + r*(inventory[i]-q)) % MOD;\n orders = 0;\n }\n \n ans = (ans + gain) % MOD; \n }\n \n i++;\n }\n \n return ans;\n }\n};" }, { "title": "Shortest Path in a Grid with Obstacles Elimination", "algo_input": "You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.\n\nReturn the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.\n\n \nExample 1:\n\nInput: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput: 6\nExplanation: \nThe shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\n\n\nExample 2:\n\nInput: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput: -1\nExplanation: We need to eliminate at least two obstacles to find such a walk.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 40\n\t1 <= k <= m * n\n\tgrid[i][j] is either 0 or 1.\n\tgrid[0][0] == grid[m - 1][n - 1] == 0\n\n", "solution_py": "class Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n Q = [[0, 0, k]] # m, n, remaining elimination quota \n rows, cols = len(grid), len(grid[0])\n V, counter = {(0, 0):k}, 0 # I use a V to keep track of how cells have been visited\n \n while Q: \n frontier = []\n for m, n, rem in Q: \n if m == rows - 1 and n == cols - 1: \n return counter \n for dm, dn in [[1, 0], [-1, 0], [0, 1], [0, -1]]: \n if 0 <= m+dm < rows and 0 <= n+dn < cols: # check inbound \n if grid[m+dm][n+dn] == 0: \n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem])\n V[(m+dm, n+dn)] = rem\n elif rem > 0: # I see a wall and I can still eliminate\n if (m+dm, n+dn) not in V or V[(m+dm, n+dn)] < rem - 1: # if not visited or could be visited with fewer elimination \n frontier.append([m+dm, n+dn, rem-1])\n V[(m+dm, n+dn)] = rem - 1\n Q = frontier \n counter += 1\n \n return -1\n\t```", "solution_js": "var shortestPath = function(grid, k) {\n const dir = [[-1, 0], [1, 0], [0, -1], [0, 1]];\n const m = grid.length;\n const n = grid[0].length;\n \n let q = [[0,0,k]];\n const visited = new Set();\n visited.add(`0:0:${k}`);\n let cnt = 0;\n while(q.length>0)\n {\n const size = q.length;\n for(let i = 0; i=0 && xx=0 && yy=0 && !visited.has(`${xx}:${yy}:${newK}`) )\n {\n q.push([xx, yy, newK]);\n visited.add(`${xx}:${yy}:${newK}`);\n }\n }\n }\n }\n cnt++;\n }\n return -1;\n};", "solution_java": "class Solution {\n int rowLen = 0;\n int colLen = 0;\n int MAXVAL = 0;\n public int shortestPath(int[][] grid, int k) {\n rowLen = grid.length;\n colLen = grid[0].length;\n MAXVAL = rowLen * colLen + 1;\n int path = shortest(grid, k, 0, 0, 0, new boolean[rowLen][colLen], new Integer[rowLen][colLen][k+1][4]);\n return path == MAXVAL ? -1 : path;\n }\n\n /* Direction\n 0 - Up\n 1 - Down\n 2 - Left\n 3 - Right\n */\n\n // For each cell(row, col) explore all possible ways to reach it with minimum cost, hence we consider the direction as well\n int shortest(int[][] grid, int k, int row, int col, int direction, boolean[][] visited, Integer[][][][] dp){\n // Reached end of the matrix\n if(row == rowLen - 1 && col == colLen - 1 && k >= 0)\n return 0;\n\n // Couldn't find a valid path\n if(k < 0 || row < 0 || col < 0 || row >= rowLen || col >= colLen)\n return MAXVAL;\n\n if(dp[row][col][k][direction] != null)\n return dp[row][col][k][direction];\n\n // 4 options to choose a direction\n // Go right\n int op1 = MAXVAL;\n if(col + 1 < colLen && !visited[row][col+1]) {\n visited[row][col+1] = true;\n if(grid[row][col+1] == 0)\n op1 = shortest(grid, k, row, col+1, 3, visited, dp) + 1;\n else\n op1 = shortest(grid, k-1, row, col+1, 3, visited, dp) + 1;\n visited[row][col+1] = false;\n }\n\n // Go left\n int op2 = MAXVAL;\n if(col - 1 >= 0 && !visited[row][col-1]) {\n visited[row][col-1] = true;\n if(grid[row][col-1] == 0)\n op2 = shortest(grid, k, row, col-1, 2, visited, dp) + 1;\n else\n op2 = shortest(grid, k-1, row, col-1, 2, visited, dp) + 1;\n visited[row][col-1] = false;\n }\n\n // Go up\n int op3 = MAXVAL;\n if(row - 1 >= 0 && !visited[row-1][col]) {\n visited[row-1][col] = true;\n if(grid[row-1][col] == 0)\n op3 = shortest(grid, k, row-1, col, 0, visited, dp) + 1;\n else\n op3 = shortest(grid, k-1, row-1, col, 0, visited, dp) + 1;\n visited[row-1][col] = false;\n }\n\n // Go down\n int op4 = MAXVAL;\n if(row + 1 < rowLen && !visited[row+1][col]) {\n visited[row+1][col] = true;\n if(grid[row+1][col] == 0)\n op4 = shortest(grid, k, row+1, col, 1, visited, dp) + 1;\n else\n op4 = shortest(grid, k-1, row+1, col, 1, visited, dp) + 1;\n visited[row+1][col] = false;\n }\n\n dp[row][col][k][direction] = Math.min(Math.min(op1, op2), Math.min(op3, op4));\n return dp[row][col][k][direction];\n }\n}", "solution_c": "class Solution {\npublic:\n vector> directions{{-1,0},{1,0},{0,1},{0,-1}};\n int shortestPath(vector>& grid, int k) {\n int m = grid.size(),n = grid[0].size(),ans=0;\n queue> q;\n bool visited[m][n][k+1];\n memset(visited,false,sizeof(visited));\n q.push({0,0,k});\n visited[0][0][k]=true;\n \n while(!q.empty()) {\n int size = q.size();\n while(size--) {\n auto p = q.front();\n q.pop();\n \n if(p[0]==m-1 && p[1]==n-1) return ans;\n for(auto x : directions) {\n int i= p[0]+x[0];\n int j= p[1]+x[1];\n int obstacle = p[2];\n \n if(i>=0 && i=0 && j0 && !visited[i][j][obstacle-1]) {\n q.push({i,j,obstacle-1});\n visited[i][j][obstacle-1]=true;\n }\n } \n }\n }\n ans++;\n }\n return -1;\n }\n};" }, { "title": "Minimum Number of Operations to Reinitialize a Permutation", "algo_input": "You are given an even integer n​​​​​​. You initially have a permutation perm of size n​​ where perm[i] == i​ (0-indexed)​​​​.\n\nIn one operation, you will create a new array arr, and for each i:\n\n\n\tIf i % 2 == 0, then arr[i] = perm[i / 2].\n\tIf i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].\n\n\nYou will then assign arr​​​​ to perm.\n\nReturn the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.\n\n \nExample 1:\n\nInput: n = 2\nOutput: 1\nExplanation: perm = [0,1] initially.\nAfter the 1st operation, perm = [0,1]\nSo it takes only 1 operation.\n\n\nExample 2:\n\nInput: n = 4\nOutput: 2\nExplanation: perm = [0,1,2,3] initially.\nAfter the 1st operation, perm = [0,2,1,3]\nAfter the 2nd operation, perm = [0,1,2,3]\nSo it takes only 2 operations.\n\n\nExample 3:\n\nInput: n = 6\nOutput: 4\n\n\n \nConstraints:\n\n\n\t2 <= n <= 1000\n\tn​​​​​​ is even.\n\n", "solution_py": "class Solution:\n def reinitializePermutation(self, n: int) -> int:\n ans = 0\n perm = list(range(n))\n while True: \n ans += 1\n perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]\n if all(perm[i] == i for i in range(n)): return ans", "solution_js": " * @param {number} n\n * @return {number}\n */\nvar reinitializePermutation = function(n) {\n if (n < 2) return 0;\n let prem = [];\n let count = 0;\n for (var i = 0; i < n; i++) {\n prem[i] = i;\n }\n let newArr = [];\n newArr = helper(prem, newArr);\n\n const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b);\n\n if (equals(prem, newArr)) {\n count++;\n return count;\n } else {\n while (!equals(prem, newArr)) {\n count++;\n let temp = newArr;\n newArr = [];\n newArr = helper(temp, newArr);\n }\n }\n return count + 1;\n};\n\nvar helper = function (prem, arr) {\n let n = prem.length;\n for (var i = 0; i < n; i++) {\n if (i % 2 == 0) {\n arr[i] = prem[i / 2];\n } else {\n arr[i] = prem[n / 2 + (i - 1) / 2];\n }\n }\n return arr;\n};", "solution_java": "class Solution {\n public int reinitializePermutation(int n) {\n int ans = 1;\n int num = 2;\n if(n == 2) return 1;\n while(true){\n if(num % (n-1) == 1)break; \n else {\n ans++;\n num = (num * 2) % (n-1);\n }\n }\n return ans;\n \n }\n}", "solution_c": "class Solution {\npublic:\n vector change(vectorarr,vectorv){\n int n=v.size();\n for(int i=0;iv(n);\n for(int i=0;iarr(n);\n\n arr=change(arr,v);\n if(arr==v){return 1;}\n\n int cnt=1;\n\n while(arr!=v){\n arr=change(arr,arr);\n cnt++;\n if(arr==v){return cnt;}\n\n }\n return cnt;\n }\n};" }, { "title": "Sum of Subarray Ranges", "algo_input": "You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.\n\nReturn the sum of all subarray ranges of nums.\n\nA subarray is a contiguous non-empty sequence of elements within an array.\n\n \nExample 1:\n\nInput: nums = [1,2,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.\n\nExample 2:\n\nInput: nums = [1,3,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.\n\n\nExample 3:\n\nInput: nums = [4,-2,-3,4,1]\nOutput: 59\nExplanation: The sum of all subarray ranges of nums is 59.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 1000\n\t-109 <= nums[i] <= 109\n\n\n \nFollow-up: Could you find a solution with O(n) time complexity?\n", "solution_py": "class Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n n = len(nums)\n \n # the answer will be sum{ Max(subarray) - Min(subarray) } over all possible subarray\n # which decomposes to sum{Max(subarray)} - sum{Min(subarray)} over all possible subarray\n # so totalsum = maxsum - minsum\n # we calculate minsum and maxsum in two different loops\n minsum = maxsum = 0\n \n # first calculate sum{ Min(subarray) } over all subarrays\n # sum{ Min(subarray) } = sum(f(i) * nums[i]) ; i=0..n-1\n # where f(i) is number of subarrays where nums[i] is the minimum value\n # f(i) = (i - index of the previous smaller value) * (index of the next smaller value - i) * nums[i]\n # we can claculate these indices in linear time using a monotonically increasing stack.\n stack = []\n for next_smaller in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically increasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_smaller == n or nums[stack[-1]] > nums[next_smaller]):\n i = stack.pop()\n prev_smaller = stack[-1] if stack else -1\n minsum += nums[i] * (next_smaller - i) * (i - prev_smaller)\n stack.append(next_smaller)\n \n # then calculate sum{ Max(subarray) } over all subarrays\n # sum{ Max(subarray) } = sum(f'(i) * nums[i]) ; i=0..n-1\n # where f'(i) is number of subarrays where nums[i] is the maximum value\n # f'(i) = (i - index of the previous larger value) - (index of the next larger value - i) * nums[i]\n # this time we use a monotonically decreasing stack.\n stack = []\n for next_larger in range(n + 1):\n\t\t\t# we pop from the stack in order to satisfy the monotonically decreasing order property\n\t\t\t# if we reach the end of the iteration and there are elements present in the stack, we pop all of them\n while stack and (next_larger == n or nums[stack[-1]] < nums[next_larger]):\n i = stack.pop()\n prev_larger = stack[-1] if stack else -1\n maxsum += nums[i] * (next_larger - i) * (i - prev_larger)\n stack.append(next_larger)\n \n return maxsum - minsum", "solution_js": "// O(n^3) time | O(1) space\nvar subArrayRanges = function(nums) {\n let res = 0\n for (let i = 1; i < nums.length; i++) {\n for (let j = 0; j < i; j++) {\n let smallest = nums[i], biggest = nums[i]\n for (let k = j; k < i; k++) {\n smallest = Math.min(smallest, nums[k])\n biggest = Math.max(biggest, nums[k])\n }\n res += biggest - smallest\n }\n }\n return res\n};", "solution_java": "class Solution {\n class Node{\n long val, displace;\n Node(long val, long displace){\n this.val = val;\n this.displace = displace;\n }\n }\n public long subArrayRanges(int[] nums) {\n \n //lesser than current element\n Stack stack = new Stack<>();\n //from left\n long [] lesserLeft = new long[nums.length];\n for (int i = 0; i< nums.length; i++){\n long count = 1;\n while(stack.size()>0 && stack.peek().val<=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n lesserLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] lesserRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val0 && stack.peek().val>=nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterLeft[i] = count;\n }\n stack.clear();\n //from right\n long[] greaterRight = new long[nums.length];\n for (int i = nums.length-1; i>=0; i--){\n long count = 1;\n while(stack.size()>0 && stack.peek().val>nums[i]){\n count+=stack.pop().displace;\n }\n stack.add(new Node(nums[i], count));\n greaterRight[i] = count;\n } \n \n long ans = 0;\n //Now we subtract the count of minimum occurrences from the count of maximum occurrences\n \n for (int i = 0; i< nums.length; i++){\n ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i];\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n long long subArrayRanges(vector& nums) {\n int n=nums.size();\n long long res=0;\n for(int i=0;imaxi)maxi=nums[j];\n else if(nums[j] i + 1:\n j -= 1\n power += tokens[j]\n else: break\n return i - (n - j)", "solution_js": "var bagOfTokensScore = function(tokens, power) {\n const n = tokens.length;\n \n tokens.sort((a, b) => a - b);\n \n let maxScore = 0;\n let currScore = 0;\n \n let left = 0;\n let right = n - 1;\n \n while (left <= right) {\n const leftPower = tokens[left];\n const rightPower = tokens[right];\n \n if (power >= leftPower) {\n power -= leftPower;\n currScore++;\n\n maxScore = Math.max(currScore, maxScore);\n left++;\n }\n else if (currScore > 0) {\n power += rightPower;\n currScore--;\n right--; \n }\n else {\n return maxScore;\n }\n }\n \n return maxScore;\n};", "solution_java": "class Solution {\n public int bagOfTokensScore(int[] tokens, int power) { \n //initially score is 0, that's why in these conditions, return 0. \n if(tokens.length == 0 || power < tokens[0])\n\t\t\treturn 0; \n Arrays.sort(tokens); //sort the array\n \n int i = 0;\n int r = tokens.length - 1;\n int score = 0;\n int answer = 0;\n \n while(i<=r){ \n if(power >= tokens[i]){\n power -= tokens[i++]; \n answer = Math.max(answer, ++score); //play all tokens, but store the max score in answer. \n }\n else if (score > 0){\n power += tokens[r--]; //take power from greatest element\n score--; //decrease by 1.\n } \n //when you can't do any of the steps (face up, face down)\n else\n return answer;\n } \n return answer;\n }\n}", "solution_c": "class Solution {\npublic:\n int bagOfTokensScore(vector& tokens, int power) {\n sort(tokens.begin(),tokens.end());\n int start=0,end=tokens.size()-1,score=0,ans=0;\n while(start<=end){\n if(power>=tokens[start]){\n ans=max(ans,++score);\n power-=tokens[start++];\n } else if(score>0){\n score--;\n power+=tokens[end--];\n } else {\n return 0;\n }\n }\n return ans;\n }\n};" }, { "title": "Greatest Sum Divisible by Three", "algo_input": "Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.\n\n \nExample 1:\n\nInput: nums = [3,6,5,1,8]\nOutput: 18\nExplanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\n\nExample 2:\n\nInput: nums = [4]\nOutput: 0\nExplanation: Since 4 is not divisible by 3, do not pick any number.\n\n\nExample 3:\n\nInput: nums = [1,2,3,4,4]\nOutput: 12\nExplanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 4 * 10^4\n\t1 <= nums[i] <= 10^4\n\n", "solution_py": "class Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n dp = [0, float('-inf'), float('-inf')]\n for x in nums:\n dp_cp = dp[:]\n for left in range(3):\n right = (left + x) % 3\n dp[right] = max(dp_cp[right], dp_cp[left] + x)\n\n return dp[0]", "solution_js": "var maxSumDivThree = function(nums) {\n // there are 3 options for how the sum fit's into 3 via mod % 3\n // track those 3 options via indices in the dp array\n // dp[0] = %3 === 0\n // dp[1] = %3 === 1\n // dp[2] = %3 === 2\n let dp = new Array(3).fill(0);\n for (let num of nums) {\n for (let i of dp.slice(0)) {\n let sum = i + num;\n let mod = sum % 3;\n // on each pass, set the value of dp[mod] to the Math.max val\n dp[mod] = Math.max(dp[mod], sum);\n }\n }\n return dp[0];\n};", "solution_java": "class Solution {\n\n public int maxSumDivThree(int[] nums) {\n int r0 = 0;\n int r1 = 0;\n int r2 = 0;\n for (int i = 0; i < nums.length; i++) {\n int nr0 = r0;\n int nr1 = r1;\n int nr2 = r2;\n int a = r0 + nums[i];\n int b = r1 + nums[i];\n int c = r2 + nums[i];\n if (a % 3 == 0) {\n nr0 = Math.max(nr0, a);\n } else if (a % 3 == 1) {\n nr1 = Math.max(nr1, a);\n } else if (a % 3 == 2) {\n nr2 = Math.max(nr2, a);\n }\n\n if (b % 3 == 0) {\n nr0 = Math.max(nr0, b);\n } else if (b % 3 == 1) {\n nr1 = Math.max(nr1, b);\n } else if (b % 3 == 2) {\n nr2 = Math.max(nr2, b);\n }\n\n if (c % 3 == 0) {\n nr0 = Math.max(nr0, c);\n } else if (c % 3 == 1) {\n nr1 = Math.max(nr1, c);\n } else if (c % 3 == 2) {\n nr2 = Math.max(nr2, c);\n }\n r0=nr0;\n r1=nr1;\n r2=nr2;\n }\n\n return r0;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxSumDivThree(vector& nums) {\n vector twos = {(int)1e4+1, (int)1e4+1}, ones = {(int)1e4+1, (int)1e4+1};\n int res = 0;\n for(int i: nums) {\n if(i%3 == 2) {\n if(i <= twos[0]) {\n twos[1] = twos[0], twos[0] = i;\n }\n else if(i < twos[1]) twos[1] = i;\n }\n else if(i%3 == 1) {\n if(i <= ones[0]) {\n ones[1] = ones[0], ones[0] = i;\n }\n else if(i < ones[1]) ones[1] = i;\n }\n res += i;\n }\n if(res%3 == 2)\n return max(res - twos[0], res - ones[0] - ones[1]);\n else if(res%3 == 1)\n return max(res - ones[0], res - twos[0] - twos[1]);\n return res;\n }\n};" }, { "title": "Boats to Save People", "algo_input": "You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.\n\nReturn the minimum number of boats to carry every given person.\n\n \nExample 1:\n\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\n\nExample 2:\n\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\n\nExample 3:\n\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\n\n\n \nConstraints:\n\n\n\t1 <= people.length <= 5 * 104\n\t1 <= people[i] <= limit <= 3 * 104\n\n", "solution_py": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people)-1\n boats = 0\n while lo <= hi:\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n else:\n hi -= 1\n boats += 1\n return boats", "solution_js": "/**\n * @param {number[]} people\n * @param {number} limit\n * @return {number}\n */\nvar numRescueBoats = function(people, limit) {\n people = people.sort((a,b) => a - b)\n\n let left = 0\n let right = people.length - 1\n let res = 0\n \n while (left <= right) {\n if (people[left] + people[right] <= limit) {\n res++\n right--\n left++\n } else if (people[right] <= limit) {\n res++ \n right--\n }\n }\n \n return res\n};", "solution_java": "class Solution {\n public int numRescueBoats(int[] people, int limit) {\n int boatCount = 0;\n Arrays.sort(people);\n\n int left = 0;\n int right = people.length - 1;\n\n while(left <= right){\n int sum = people[left] + people[right];\n if(sum <= limit){\n boatCount++;\n left++;\n right--;\n }\n else{\n boatCount++;\n right--;\n }\n }\n return boatCount;\n }\n}", "solution_c": "\t\t\t\t// 😉😉😉😉Please upvote if it helps 😉😉😉😉\nclass Solution {\npublic:\n int numRescueBoats(vector& people, int limit) {\n \n // sort vector\n sort(people.begin(),people.end());\n \n int i = 0, j = people.size() - 1,cnt = 0;\n \n while(i <= j)\n { \n // lightest person + heaviest person sum <= limit\n // they can go together\n if(people[i] + people[j] <= limit)\n {\n ++i;\n --j;\n }\n // if sum is over the limit,\n // heaviest will go alone.\n else\n --j;\n \n ++cnt; // number of boats\n }\n \n return cnt;\n \n }\n\t// for github repository link go to my profile.\n};" }, { "title": "Maximum Product of Two Elements in an Array", "algo_input": "Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).\n \nExample 1:\n\nInput: nums = [3,4,5,2]\nOutput: 12 \nExplanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \n\n\nExample 2:\n\nInput: nums = [1,5,4,5]\nOutput: 16\nExplanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\n\n\nExample 3:\n\nInput: nums = [3,7]\nOutput: 12\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 500\n\t1 <= nums[i] <= 10^3\n\n", "solution_py": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n # mx1 - max element, mx2 - second max element\n mx1 = nums[0] if nums[0] > nums[1] else nums[1]\n mx2 = nums[1] if nums[0] > nums[1] else nums[0]\n for num in nums[2:]:\n if num > mx1:\n mx1, mx2 = num, mx1\n elif num > mx2:\n mx2 = num\n\n return (mx1 - 1) * (mx2 - 1)", "solution_js": "var maxProduct = function(nums) {\n let val = [];\n for(let i=0; i max) {\n max = nums[i];\n maxi = i;\n }\n }\n nums[maxi] = Integer.MIN_VALUE;\n int nextmax = Integer.MIN_VALUE;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] > nextmax) nextmax = nums[i];\n }\n return max*nextmax-max-nextmax+1;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxProduct(vector& nums) {\n int n = nums.size(); \n sort(nums.begin(), nums.end()); \n return (nums[n -1]-1)* (nums[n-2]-1);\n }\n};" }, { "title": "Last Moment Before All Ants Fall Out of a Plank", "algo_input": "We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.\n\nWhen two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.\n\nWhen an ant reaches one end of the plank at a time t, it falls out of the plank immediately.\n\nGiven an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.\n\n \nExample 1:\n\nInput: n = 4, left = [4,3], right = [0,1]\nOutput: 4\nExplanation: In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).\n\n\nExample 2:\n\nInput: n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput: 7\nExplanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.\n\n\nExample 3:\n\nInput: n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput: 7\nExplanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 104\n\t0 <= left.length <= n + 1\n\t0 <= left[i] <= n\n\t0 <= right.length <= n + 1\n\t0 <= right[i] <= n\n\t1 <= left.length + right.length <= n + 1\n\tAll values of left and right are unique, and each value can appear only in one of the two arrays.\n\n", "solution_py": "class Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n # make sure left and right are not empty without changing the answer\n left.append(0)\n right.append(n)\n\n return max(max(left), n - min(right))", "solution_js": "var getLastMoment = function(n, left, right) {\n const maxLeft = Math.max(...left);\n const minRight = Math.min(...right);\n\n return Math.max(n - minRight, maxLeft);\n};", "solution_java": "class Solution {\n public int getLastMoment(int n, int[] left, int[] right) {\n int max = 0;\n for (int i = 0; i < left.length; i++) {\n if (left[i] > max)\n max = left[i];\n }\n for (int i = 0; i < right.length; i++) {\n if (n - right[i] > max)\n max = n - right[i];\n }\n return max;\n }\n}", "solution_c": "class Solution {\npublic:\n int getLastMoment(int n, vector& left, vector& right) {\n int mx=0;\n for(auto&i:left)mx=max(mx,i);\n for(auto&i:right)mx=max(mx,n-i);\n return mx;\n }\n};" }, { "title": "Smallest String Starting From Leaf", "algo_input": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.\n\nReturn the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\n\nAs a reminder, any shorter prefix of a string is lexicographically smaller.\n\n\n\tFor example, \"ab\" is lexicographically smaller than \"aba\".\n\n\nA leaf of a node is a node that has no children.\n\n \nExample 1:\n\nInput: root = [0,1,2,3,4,3,4]\nOutput: \"dba\"\n\n\nExample 2:\n\nInput: root = [25,1,3,1,3,0,2]\nOutput: \"adz\"\n\n\nExample 3:\n\nInput: root = [2,2,1,null,1,0,null,0]\nOutput: \"abc\"\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 8500].\n\t0 <= Node.val <= 25\n\n", "solution_py": "class Solution:\n res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, \"\")\n return self.res", "solution_js": "var smallestFromLeaf = function(root) {\n \n if(root === null) return '';\n \n let queue = [[root, ''+giveCharacter(root.val)]];\n let leafLevelFound = false;\n let possibleSmallString = [];\n \n while(queue.length > 0){\n \n let currentLevelLength = queue.length;\n \n \n for(let i=0; i a, 1 -> b, 2 -> c\n public Character intToChar(int i) {\n return (char) (i + 'a');\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 string res;\n void solve(TreeNode* root,string cur){\n if(!root) return;\n cur.push_back((char)('a'+root->val));//converting integer to corresponding characer\n if(!root->left and !root->right){\n\t\t\t//reversing the string since it is computed from root to leaf, but we need viceversa\n reverse(cur.begin(),cur.end());\n if(res==\"\" or curleft,cur);\n solve(root->right,cur);\n return;\n }\n string smallestFromLeaf(TreeNode* root) {\n if(!root) return \"\"; \n solve(root,\"\");\n return res;\n }\n};" }, { "title": "Find in Mountain Array", "algo_input": "(This problem is an interactive problem.)\n\nYou may recall that an array arr is a mountain array if and only if:\n\n\n\tarr.length >= 3\n\tThere exists some i with 0 < i < arr.length - 1 such that:\n\t\n\t\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n\t\tarr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n\t\n\t\n\n\nGiven a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.\n\nYou cannot access the mountain array directly. You may only access the array using a MountainArray interface:\n\n\n\tMountainArray.get(k) returns the element of the array at index k (0-indexed).\n\tMountainArray.length() returns the length of the array.\n\n\nSubmissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.\n\n \nExample 1:\n\nInput: array = [1,2,3,4,5,3,1], target = 3\nOutput: 2\nExplanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\n\nExample 2:\n\nInput: array = [0,1,2,4,2,1], target = 3\nOutput: -1\nExplanation: 3 does not exist in the array, so we return -1.\n\n\n \nConstraints:\n\n\n\t3 <= mountain_arr.length() <= 104\n\t0 <= target <= 109\n\t0 <= mountain_arr.get(index) <= 109\n\n", "solution_py": "# \"\"\"\n# This is MountainArray's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class MountainArray:\n# def get(self, index: int) -> int:\n# def length(self) -> int:\n\nclass Solution:\n def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:\n min_index = -1\n peak = self.findpeak(mountain_arr)\n \n min_index = self.binary_search(0, peak, mountain_arr, target, 1)\n if min_index == -1:\n min_index = self.binary_search(peak+1, mountain_arr.length() - 1, mountain_arr, target, -1)\n return min_index\n\n def findpeak(self, mountain_arr):\n start = 0\n end = mountain_arr.length() - 1\n while start < end:\n mid = start + int((end - start)/2)\n if mountain_arr.get(mid) < mountain_arr.get(mid + 1):\n start = mid + 1\n else:\n end = mid\n \n return start\n \n def binary_search(self, start, end, mountain_arr, target, asc):\n while start <= end:\n mid = start + int((end - start)/2)\n mountain_arr_get_mid = mountain_arr.get(mid)\n if target == mountain_arr_get_mid:\n return mid\n if asc == 1:\n if target < mountain_arr_get_mid:\n end = mid - 1\n elif target > mountain_arr_get_mid:\n start = mid + 1\n else:\n if target < mountain_arr_get_mid:\n start = mid + 1\n elif target > mountain_arr_get_mid:\n end = mid - 1\n \n return -1", "solution_js": "/**\n * // This is the MountainArray's API interface.\n * // You should not implement it, or speculate about its implementation\n * function MountainArray() {\n * @param {number} index\n * @return {number}\n * this.get = function(index) {\n * ...\n * };\n *\n * @return {number}\n * this.length = function() {\n * ...\n * };\n * };\n */\n\nvar binarySearch = function(left, right, condition) {\n while (left < right) {\n var mid = left + Math.floor((right - left) / 2);\n if (condition(mid)) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return left;\n}\n\n/**\n * @param {number} target\n * @param {MountainArray} mountainArr\n * @return {number}\n */\nvar findInMountainArray = function(target, mountainArr) {\n var n = mountainArr.length();\n var maxNumIdx = binarySearch(1, n - 2, function(idx) {\n return mountainArr.get(idx) > mountainArr.get(idx + 1);\n });\n var leftIdx = binarySearch(0, maxNumIdx, function(idx) {\n return mountainArr.get(idx) >= target;\n });\n if (mountainArr.get(leftIdx) === target) {\n return leftIdx;\n }\n var rightIdx = binarySearch(maxNumIdx, n - 1, function(idx) {\n return mountainArr.get(idx) <= target;\n });\n if (mountainArr.get(rightIdx) === target) {\n return rightIdx;\n }\n return -1;\n};", "solution_java": "class Solution {\n public int findInMountainArray(int target, MountainArray mountainArr) {\n int peak = findPeak(mountainArr);\n \n int left =binary(0,peak,mountainArr,target,true);\n if(left!=-1){\n return left;\n }\n int right= binary(peak+1,mountainArr.length()-1,mountainArr, target,false);\n return right; \n }\n \n static int findPeak(MountainArray mountainArr){\n int start=0;\n int end =mountainArr.length()-1;\n \n while(startarr.get(mid)){\n if(left){\n low=mid+1;\n }else{\n high=mid-1; \n } \n }else{\n return mid;\n }\n } \n return -1;\n }\n}", "solution_c": "/**\n * // This is the MountainArray's API interface.\n * // You should not implement it, or speculate about its implementation\n * class MountainArray {\n * public:\n * int get(int index);\n * int length();\n * };\n */\n\nclass Solution {\npublic:\n\n //----------------------- find peak ---------------------------------------\n\n int find_max(MountainArray &mountainArr,int start,int end)\n { int n= mountainArr.length();\n while(start<=end)\n { int mid= start+(end-start)/2;\n int next=(mid+1)%n;\n int prev=(mid+n-1)%n;\n\n int mid_val = mountainArr.get(mid);\n int pre_val = mountainArr.get(prev);\n int next_val = mountainArr.get(next);\n\n if(mid_val > next_val and mid_val>pre_val)\n return mid;\n\n else if(mid_val pre_val)\n start=mid+1;\n\n else if(mid_val>next_val and mid_val mid_val)\n {\n end=mid-1;\n }\n else\n start=mid+1;\n }\n return -1;\n }\n\n //------------------------------returns minimum index of target--------------------------------------\n\n int evaluate_ans(int a,int b)\n {\n if(a==-1 and b==-1 )\n return -1;\n else if(a!= -1 and b!= -1)\n return min(a,b);\n else if(a==-1 and b!=-1)\n return b;\n else\n return a;\n\n }\n\n int findInMountainArray(int target, MountainArray &mountainArr) {\n\n int start=0;\n int n= mountainArr.length()-1;\n int max_in = find_max(mountainArr,start ,n);\n\n int a= binary_search(mountainArr,start,max_in,target);\n int b= binary_search_rev(mountainArr,max_in + 1,n,target);\n\n return evaluate_ans(a,b);\n }\n};" }, { "title": "Count Nodes With the Highest Score", "algo_input": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.\n\nEach node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.\n\nReturn the number of nodes that have the highest score.\n\n \nExample 1:\n\nInput: parents = [-1,2,0,2,0]\nOutput: 3\nExplanation:\n- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.\n\n\nExample 2:\n\nInput: parents = [-1,2,0]\nOutput: 2\nExplanation:\n- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.\n\n\n \nConstraints:\n\n\n\tn == parents.length\n\t2 <= n <= 105\n\tparents[0] == -1\n\t0 <= parents[i] <= n - 1 for i != 0\n\tparents represents a valid binary tree.\n\n", "solution_py": "class Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n graph = collections.defaultdict(list)\n for node, parent in enumerate(parents): # build graph\n graph[parent].append(node)\n n = len(parents) # total number of nodes\n d = collections.Counter()\n def count_nodes(node): # number of children node + self\n p, s = 1, 0 # p: product, s: sum\n for child in graph[node]: # for each child (only 2 at maximum)\n res = count_nodes(child) # get its nodes count\n p *= res # take the product\n s += res # take the sum\n p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)\n d[p] += 1 # count the product\n return s + 1 # return number of children node + 1 (self)\n count_nodes(0) # starting from root (0)\n return d[max(d.keys())] # return max count", "solution_js": "var countHighestScoreNodes = function(parents) {\n const n = parents.length;\n const adj = [];\n \n for (let i = 0; i < n; ++i) {\n adj[i] = [];\n } \n \n for (let i = 1; i < n; ++i) {\n const parent = parents[i];\n adj[parent].push(i);\n }\n \n let maxProd = 0;\n let maxCount = 0;\n \n dfs(0);\n \n return maxCount;\n \n function dfs(node) {\n let rem = n - 1;\n\n let sum = 0;\n let prod = 1;\n\n for (const child of adj[node]) {\n const count = dfs(child);\n \n sum += count;\n prod *= count;\n rem -= count;\n }\n\n if (rem > 0) prod *= rem;\n\n if (prod > maxProd) {\n maxProd = prod;\n maxCount = 1;\n }\n else if (prod === maxProd) {\n ++maxCount;\n }\n\n return sum + 1;\n }\n};", "solution_java": "class Solution {\n long max = 0, res = 0;\n public int countHighestScoreNodes(int[] parents) {\n Map> hm = new HashMap();\n for(int i = 0; i < parents.length; i++) { // build the tree\n hm.computeIfAbsent(parents[i], x ->new ArrayList<>()).add(i);\n }\n dfs(0, parents.length, hm); // traverse the tree to get the result\n return (int)res;\n }\n int dfs(int s, int n, Map> hm) {\n int sum = 1;\n long mult = 1L;\n for(int child : hm.getOrDefault(s, new ArrayList<>())) {\n int count = dfs(child, n, hm); // subtree node count\n sum += count;\n mult *= count; // multiply the result by children size\n } \n mult *= (s == 0 ? 1L : n - sum); // multiply the result by remain size except self and children size(the nodes through parent)\n if(mult > max) {\n max = mult;\n res = 1;\n } else if (mult == max) {\n res++;\n }\n return sum; // return the node count of the tree rooted at s\n }\n}", "solution_c": "class Solution {\npublic:\n \n \n // Steps : \n // 1 - For each node, you need to find the sizes of the subtrees rooted in each of its children.\n \n // 2 - How to determine the number of nodes in the rest of the tree? \n\t// Can you subtract the size of the subtree rooted at the node from the total number of nodes of the tree?\n \n // 3 - Use these values to compute the score of the node. Track the maximum score, and how many nodes achieve such score. \n \n\t// calculating size of each subtree by standing at every node '0' to 'n-1'\n int dfs(int src,vector>& g,vector& size)\n {\n int ans = 1;// for curent node\n for(auto child : g[src]){\n ans += dfs(child,g,size);\n }\n return size[src] = ans; \n }\n \n // This code can also be work for generalized tree not only for Binary tree\n int countHighestScoreNodes(vector& parents) \n { \n int n=parents.size();\n vectorsize(n,0); // size[i] indicates size of subtree(rooted at i node) + 1\n vector>g(n); // storing left and right child of a node\n for(int i=1;i maxScore){\n maxScore = product;\n maxCount = 1;\n }\n else if(product == maxScore){\n maxCount++; // store count of nodes which have maximum score equal to \"maxScore\"\n }\n }\n \n return maxCount;\n }\n};" }, { "title": "Recover a Tree From Preorder Traversal", "algo_input": "We run a preorder depth-first search (DFS) on the root of a binary tree.\n\nAt each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node.  If the depth of a node is D, the depth of its immediate child is D + 1.  The depth of the root node is 0.\n\nIf a node has only one child, that child is guaranteed to be the left child.\n\nGiven the output traversal of this traversal, recover the tree and return its root.\n\n \nExample 1:\n\nInput: traversal = \"1-2--3--4-5--6--7\"\nOutput: [1,2,5,3,4,6,7]\n\n\nExample 2:\n\nInput: traversal = \"1-2--3---4-5--6---7\"\nOutput: [1,2,5,3,null,6,null,4,null,7]\n\n\nExample 3:\n\nInput: traversal = \"1-401--349---90--88\"\nOutput: [1,401,null,349,88,90]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the original tree is in the range [1, 1000].\n\t1 <= Node.val <= 109\n\n", "solution_py": "class Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n i = 0\n dummy_head = TreeNode()\n depth = 0\n while i < len(traversal):\n if traversal[i].isdigit():\n value, i = get_value(traversal, i)\n insert_node(dummy_head, depth, value)\n\n else:\n depth, i = get_depth(traversal, i)\n\n return dummy_head.left\n\n# Returns the next value from the string traversal, and returns the position following the last digit of the current value.\ndef get_value(traversal, i):\n value = 0\n while i < len(traversal) and traversal[i].isdigit():\n value *= 10\n value += int(traversal[i])\n i += 1\n\n return value, i\n\n# Insertes a node of the given `value` at the given `depth` of the subtree whose root is the given `root`.\ndef insert_node(root, depth, value):\n for _ in range(depth):\n if root.right:\n root = root.right\n else:\n root = root.left\n\n new_node = TreeNode(value)\n if root.left:\n root.right = new_node\n else:\n root.left = new_node\n\n# Gets the next depth from the string traversal, and returns the position following the last dash of the current depth.\ndef get_depth(traversal, i):\n depth = 0\n while i < len(traversal) and traversal[i] == \"-\":\n depth += 1\n i += 1\n\n return depth, i", "solution_js": "var recoverFromPreorder = function(traversal) {\n \n let n = traversal.length;\n \n // Every layer in dfs handles the depth+1 of '-' only.\n // ex: \n // depth=0 -> find '-' as splitter\n // depth=1 -> find '--' as splitter\n // depth=2 -> find '---' as splitter\n let dfs = (str,depth)=>{\n if(str.indexOf(\"-\") === -1) return new TreeNode(str);\n\t\t\n\t\t// 1. We split by the depth+1 number of '-'\n // Using regex to split is much easier. -> str.split(/(?<=\\d)-(?=\\d)/g)\n\t\t// where (?<=\\d) means positive lookbehind , ex: \"1- ...\", then we'll split '-' excluding 1.\n\t\t// Similarly , (?=\\d) means positive lookahead , ex: \"-5 ...\", then we'll split '-' excluding 5.\n\t\t\n let re = new RegExp(`(?<=\\\\d)${\"-\".repeat(depth+1)}(?=\\\\d)`,'g');\n let [val,leftStr,rightStr] = str.split(re);\n // ex: 1-2--3--4-5--6--7 --> ['1','2--3--4','5--6--7']\n \n\t\t// 2. After splitting, we'll get [val,leftStr,rightStr]\n\t\t// Then we could handle left / right node in the next dfs layer intuitively.\n let node = new TreeNode(val);\n if(leftStr) node.left = dfs(leftStr,depth+1);\n if(rightStr) node.right = dfs(rightStr,depth+1);\n \n return node;\n };\n \n return dfs(traversal,0);\n \n};", "solution_java": "class Solution {\n public TreeNode recoverFromPreorder(String traversal) {\n if(!traversal.contains(\"-\"))\n return new TreeNode(Integer.parseInt(traversal));\n String number = \"\";\n int i = 0;\n while(traversal.charAt(i)!='-'){\n number+=traversal.charAt(i);\n i++;\n }\n //System.out.print(\"root = \" + number + \" \" + i + \" \");\n TreeNode root = new TreeNode(Integer.parseInt(number));\n StringBuilder str = new StringBuilder();\n int bk = 0;\n for(int j = i; i < traversal.length(); i++){\n if(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-' && traversal.charAt(i+1) != '-')\n bk = str.toString().length();\n else if(!(traversal.charAt(i-1) != '-' && traversal.charAt(i) == '-'))\n str.append(traversal.charAt(i));\n }\n String divide = str.toString();\n \n TreeNode left = (bk==0)?recoverFromPreorder(divide):recoverFromPreorder(divide.substring(0,bk));\n TreeNode right = (bk==0)?null:recoverFromPreorder(divide.substring(bk,divide.length()));\n root.left = left;\n root.right = right;\n \n \n return root;\n }\n}", "solution_c": "class Solution {\npublic:\n\n // Returns the index of '-' if present otherwise returns the string length\n int findIndex(int ind, string &traversal){\n int req = traversal.size();\n for(int i=ind; i> st;\n\n // Finding the root node\n int ind = findIndex(0, traversal);\n string str = traversal.substr(0, ind);\n TreeNode *root = new TreeNode(stoi(str));\n\n // Pushing the root node along with its depth\n st.push({root, 0});\n\n // Starting from 'ind' as it has the next '-' character\n int i = ind;\n\n while(i 1\n int ind = findIndex(i, traversal);\n string str = traversal.substr(i, ind-i);\n TreeNode *node = new TreeNode(stoi(str));\n\n // Finding its appropriate parent, whose depth is one less than current depth\n while(!st.empty() && st.top().second != depth-1){\n st.pop();\n }\n\n // There is already left child for the parent\n if(st.top().first->left){\n st.top().first->right = node;\n }\n else{\n st.top().first->left = node;\n }\n\n // Pushing that node and its depth into stack\n st.push({node, depth});\n depth = 0;\n i = ind;\n }\n\n return root;\n }\n};" }, { "title": "Path with Maximum Gold", "algo_input": "In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.\n\nReturn the maximum amount of gold you can collect under the conditions:\n\n\n\tEvery time you are located in a cell you will collect all the gold in that cell.\n\tFrom your position, you can walk one step to the left, right, up, or down.\n\tYou can't visit the same cell more than once.\n\tNever visit a cell with 0 gold.\n\tYou can start and stop collecting gold from any position in the grid that has some gold.\n\n\n \nExample 1:\n\nInput: grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput: 24\nExplanation:\n[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.\n\n\nExample 2:\n\nInput: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput: 28\nExplanation:\n[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 15\n\t0 <= grid[i][j] <= 100\n\tThere are at most 25 cells containing gold.\n\n", "solution_py": "class Solution:\n def getMaximumGold(self, grid):\n answer = [0]\n\n def visit(visited, i, j, gold_sum):\n val = grid[i][j]\n if val == 0 or (i,j) in visited:\n answer[0] = max(answer[0], gold_sum)\n return\n\n gold_sum_new = gold_sum + val\n visited_new = visited.union({(i,j)})\n\n if i > 0:\n visit(visited_new, i-1, j, gold_sum_new)\n\n if j < len(grid[i]) - 1:\n visit(visited_new, i, j+1, gold_sum_new)\n\n if i < len(grid) - 1:\n visit(visited_new, i+1, j, gold_sum_new)\n if j > 0:\n visit(visited_new, i, j-1, gold_sum_new)\n #choosing the starting points\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] != 0:\n count = 0\n\n try:\n if grid[i-1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j+1] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i+1][j] != 0:\n count += 1\n except:\n pass\n try:\n if grid[i][j-1] != 0:\n count += 1\n except:\n pass\n\n if count < 3:\n visit(set(),i,j,0)\n\n return answer[0]", "solution_js": "var getMaximumGold = function(grid) {\n let max = 0;\n \n\t// This is our internal dfs function that will search all possible directions from a cell\n const mine = (x, y, n) => {\n\t // We can't mine any gold if the position is out of the grid, or the cell doesnt have any gold\n if (x < 0 || y < 0 || x > grid.length - 1 || y > grid[x].length - 1 || grid[x][y] == 0) return 0;\n\t\t\n\t\t// Save the temp value so we can mark the cell as visited\n let temp = grid[x][y];\n grid[x][y] = 0;\n \n\t\t// Try mining left, right, up, and down from the current position, \n\t\t// bringing along the gold total that was found in the current cell\n mine(x + 1, y, n + temp);\n mine(x - 1, y, n + temp);\n mine(x, y + 1, n + temp);\n mine(x, y - 1, n + temp);\n \n\t\t// After we've tried all directions reset cell to have its original value,\n\t\t// so it can be mined from a different starting point\n grid[x][y] = temp;\n \n\t\t// Update the max based on the mining done up until the current cell\n max = Math.max(max, n + temp);\n }\n\t\n\t// We need to run this dfs function through every potential starting point\n for (let i = 0; i < grid.length; i++) {\n for (let j = 0; j < grid[i].length; j++) {\n mine(i, j, 0);\n }\n }\n return max;\n \n};", "solution_java": "class Solution {\n int r = 0;\n int c = 0;\n int max = 0;\n public int getMaximumGold(int[][] grid) {\n r = grid.length;\n c = grid[0].length;\n for(int i = 0; i < r; i++) {\n for(int j = 0; j < c; j++) {\n if(grid[i][j] != 0) {\n dfs(grid, i, j, 0);\n }\n }\n }\n return max;\n }\n \n private void dfs(int[][] grid, int i, int j, int cur) {\n if(i < 0 || i >= r || j < 0 || j >= c || grid[i][j] == 0) {\n max = Math.max(max, cur);\n return;\n }\n int val = grid[i][j];\n grid[i][j] = 0;\n dfs(grid, i + 1, j, cur + val);\n dfs(grid, i - 1, j, cur + val);\n dfs(grid, i, j + 1, cur + val);\n dfs(grid, i, j - 1, cur + val);\n grid[i][j] = val;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxgold=0;\n int m,n;\n void gold(int i,int j,vector>& grid,vector>& vis,int count){\n// Down\n if(i+1=0 && !vis[i][j-1] && grid[i][j-1]){\n vis[i][j]=1;\n gold(i,j-1,grid,vis,count+grid[i][j-1]);\n vis[i][j]=0;\n }\n// Right\n if(j+1=0 && !vis[i-1][j] && grid[i-1][j]){\n vis[i][j]=1;\n gold(i-1,j,grid,vis,count+grid[i-1][j]);\n vis[i][j]=0;\n }\n maxgold=max(maxgold,count);\n }\n\n int getMaximumGold(vector>& grid) {\n m=grid.size();\n n=grid[0].size();\n for(int i=0;i>vis(m,vector(n,0));\n gold(i,j,grid,vis,grid[i][j]);\n }\n }\n }\n return maxgold;\n }\n};" }, { "title": "Count of Smaller Numbers After Self", "algo_input": "Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].\n\n \nExample 1:\n\nInput: nums = [5,2,6,1]\nOutput: [2,1,1,0]\nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\n\n\nExample 2:\n\nInput: nums = [-1]\nOutput: [0]\n\n\nExample 3:\n\nInput: nums = [-1,-1]\nOutput: [0,0]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t-104 <= nums[i] <= 104\n\n", "solution_py": "class Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n # build the binary indexed tree\n num_buckets = 10 ** 4 + 10 ** 4 + 1 # 10**4 negative + 10**4 positive numbers + bucket at 0\n tree = [0] * (num_buckets + 1) # add 1 because binary indexed tree data starts at index 1\n\n result = [0] * len(nums)\n\n # iterate from right to left\n for result_index in range(len(nums) - 1, -1, -1):\n n = nums[result_index]\n # add 10**4 to n to account for negative numbers\n i = n + 10 ** 4\n\n # convert to 1-based index for the tree\n i += 1\n # perform range sum query of buckets [-inf, n-1], where n is current number\n # because we want n - 1 for range sum query of [-inf, n-1], not n, subtract 1 from i:\n i -= 1\n\n val = 0\n while i != 0:\n val += tree[i]\n # get parent node by subtracting least significant set bit\n i -= i & -i\n\n result[result_index] = val\n\n # update the binary indexed tree with new bucket\n i = n + 10 ** 4\n i += 1\n while i < len(tree):\n tree[i] += 1\n # get next node to update by adding the least significant set bit\n i += i & -i\n\n return result", "solution_js": "var countSmaller = function(nums) {\n if(nums===null || nums.length == 0) return []\n \n let N = nums.length\n const result = new Array(N).fill(0)\n const numsWithIdx = new Array(N).fill(0)\n \n for(let i = 0; i < nums.length; i++) {\n const curr = nums[i]\n \n numsWithIdx[i] = {val:curr, originalIdx: i}\n }\n\n divideAndConqueuer(0, nums.length - 1)\n \n const resultList = []\n result.forEach(el => resultList.push(el))\n \n return resultList\n\n function divideAndConqueuer(left, right) {\n if(left < right) {\n const mid = Math.floor(left + (right - left)/2)\n divideAndConqueuer(left, mid)\n divideAndConqueuer(mid+1, right)\n merge(left, mid, right)\n }\n }\n\n function merge(left, mid, right) {\n const leftLen = mid - left + 1\n const rightLen = right - mid\n \n let rightSmallers = 0\n\n const leftAux = new Array(leftLen).fill(0)\n const rightAux = new Array(rightLen).fill(0)\n\n\n for(let i = 0; i < leftLen; i++) {\n leftAux[i] = numsWithIdx[left+i]\n }\n\n\n for(let i = 0; i < rightLen; i++) {\n rightAux[i] = numsWithIdx[mid+1+i]\n }\n\n\n let leftPointer = 0\n let rightPointer = 0\n let insertAtPointer = left\n\n while(leftPointer < leftLen && rightPointer < rightLen) {\n if(leftAux[leftPointer].val <= rightAux[rightPointer].val) {\n \n result[leftAux[leftPointer].originalIdx] += rightSmallers \n numsWithIdx[insertAtPointer++] = leftAux[leftPointer++]\n \n } else {\n numsWithIdx[insertAtPointer++] = rightAux[rightPointer++] \n rightSmallers++\n }\n }\n\n\n while(rightPointer < rightLen) {\n numsWithIdx[insertAtPointer++] = rightAux[rightPointer++] \n }\n \n while(leftPointer < leftLen) {\n result[leftAux[leftPointer].originalIdx] += rightSmallers \n numsWithIdx[insertAtPointer++] = leftAux[leftPointer++] \n }\n\n }\n};", "solution_java": "class Solution { \n public List countSmaller(int[] nums) {\n int min = 20001;\n int max = -1;\n for (int num : nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n \n min--;\n int[] count = new int[max-min+1];\n Integer[] result = new Integer[nums.length];\n for (int i = nums.length-1; i >=0; i--) {\n int k = nums[i]-min-1;\n int c = 0;\n do {\n c += count[k];\n k -= (-k&k);\n } while (k > 0);\n result[i] = c;\n \n k = nums[i]-min;\n while (k < count.length) {\n count[k]++;\n k += (-k&k);\n }\n }\n \n return Arrays.asList(result);\n }\n}", "solution_c": "typedef struct _SmallerValueCount {\n _SmallerValueCount(const int &value, const int &originalIndex) :\n mValue(value), mOriginalIndex(originalIndex) {}\n \n int mValue = 0;\n int mOriginalIndex = 0;\n} SmallerValueCount;\n\nclass Solution {\npublic:\n vector countSmaller(vector& nums) {\n vector convertedNums;\n convertedNums.reserve(nums.size());\n\n for (int i = 0; i < nums.size(); ++i)\n convertedNums.emplace_back(SmallerValueCount(nums[i], i));\n\n vector smallerCounts(convertedNums.size(), 0);\n merge_sort(convertedNums, smallerCounts, 0, nums.size() - 1);\n\n return smallerCounts;\n }\n\n void merge_sort(vector &nums, vector &smallerCounts, const int &left, const int &right) {\n if (left >= right)\n return;\n const auto mid = (left + right) / 2;\n merge_sort(nums, smallerCounts, left, mid);\n merge_sort(nums, smallerCounts, mid+1, right);\n merge(nums, smallerCounts, left, mid, right);\n }\n\n void merge(vector &nums, vector &smallerCounts, const int &left, const int &mid, const int &right)\n {\n vector buffer;\n buffer.reserve(right - left + 1);\n\n int i = left, j = mid + 1;\n int smallerCount = 0;\n while (i <= mid && j <= right)\n if (nums[i].mValue > nums[j].mValue)\n {\n ++smallerCount;\n buffer.push_back(nums[j]);\n ++j;\n }\n else\n {\n smallerCounts[nums[i].mOriginalIndex] += smallerCount;\n buffer.push_back(nums[i]);\n ++i;\n }\n\n while (i <= mid)\n {\n smallerCounts[nums[i].mOriginalIndex] += smallerCount;\n buffer.push_back(nums[i]);\n ++i;\n }\n\n while (j <= right)\n {\n buffer.push_back(nums[j]);\n ++j;\n }\n\n std::move(std::begin(buffer), std::end(buffer), std::next(std::begin(nums), left));\n }\n\n};" }, { "title": "01 Matrix", "algo_input": "Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.\n\nThe distance between two adjacent cells is 1.\n\n \nExample 1:\n\nInput: mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput: [[0,0,0],[0,1,0],[0,0,0]]\n\n\nExample 2:\n\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput: [[0,0,0],[0,1,0],[1,2,1]]\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 <= m, n <= 104\n\t1 <= m * n <= 104\n\tmat[i][j] is either 0 or 1.\n\tThere is at least one 0 in mat.\n\n", "solution_py": "class Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n if not mat or not mat[0]:\n return []\n\n m, n = len(mat), len(mat[0])\n queue = deque()\n MAX_VALUE = m * n\n \n # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 0:\n queue.append((i, j))\n else:\n mat[i][j] = MAX_VALUE\n \n directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n \n while queue:\n row, col = queue.popleft()\n for dr, dc in directions:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and mat[r][c] > mat[row][col] + 1:\n queue.append((r, c))\n mat[r][c] = mat[row][col] + 1\n \n return mat", "solution_js": "/**\n * @param {number[][]} mat\n * @return {number[][]}\n */\nvar updateMatrix = function(mat) {\n const rows = mat.length,\n cols = mat[0].length;\n \n if (!rows) return mat;\n \n const queue = new Queue();\n const dist = Array.from({length: rows}, () => new Array(cols).fill(Infinity));\n \n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n if (!mat[i][j]) {\n dist[i][j] = 0;\n queue.enqueue([i, j]);\n }\n }\n }\n \n const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];\n \n while (!queue.isEmpty()) {\n const [ row, col ] = queue.dequeue();\n for (let i = 0; i < 4; i++) {\n const nRow = row + dirs[i][0],\n nCol = col + dirs[i][1];\n \n if (nRow < 0 || nCol < 0 || nRow >= rows || nCol >= cols) continue;\n \n if (dist[nRow][nCol] > dist[row][col] + 1) {\n dist[nRow][nCol] = dist[row][col] + 1;\n queue.enqueue([nRow, nCol]);\n }\n }\n }\n \n return dist;\n};", "solution_java": "class Solution {\n// BFS\n// We add all 0 to the queue in the 0th level of the BFS. From there, every subsequent pair of indexes added would be 1 in the mat. THis way levels can represent the distance of a one from the closest 0 to it.\n boolean visited[][];\n \n // Could also convert the indexes to a single number by mat[0].length * i + j.\n class Pair{\n int x;\n int y;\n Pair(int x, int y){\n this.x = x;\n this.y = y;\n }\n }\n public int[][] updateMatrix(int[][] mat) {\n int level = 0;\n visited = new boolean[mat.length][mat[0].length];\n Queue q = new ArrayDeque<>();\n // Addition of all pairs in mat that have 0.\n for(int i = 0; i < mat.length; i++){\n for(int j = 0; j < mat[0].length; j++){\n if(mat[i][j] == 0){\n visited[i][j] = true;\n q.add(new Pair(i, j));\n }\n }\n }\n while(q.size()>0){\n int size = q.size();\n while(size-- > 0){\n Pair p = q.remove();\n mat[p.x][p.y] = level;\n if(p.x > 0 && visited[p.x - 1][p.y] == false){\n visited[p.x-1][p.y] = true;\n q.add(new Pair(p.x-1, p.y));\n }\n if(p.x < mat.length - 1 && visited[p.x + 1][p.y] == false){\n visited[p.x+1][p.y] = true;\n q.add(new Pair(p.x+1, p.y));\n \n }\n if(p.y > 0 && visited[p.x][p.y-1] == false){\n visited[p.x][p.y-1] = true;\n q.add(new Pair(p.x, p.y-1));\n \n }\n if(p.y < mat[0].length-1 && visited[p.x][p.y + 1] == false){\n visited[p.x][p.y+1] = true;\n q.add(new Pair(p.x, p.y + 1));\n }\n }\n level++;\n }\n return mat;\n }\n}", "solution_c": "class Solution {\n bool isValid(vector>& grid,int r,int c,int nr,int nc,int m,int n){\n if(nr>=0 && nc>=0 && nr> updateMatrix(vector>& mat) {\n queue> q;\n int m = mat.size();\n int n = mat[0].size();\n for(int i=0;i bool:\n \n # if already equal\n if target == mat:\n return True\n # there are 4 different rotation with 90 deg. \n # We need to check at most 3 more rotation.\n for i in range(3):\n # transpose the matrix by swap row and col values.\n for j in range(len(mat)):\n for k in range(j+1, len(mat)):\n mat[j][k], mat[k][j] = mat[k][j], mat[j][k]\n # Reflect the row by reverse it.\n mat[j] = mat[j][::-1]\n # now the matrix is roteted; check if they're alike.\n if target == mat:\n return True\n return False", "solution_js": "var findRotation = function(mat, target) {\n let width = mat[0].length;\n let height = mat.length;\n \n let normal = true;\n let rightOneTime = true;\n let rightTwoTimes = true;\n let rightThreeTimes = true;\n for (let i = 0; i < height; i++) {\n for (let j = 0; j < width; j++) {\n // don't rotate mat\n if (mat[i][j] !== target[i][j]) {\n normal = false;\n }\n // rotate mat right 1 time\n if (mat[i][j] !== target[j][width - 1 - i]) {\n rightOneTime = false;\n }\n // rotate mat right 2 times\n if (mat[i][j] !== target[height - 1 - i][width - 1 - j]) {\n rightTwoTimes = false;\n }\n // rotate mat right 3 times\n if (mat[i][j] !== target[height - 1 - j][i]) {\n rightThreeTimes = false;\n }\n }\n }\n return normal || rightOneTime || rightTwoTimes || rightThreeTimes;\n};", "solution_java": "class Solution {\n public boolean findRotation(int[][] mat, int[][] target) {\n if (mat == target) return true;\n int n = mat.length;\n int[] res[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 90\n for (int j = 0; j < n; j++) {\n res[i][j] = mat[n - 1 - j][i];\n }\n }\n\n int[] res2[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 180\n for (int j = 0; j < n; j++) {\n res2[i][j] = res[n - 1 - j][i];\n }\n }\n\n int[] res3[] = new int[n][n];\n for (int i = 0; i < n; i++) { //clockwise 270\n for (int j = 0; j < n; j++) {\n res3[i][j] = res2[n - 1 - j][i];\n }\n }\n\n //compare to 90,180,270 and itself\n if(Arrays.deepEquals(target, res) || Arrays.deepEquals(target, res2) || Arrays.deepEquals(target, res3) || Arrays.deepEquals(target, mat) ){\n return true;\n }\n return false;\n }\n}\n\n// Arrays.deepEquals() use for matrix", "solution_c": "class Solution {\npublic:\n bool findRotation(vector>& mat, vector>& target) {\n int n = mat.size();\n if(mat == target) { // rotation by 0 degree.\n return true;\n }\n\n int deg = 3; // more rotations with 90, 180, 270 degree's.\n\n while(deg --) {\n for(int i = 0; i < n; i ++) {\n for(int j = i; j < n; j ++) {\n swap(mat[i][j], mat[j][i]); // transpose of matrix.\n }\n }\n for(int i = 0; i < n; i ++) {\n reverse(mat[i].begin(),mat[i].end()); // reverse each row.\n }\n if(mat == target) {\n return true;\n }\n }\n return false;\n }\n};" }, { "title": "Map of Highest Peak", "algo_input": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells.\n\n\n\tIf isWater[i][j] == 0, cell (i, j) is a land cell.\n\tIf isWater[i][j] == 1, cell (i, j) is a water cell.\n\n\nYou must assign each cell a height in a way that follows these rules:\n\n\n\tThe height of each cell must be non-negative.\n\tIf the cell is a water cell, its height must be 0.\n\tAny two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n\n\nFind an assignment of heights such that the maximum height in the matrix is maximized.\n\nReturn an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.\n\n \nExample 1:\n\n\n\nInput: isWater = [[0,1],[0,0]]\nOutput: [[1,0],[2,1]]\nExplanation: The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.\n\n\nExample 2:\n\n\n\nInput: isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput: [[1,1,0],[0,1,1],[1,2,2]]\nExplanation: A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n\n\n \nConstraints:\n\n\n\tm == isWater.length\n\tn == isWater[i].length\n\t1 <= m, n <= 1000\n\tisWater[i][j] is 0 or 1.\n\tThere is at least one water cell.\n\n", "solution_py": "class Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n arr = collections.deque()\n m, n = len(isWater), len(isWater[0])\n for i in range(m):\n for j in range(n):\n if isWater[i][j] == 1:\n arr.append((0, i, j))\n \n ans = [[-1] * n for _ in range(m)]\n while arr:\n val, x, y = arr.popleft() \n if ans[x][y] != -1: continue\n ans[x][y] = val\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n xx, yy = x+dx, y+dy\n if 0 <= xx < m and 0 <= yy < n and ans[xx][yy] == -1:\n arr.append((val+1, xx, yy))\n return ans", "solution_js": "var highestPeak = function(isWater) {\n const RN = isWater.length, CN = isWater[0].length;\n const output = [...Array(RN)].map(() => Array(CN).fill(-1));\n const dir = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n let queue = []\n\n for(let r = 0; r < RN; r++) {\n for(let c = 0; c < CN; c++) {\n if(isWater[r][c]) {\n queue.push([r, c]);\n output[r][c] = 0;\n }\n }\n }\n\n while(queue.length) {\n const next = []\n\n for(let [r, c] of queue) {\n for(let [dr, dc] of dir) {\n dr += r;\n dc += c;\n if(dr < 0 || dc < 0 || dr >= RN || dc >= CN || output[dr][dc] !== -1) continue;\n output[dr][dc] = output[r][c] + 1;\n next.push([dr, dc]);\n }\n }\n queue = next;\n }\n return output;\n};", "solution_java": "class Solution {\n \n static int[][] DIRECTION = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};\n int rows;\n int cols;\n int[][] isWater;\n\n \n public int[][] highestPeak(int[][] isWater) {\n this.isWater = isWater;\n rows = isWater.length;\n cols = isWater[0].length;\n \n\n int[][] heightCells = new int[rows][cols];\n \n //store the coordinate of water cell\n Queue queue = new LinkedList();\n \n for(int r = 0; r < rows; r++){\n for(int c = 0; c < cols; c++){\n if(isWater[r][c] == 1){\n \n //mark as water\n heightCells[r][c] = 0;\n \n //add water coordinate\n queue.add(new int[]{r, c});\n } else{\n //mark default value for land\n heightCells[r][c] = -1; \n }\n }\n }\n\n \n /*\n * Approach\n * 1. start from every water source, \n update their neighbor height\n * 2. add each neighbours which was not processed earlier\n 3. do it every cell is processed\n */\n bfs(queue, heightCells);\n \n \n return heightCells;\n }\n \n private void bfs(Queue queue, int[][] heightCells){\n \n while(!queue.isEmpty()){\n int[] cell = queue.remove();\n \n //increment height of neighbor cell in all 4 direction \n //e.g, left, right, up, down\n for(int[] dir : DIRECTION){\n \n int newRow = cell[0] + dir[0];\n int newCol = cell[1] + dir[1]; \n \n //check new coordinate of cell inside the grid or not\n if(!isInsideGrid(newRow, newCol)) continue;\n \n //check already handled\n if(heightCells[newRow][newCol] != -1) continue;\n\n //increament, \n heightCells[newRow][newCol] = heightCells[cell[0]][cell[1]] + 1;\n \n //to handle the neighbour of this new cell\n queue.add(new int[]{newRow, newCol});\n }\n \n }\n }\n \n private boolean isInsideGrid(int row, int col){\n return row >= 0 && row < rows && col >= 0 && col < cols;\n } \n}", "solution_c": "class Solution {\npublic:\n\n vector> highestPeak(vector>& isWater) {\n int r = isWater.size();\n int c = isWater[0].size();\n queue > curr;\n\n for (int i = 0; i < r; i++) {\n for (int j = 0; j < c; j++) {\n //set the land cell to -1 (not visited)\n if (isWater[i][j] == 0) {\n isWater[i][j] = -1;\n }\n //set the water cell to zero and to queue\n else {\n isWater[i][j] = 0;\n curr.push({i, j});\n }\n }\n }\n\n int hill = 0;\n while (!curr.empty()) {\n int len = curr.size();\n\n for (int k = 0; k < len; k++) {\n\n //for each cell check its 4 boundary cells\n //if it is not visited, increase its hill by 1\n pair fnt = curr.front(); curr.pop();\n int i = fnt.first, j = fnt.second;\n\n //top cell\n if (i > 0 && isWater[i - 1][j] == -1) {\n isWater[i - 1][j] = hill + 1;\n curr.push({i-1, j});\n }\n //bottom cell\n if ((i < r - 1) && (isWater[i + 1][j] == -1)) {\n isWater[i + 1][j] = hill + 1;\n curr.push({i+1, j});\n }\n //left cell\n if (j > 0 && (isWater[i][j - 1] == -1)) {\n isWater[i][j - 1] = hill + 1;\n curr.push({i, j-1});\n }\n //right cell\n if ((j < c - 1) && (isWater[i][j + 1] == -1)) {\n isWater[i][j + 1] = hill + 1;\n curr.push({i, j+1});\n }\n }\n\n //after 1 complete round increase the height of the hill\n hill += 1;\n }\n\n return isWater;\n }\n};" }, { "title": "Path Crossing", "algo_input": "Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.\n\nReturn true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.\n\n \nExample 1:\n\nInput: path = \"NES\"\nOutput: false \nExplanation: Notice that the path doesn't cross any point more than once.\n\n\nExample 2:\n\nInput: path = \"NESWW\"\nOutput: true\nExplanation: Notice that the path visits the origin twice.\n\n \nConstraints:\n\n\n\t1 <= path.length <= 104\n\tpath[i] is either 'N', 'S', 'E', or 'W'.\n\n", "solution_py": "class Solution:\n def isPathCrossing(self, path: str) -> bool:\n c = set()\n x,y = 0,0\n c.add((x,y))\n for i in path:\n if i == 'N':\n y+=1\n elif i == 'E':\n x+=1\n elif i == 'W':\n x-=1\n else:\n y-=1\n if (x,y) in c:\n return True\n else:\n c.add((x,y))\n return False", "solution_js": "var isPathCrossing = function(path) {\n let set = new Set();\n let curr = [0, 0]\n \n let start = `${curr[0]}, ${curr[1]}`\n set.add(start)\n \n for (let el of path) {\n if (el === 'N') curr[1]++;\n else if (el === 'S') curr[1]--;\n else if (el === 'E') curr[0]++;\n else curr[0]--;\n \n let key = `${curr[0]}, ${curr[1]}`\n if (set.has(key)) return true;\n set.add(key)\n }\n \n return false;\n};", "solution_java": "// Path crossing\n// Leetcode\n\nclass Solution {\n public boolean isPathCrossing(String path) {\n Set visited = new HashSet<>();\n int x = 0, y = 0;\n visited.add(x + \",\" + y);\n for (char c : path.toCharArray()) {\n if (c == 'N') y++;\n else if (c == 'S') y--;\n else if (c == 'E') x++;\n else x--;\n if (visited.contains(x + \",\" + y)) return true;\n visited.add(x + \",\" + y);\n }\n return false; \n }\n}", "solution_c": "class Solution {\npublic:\n bool isPathCrossing(string path) {\n\n set>st;\n\n int x=0,y=0;\n\n st.insert({0, 0});\n\n for(int i=0;i List[List[int]]:\n G = defaultdict(list)\n din = defaultdict(int)\n dout = defaultdict(int)\n for v, w in pairs:\n G[v].append(w)\n dout[v] += 1\n din[w] += 1\n start = pairs[0][0]\n for v in G:\n if din[v]+1 == dout[v]:\n start = v\n route = []\n def dfs(v):\n while G[v]:\n w = G[v].pop()\n dfs(w)\n route.append(v)\n dfs(start)\n route.reverse()\n return [[route[i],route[i+1]] for i in range(len(route)-1)]", "solution_js": "var validArrangement = function(pairs) {\n let graph = {};\n let degrees = {}; // outdegree: positive, indegree: negative\n for (var [x, y] of pairs) {\n if (!graph[x]) graph[x] = [];\n graph[x].push(y);\n if (degrees[x] === undefined) degrees[x] = 0;\n if (degrees[y] === undefined) degrees[y] = 0;\n degrees[x]++;\n degrees[y]--;\n }\n let start = pairs[0][0];\n for (var [x] of pairs) {\n if (degrees[x] === 1) start = x; // one extra outdegree\n }\n let ans = [];\n dfs(start);\n\n function dfs(node) {\n while ((graph[node] || []).length) {\n let neighbor = graph[node].pop();\n dfs(neighbor);\n ans.push([node, neighbor]);\n }\n }\n return ans.reverse();\n};", "solution_java": "class Solution {\n public int[][] validArrangement(int[][] pairs) {\n int n = pairs.length;\n \n int[][] ans = new int[n][2];\n for (int[] a : ans) {\n a[0] = -1;\n a[1] = -1;\n }\n \n Map outdegree = new HashMap<>();\n Map> out = new HashMap<>();\n \n for (int[] pair : pairs) {\n outdegree.put(pair[0], outdegree.getOrDefault(pair[0], 0) + 1);\n outdegree.put(pair[1], outdegree.getOrDefault(pair[1], 0) - 1);\n \n out.computeIfAbsent(pair[0], k -> new ArrayDeque<>());\n out.computeIfAbsent(pair[1], k -> new ArrayDeque<>());\n \n out.get(pair[0]).addLast(pair[1]);\n }\n \n for (Map.Entry entry : outdegree.entrySet()) {\n if (entry.getValue() == 1) ans[0][0] = entry.getKey();\n if (entry.getValue() == -1) ans[n - 1][1] = entry.getKey();\n }\n \n if (ans[0][0] == -1) {\n ans[0][0] = pairs[0][0];\n ans[n - 1][1] = pairs[0][0];\n }\n \n int i = 0;\n int j = n - 1;\n while (i < j) {\n int from = ans[i][0];\n \n Deque toList = out.get(from);\n \n if (toList.size() == 0) {\n ans[j][0] = ans[--i][0];\n ans[--j][1] = ans[j + 1][0];\n } else {\n ans[i++][1] = toList.removeLast();\n ans[i][0] = ans[i - 1][1];\n }\n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> validArrangement(vector>& pairs) {\n int m = pairs.size();\n // Eulerian Path\n unordered_map> adj;\n unordered_map in;\n unordered_map out;\n // reserve spaces for unordered_map may help in runtime.\n adj.reserve(m);\n in.reserve(m);\n out.reserve(m);\n for (int i = 0; i < m; i++) {\n int u = pairs[i][0], v = pairs[i][1];\n in[v]++;\n out[u]++;\n adj[u].push(v);\n }\n // find the starting node\n int start = -1;\n for (auto& p : adj) {\n int i = p.first;\n if (out[i] - in[i] == 1) start = i;\n }\n if (start == -1) {\n // Eulerian Circuit -> start at any node\n start = adj.begin()->first;\n }\n vector> ans;\n euler(adj, ans, start);\n reverse(ans.begin(), ans.end());\n return ans;\n }\nprivate:\n void euler(unordered_map>& adj, vector>& ans, int curr) {\n auto& stk = adj[curr];\n while (!stk.empty()) {\n int nei = stk.top();\n stk.pop();\n euler(adj, ans, nei);\n // postorder\n ans.push_back({curr, nei});\n }\n }\n};" }, { "title": "Car Fleet", "algo_input": "There are n cars going to the same destination along a one-lane road. The destination is target miles away.\n\nYou are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).\n\nA car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).\n\nA car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.\n\nIf a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.\n\nReturn the number of car fleets that will arrive at the destination.\n\n \nExample 1:\n\nInput: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\nOutput: 3\nExplanation:\nThe cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\nThe car starting at 0 does not catch up to any other car, so it is a fleet by itself.\nThe cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\nNote that no other cars meet these fleets before the destination, so the answer is 3.\n\n\nExample 2:\n\nInput: target = 10, position = [3], speed = [3]\nOutput: 1\nExplanation: There is only one car, hence there is only one fleet.\n\n\nExample 3:\n\nInput: target = 100, position = [0,2,4], speed = [4,2,1]\nOutput: 1\nExplanation:\nThe cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\nThen, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\n\n\n \nConstraints:\n\n\n\tn == position.length == speed.length\n\t1 <= n <= 105\n\t0 < target <= 106\n\t0 <= position[i] < target\n\tAll the values of position are unique.\n\t0 < speed[i] <= 106\n\n", "solution_py": "class Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n def computeArrivalTime(curr_pos, curr_speed):\n nonlocal target\n return (target - curr_pos) / curr_speed\n # avoid integer division, as a car may arrive at 5.2s and another at 5.6s\n\n cars = list(zip(position, speed))\n cars.sort(key=lambda x: x[0], reverse=True)\n arrival_bound = None # time upper bound\n fleet = 0\n for pos, sp in cars:\n curr_arrival = computeArrivalTime(pos, sp)\n if not arrival_bound or curr_arrival > arrival_bound:\n arrival_bound = curr_arrival\n fleet += 1\n return fleet\n # time O(n logn): sort = (nlogn); loop = (n)\n # space O(n): depend on sort", "solution_js": "var carFleet = function(target, position, speed) {\n for (let i = 0 ; i < position.length ; i ++) {\n position[i] = [target - position[i], speed[i]]\n }\n position.sort((a, b) => { return a[0] - b[0] })\n let count = 1, prev = position[0][0] / position[0][1]\n for (let i = 1 ; i < position.length ; i ++) {\n\t\t// if the time taken is longer then it will cause another fleet\n if (position[i][0] / position[i][1] > prev) {\n count ++\n prev = position[i][0] / position[i][1]\n }\n }\n \n return count\n};", "solution_java": "class Solution {\n class pair implements Comparable{\n int pos;\n double time;\n pair(int pos,double time){\n this.pos=pos;\n this.time=time;\n }\n public int compareTo(pair o){\n return o.pos-this.pos;\n }\n }\n public int carFleet(int target, int[] position, int[] speed) {\n double []arr=new double[position.length];\n for(int i=0;ipq=new PriorityQueue<>();\n for(int i=0;i0){\n pair rem=pq.remove();\n if(updatetime& position, vector& speed) {\n \n int n = position.size();\n vector> cars;\n \n for(int i=0; i=0; i--){\n times[i] =((double) (target-cars[i].first)/cars[i].second);\n if(i str:\n if int(n)>0:\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])>=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n else:\n n = n[1:]\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])<=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n ans = \"-\"+ans\n \n return ans\n ", "solution_js": "var maxValue = function(n, x) {\n let i;\n\n // if the number if positive, find the first\n // number that is less than x\n if (n[0] !== '-') {\n for (i = 0; i < n.length; i++) {\n if (Number(n[i]) < x) break;\n } \n \n // if the number is negative, find the first\n // number that is greater than x\n } else {\n for (i = 1; i < n.length; i++) {\n if (Number(n[i]) > x) break;\n }\n }\n \n // return the string with x inserted at the found index\n return n.slice(0, i) + x + n.slice(i)\n};\n\n\n///////////////// short hand ////////////////////\n\n\nvar maxValue = function(n, x) {\n let i;\n if (n[0] !== '-') {\n for (i = 0; i < n.length; i++) {\n if (Number(n[i]) < x) break;\n } \n } else {\n for (i = 1; i < n.length; i++) {\n if (Number(n[i]) > x) break;\n }\n }\n return n.slice(0, i) + x + n.slice(i)\n};", "solution_java": "class Solution {\n public String maxValue(String n, int x) {\n StringBuilder res= new StringBuilder();\n int i=0, j=0;\n if(n.charAt(0)=='-'){\n res.append(n.charAt(0));\n for(j=1; j= x){ \n res.append(ch);\n }else{\n res.append(x);\n res.append(ch);\n res.append(n.substring(i+1));\n break;\n }\n }\n if(i==n.length()){\n res.append(x);\n }\n }\n return res.toString();\n }\n}", "solution_c": "class Solution { \n\npublic:\nstring maxValue(string s, int x) {\n int p=0,flag=0;\n char ch='0'+x; //change int to char\n string str;\n\t\n if(s[0]=='-')\n { //for negative numbers\n\t for(int i=1;is[i] && !flag){\n str+=ch;\n str+=s[i];\n flag=1;\n }\n else \n str+=s[i];\n } \n if(!flag) str+=ch;\n return str;\n }\n};" }, { "title": "Camelcase Matching", "algo_input": "Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.\n\nA query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.\n\n \nExample 1:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput: [true,false,true,true,false]\nExplanation: \"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".\n\n\nExample 2:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput: [true,false,true,false,false]\nExplanation: \"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".\n\n\nExample 3:\n\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput: [false,true,false,false,false]\nExplanation: \"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".\n\n\n \nConstraints:\n\n\n\t1 <= pattern.length, queries.length <= 100\n\t1 <= queries[i].length <= 100\n\tqueries[i] and pattern consist of English letters.\n\n", "solution_py": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n res, N = [], len(pattern)\n\t\t\n for query in queries:\n\t\t\n if self.upLetter(query) != self.upLetter(pattern) or self.LCS(query, pattern) != N:\n res.append(False)\n \n else:\n res.append(True)\n\t\t\t\t\n return res\n \n \n\t\t\n def LCS(self, A, B):\n N, M = len(A), len(B)\n d = [[0 for _ in range(M+1)] for _ in range(N+1)]\n\n for i in range(1, N+1):\n for j in range(1, M+1):\n\t\t\t\n if A[i - 1] == B[j - 1]:\n d[i][j] = 1 + d[i-1][j-1]\n\n else:\n d[i][j] = max(d[i-1][j], d[i][j-1])\n return d[-1][-1]\n\n\n \n def upLetter(self, w):\n count = 0\n for c in w:\n if c.isupper():\n count += 1\n return count", "solution_js": "var camelMatch = function(queries, pattern) {\n function camelMatch(q, p){\n let qlist=[]\n let plist=[]\n for(let a of q) if(a<='Z') qlist.push(a);\n for(let a of p) if(a<='Z') plist.push(a);\n return plist.join('') === qlist.join('')\n }\n function seqMatch(q, p){\n if(!camelMatch(p,q)) return false\n let pi=0\n for(let qi=0; qiseqMatch(q, pattern))\n}", "solution_java": "class Solution {\n public List camelMatch(String[] queries, String pattern) {\n List list = new ArrayList<>();\n\n for (var q : queries) {\n int index = 0;\n boolean flag = true;\n for (var c : q.toCharArray()) {\n if(index < pattern.length() && c == pattern.charAt(index)){\n index++;\n continue;\n }\n if(c >= 'A' && c <= 'Z'){\n if(index >= pattern.length() || c != pattern.charAt(index)){\n flag = false;\n break;\n }\n }\n }\n flag = flag && index == pattern.length();\n list.add(flag);\n }\n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n vector camelMatch(vector& queries, string pattern) {\n \n vector res(queries.size());\n \n for (int i = 0; i < queries.size(); i++)\n {\n int patRef = 0;\n bool isCamel = true;\n \n for (const char& ltr : queries[i])\n {\n if (patRef == pattern.size())\n {\n if (isupper(ltr))\n {\n isCamel = false;\n break;\n }\n }\n else\n {\n if (isupper(ltr) and isupper(pattern[patRef]) and ltr != pattern[patRef])\n {\n isCamel = false;\n break;\n }\n else if (islower(ltr) and islower(pattern[patRef]) and ltr == pattern[patRef])\n patRef++;\n else if (ltr == pattern[patRef])\n patRef++;\n }\n }\n \n if (patRef == pattern.size() and isCamel)\n res[i] = true;\n }\n \n return res;\n }\n};" }, { "title": "Decode the Message", "algo_input": "You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:\n\n\n\tUse the first appearance of all 26 lowercase English letters in key as the order of the substitution table.\n\tAlign the substitution table with the regular English alphabet.\n\tEach letter in message is then substituted using the table.\n\tSpaces ' ' are transformed to themselves.\n\n\n\n\tFor example, given key = \"happy boy\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').\n\n\nReturn the decoded message.\n\n \nExample 1:\n\nInput: key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\nOutput: \"this is a secret\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"the quick brown fox jumps over the lazy dog\".\n\n\nExample 2:\n\nInput: key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\nOutput: \"the five boxing wizards jump quickly\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".\n\n\n \nConstraints:\n\n\n\t26 <= key.length <= 2000\n\tkey consists of lowercase English letters and ' '.\n\tkey contains every letter in the English alphabet ('a' to 'z') at least once.\n\t1 <= message.length <= 2000\n\tmessage consists of lowercase English letters and ' '.\n\n", "solution_py": "class Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n alpha = ['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 i=0\n d={}\n for j in key:\n if j!=\" \" and j not in d:\n d[j]=alpha[i]\n i+=1\n if len(d)==26:\n break\n res=\"\"\n d[\" \"]=\" \"\n for i in message:\n res+=d[i]\n return res", "solution_js": "var decodeMessage = function(key, message) {\n let result = ''\n key = Array.from(new Set(key.split(' ').join('')))\n const hash = new Map()\n const alpha = 'abcdefghijklmnopqrstuvwxyz'\n \n for (let i = 0; i < alpha.length; i++) {\n hash.set(key[i], alpha[i])\n }\n\n for (let chr of message) {\n result += hash.get(chr) || ' '\n }\n \n return result\n};", "solution_java": "class Solution {\n public String decodeMessage(String key, String message) {\n StringBuilder ans = new StringBuilder();//Using String Builder to append the string\n key = key.replaceAll(\" \", \"\");\n //Removing the spaces\n HashMap letters = new HashMap<>();\n //Mapping the key into a hashmap.\n char original = 'a';\n for (int i = 0; i < key.length() ; i++) {\n if (!letters.containsKey(key.charAt(i))){\n letters.put(key.charAt(i),original++);\n }\n }\n //After the first pass all the letters of the key will be mapped with their respective original letters.\n for (int i = 0; i < message.length(); i++) {\n if (letters.containsKey(message.charAt(i))){\n //Now replacing the letters of the message with appropriate letter according to the key\n ans.append(letters.get(message.charAt(i)));\n }else{\n ans.append(message.charAt(i));\n //This is for characters other than the letters in the key example a space \" \"\n //They will not be replaced by any letters hence original letter is appended into the StringBuilder\n }\n }\n return ans.toString();\n }\n}", "solution_c": "class Solution {\npublic:\n string decodeMessage(string key, string message) {\n vector alpha {'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 int i=0;\n\n map d;\n\n for(int j=0;j<26;j++){\n d[alpha[j]]='0';\n }\n\n for(int j=0; j bool:\n if len(arr) < k*m:\n return False\n \n n = len(arr)\n pattern = arr[0:m]\n repeats = 1\n for i in range(m, n - m + 1, m):\n if arr[i:i+m] != pattern:\n break\n \n repeats += 1\n if repeats >= k:\n return True\n \n return self.containsPattern(arr[1:], m, k)", "solution_js": "var containsPattern = function(arr, m, k) {\n\tconst origin = arr.join(',');\n\n\treturn arr.some((_, index, array) => {\n\t\tconst check = arr.slice(index, m + index).join(',') + ',';\n\n\t\tindex + k * m > arr.length && array.splice(index);\n\t\tconst target = check.repeat(k).slice(0, -1);\n\t\tif (~origin.indexOf(target)) return true\n\t});\n};", "solution_java": "// Time complexity: O(N)\n// Space complexity: O(1)\nclass Solution {\n public boolean containsPattern(int[] arr, int m, int k) {\n int count = 0;\n for (int i = 0; i < arr.length - m; i++) {\n if (arr[i] == arr[i + m]) {\n count++;\n } else {\n count = 0;\n }\n if (count == m * (k-1)) {\n return true;\n }\n }\n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool containsPattern(vector& arr, int m, int k) {\n unordered_map> ump;\n string num = \"\";\n for(int i = 0; i < arr.size(); ++i)\n num += to_string(arr[i]);\n for(int i = 0; i <= num.length() - m; ++i){\n string str = num.substr(i, m);\n ump[str].push_back(i);\n }\n for(auto it = ump.begin(); it != ump.end(); ++it){\n if(it->second.size() >= k){\n bool flag = true;\n for(int i = 1; i < it->second.size(); ++i){\n if(it->second[i] - it->second[i - 1] < m)\n flag = false;\n }\n if(flag == true)\n return true;\n }\n }\n return false;\n }\n};" }, { "title": "The k Strongest Values in an Array", "algo_input": "Given an array of integers arr and an integer k.\n\nA value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].\n\nReturn a list of the strongest k values in the array. return the answer in any arbitrary order.\n\nMedian is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).\n\n\n\tFor arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.\n\tFor arr = [-7, 22, 17, 3], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.\n\n\n \nExample 1:\n\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\n\n\nExample 2:\n\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\n\n\nExample 3:\n\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 105\n\t-105 <= arr[i] <= 105\n\t1 <= k <= arr.length\n\n", "solution_py": "class Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n n = len(arr)\n medInd = (n-1)//2\n arr = sorted(arr)\n med = arr[medInd]\n \n start, end = 0, n-1\n ans = []\n while start <= end and len(ans) < k:\n if abs(med - arr[end]) < abs(med - arr[start]):\n ans.append(arr[start])\n start += 1\n else:# abs(med - arr[end]) >= abs(med - arr[start]):\n # <= because end is always bigger in a sorted array\n ans.append(arr[end])\n end -= 1\n \n return ans", "solution_js": "var getStrongest = function(arr, k) {\n // sort array so we can easily find median\n const sorted = arr.sort((a,b) => a-b)\n // get index of median\n const medianIndex = Math.floor(((sorted.length-1)/2))\n // get median\n const median = sorted[medianIndex]\n\n // custom sort function following the parameters given us in the description\n const compareFunction = (a, b) => {\n if (Math.abs(a-median) > Math.abs(b-median)) {\n return 1\n }\n else if (Math.abs(a-median) === Math.abs(b-median) && a > b) {\n return 1\n } else {\n return -1\n }\n }\n\n // sort array using our custom sort function\n const strongest = arr.sort(compareFunction).reverse().slice(0,k);\n\n return strongest;\n};", "solution_java": "class Solution {\n public int[] getStrongest(int[] arr, int k) {\n int[] result = new int[k];\n int n = arr.length, left = 0, right = n - 1, idx = 0;\n Arrays.sort(arr);\n int median = arr[(n - 1) / 2];\n while (left <= right) {\n int diff_l = Math.abs(arr[left] - median);\n int diff_r = Math.abs(arr[right] - median);\n\n if (diff_r > diff_l)\n result[idx++] = arr[right--];\n else if (diff_l > diff_r)\n result[idx++] = arr[left++];\n else if (arr[right] > arr[left])\n result[idx++] = arr[right--];\n else\n result[idx++] = arr[left++];\n if (idx == k)\n break;\n }\n return result;\n }\n}", "solution_c": "class Solution \n{\npublic:\n vector getStrongest(vector& arr, int k) \n {\n int n=arr.size();\n sort(arr.begin(),arr.end());\n int m=arr[(n-1)/2];\n priority_queue> pq;\n for(auto it: arr)\n {\n pq.push({abs(it-m),it});\n }\n vector ans;\n while(k-- && !pq.empty())\n {\n ans.push_back(pq.top().second);\n pq.pop();\n }\n return ans;\n }\n};" }, { "title": "Maximum Product Subarray", "algo_input": "Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.\n\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n\nA subarray is a contiguous subsequence of the array.\n\n \nExample 1:\n\nInput: nums = [2,3,-2,4]\nOutput: 6\nExplanation: [2,3] has the largest product 6.\n\n\nExample 2:\n\nInput: nums = [-2,0,-1]\nOutput: 0\nExplanation: The result cannot be 2, because [-2,-1] is not a subarray.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t-10 <= nums[i] <= 10\n\tThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n\n", "solution_py": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n prod=1\n maxprod=-100000000\n for i in range(len(nums)): # traverse from L-R so that we get max \n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n prod=1\n for i in range(len(nums)-1,-1,-1): #if 0 or -ve present at starting then find from back\n prod*=nums[i]\n maxprod=max(maxprod,prod)\n if prod==0:\n prod=1\n\n return maxprod", "solution_js": "/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxProduct = function(nums) {\n const n = nums.length - 1;\n let ans = nums[0];\n let l = 1, r = 1;\n\n for (let i = 0; i < nums.length; i++) {\n l = (l ? l : 1) * nums[i];\n r = (r ? r : 1) * nums[n - i];\n ans = Math.max(ans, Math.max(l, r));\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int maxProduct(int[] nums) {\n int ans = Integer.MIN_VALUE;\n int m = 1;\n for(int i=0; i< nums.length; i++){\n m*=nums[i];\n ans = Math.max(m, ans);\n if(m == 0) m=1;\n }\n int n = 1;\n for(int i=nums.length-1; i>=0; i--){\n n*=nums[i];\n ans = Math.max(n, ans);\n if(n == 0) n=1;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxProduct(vector& nums) {\n int n = nums.size();\n int negPro = 1;\n int posPro = 1;\n int CHECK_ZERO = 0;\n int res = INT_MIN;\n for(int i = 0; i < n; i++)\n {\n if(nums[i] == 0)\n {\n posPro = 1;\n negPro = 1;\n CHECK_ZERO = 1;\n }\n int numPos = posPro * nums[i];\n int numNeg = negPro * nums[i];\n posPro = max(numPos, max(numNeg, nums[i]));\n negPro = min(numPos, min(numNeg, nums[i]));\n res = max(posPro,res);\n }\n return (CHECK_ZERO ? max(0,res) : res);\n }\n};" }, { "title": "Subarray Sums Divisible by K", "algo_input": "Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.\n\nA subarray is a contiguous part of an array.\n\n \nExample 1:\n\nInput: nums = [4,5,0,-2,-3,1], k = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\n\nExample 2:\n\nInput: nums = [5], k = 9\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 3 * 104\n\t-104 <= nums[i] <= 104\n\t2 <= k <= 104\n\n", "solution_py": "class Solution:\n def subarraysDivByK(self, nums, k):\n n = len(nums)\n prefix_mod = 0\n result = 0\n\n # There are k mod groups 0...k-1.\n mod_groups = [0] * k\n mod_groups[0] = 1\n\n for num in nums:\n # Take modulo twice to avoid negative remainders.\n prefix_mod = (prefix_mod + num % k + k) % k\n # Add the count of subarrays that have the same remainder as the current\n # one to cancel out the remainders.\n result += mod_groups[prefix_mod]\n mod_groups[prefix_mod] += 1\n\n return result", "solution_js": "var subarraysDivByK = function(nums, k) {\n let count = 0;\n let map = new Map();\n map.set(0, 1)\n let sum = 0;\n for(let i=0; i map = new HashMap<>();\n int count = 0;\n int sum = 0;\n for(int i=0;i& nums, int k) {\n // take an ans variable\n int ans = 0;\n // initialize a map of int, int and insert {0,1} as 0 occurs first time for sum\n unordered_map mapp;\n mapp.insert({0,1});\n // initialize presum = 0 and remainder rem = 0 which will be used in further calculations\n int presum = 0;\n\n int rem = 0;\n\n // Logic\n /*\n 1. We will traverse the entire given array/vector.\n 2. While traversing we will add the element in our presum, i.e presum += nums[i] .\n 3. Now we will do the % of presum and k and store it in rem that we have created.\n 4. We need to take care of negative value of rem. If it is < 0, then we will add k to the remainder to make it positive.\n 5. Now we will check if rem already exist in the map. If it exist then we will add it's frequency to ans variable\n and then increment rem's value in map, i.e. mapp[rem]++, else we will add it in the map.\n 6. At last we will return ans.\n */\n\n for(int i=0; i float:\n \n x_dir = [2, 1, -1, -2, -2, -1, 1, 2]\n y_dir = [1, 2, 2, 1, -1, -2, -2, -1]\n \n cache = {}\n \n def kMoves(i, j, moves):\n if i >= n or j >= n or i < 0 or j < 0:\n return 0\n \n if moves == k:\n return 1\n \n if (i, j, moves) in cache:\n return cache[(i, j, moves)]\n \n totMoves = 0\n for ind in range(8):\n totMoves += kMoves(i+x_dir[ind], j+y_dir[ind], moves+1)*(1/8)\n \n cache[(i, j, moves)] = totMoves\n return totMoves\n \n return kMoves(row, column, 0)", "solution_js": "var knightProbability = function(n, k, row, column) {\n if (k === 0) return 1;\n const dirs = [[-2, -1], [-1, -2], [1, -2], [2, -1], [2, 1], [1, 2], [-1, 2], [-2, 1]];\n const dp = Array(k + 1)\n .fill('')\n .map(_ => Array(n).fill('').map(_ => Array(n).fill(0)));\n\n const isOut = (pos) => pos < 0 || pos > n - 1;\n const move = (x = row, y = column, step = k) => {\n if (step === 0) return 1;\n const moves = dp[step][x][y];\n if (moves !== 0) return moves;\n\n for (const [mvoeX, moveY] of dirs) {\n const nextX = x + mvoeX;\n const nextY = y + moveY;\n if (isOut(nextX) || isOut(nextY)) continue;\n\n dp[step][x][y] += move(nextX, nextY, step - 1);\n }\n return dp[step][x][y];\n };\n\n move();\n return dp[k][row][column] / 8 ** k;\n};", "solution_java": "class Solution {\n public double knightProbability(int n, int k, int row, int column) {\n double [][]curr=new double[n][n];\n double [][]next=new double[n][n];\n \n curr[row][column]=1;\n \n int [][]dir={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};\n for(int p=1;p<=k;p++){\n for(int i=0;i=n || nj>=n){\n continue;\n }\n \n next[ni][nj]+=curr[i][j]/8.0;\n }\n }\n }\n }\n \n curr=next;\n next=new double[n][n];\n }\n \n double sum=0.0;\n \n for(int i=0;i dx = {-2, -2, -1, 1, 2, 2, 1, -1};\n \n vector dy = {-1, 1, 2, 2, 1, -1, -2, -2};\n \n double dfs(int i, int j, int n, int moves)\n {\n // base case if we have reached out of grid\n \n if(i < 0 || i >= n || j < 0 || j >= n)\n return 0;\n \n // if no moves are remaining\n \n if(moves <= 0)\n return 1;\n \n // if already calculated\n \n if(dp[i][j][moves] != 0)\n return dp[i][j][moves];\n \n // find total possible ways of staying on chess board\n \n double ans = 0;\n \n for(int k = 0; k < 8; k++)\n {\n int new_row = i + dx[k];\n \n int new_col = j + dy[k];\n \n ans += dfs(new_row, new_col, n, moves - 1);\n }\n \n // for each cell there are 8 possible moves, so probablity will be no. of successfull moves / 8\n \n // store the result and return\n \n return dp[i][j][moves] = ans / 8.0;\n }\n \n double knightProbability(int n, int k, int row, int column) {\n \n // initialize the dp with 0\n \n memset(dp, 0, sizeof(dp));\n \n return dfs(row, column, n, k);\n }\n};" }, { "title": "Rearrange Spaces Between Words", "algo_input": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.\n\nRearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.\n\nReturn the string after rearranging the spaces.\n\n \nExample 1:\n\nInput: text = \" this is a sentence \"\nOutput: \"this is a sentence\"\nExplanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\n\n\nExample 2:\n\nInput: text = \" practice makes perfect\"\nOutput: \"practice makes perfect \"\nExplanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.\n\n\n \nConstraints:\n\n\n\t1 <= text.length <= 100\n\ttext consists of lowercase English letters and ' '.\n\ttext contains at least one word.\n\n", "solution_py": "class Solution(object):\n def reorderSpaces(self, text):\n word_list = text.split()\n words, spaces = len(word_list), text.count(\" \")\n \n if words > 1:\n q, r = spaces//(words-1), spaces%(words-1)\n return (\" \" * q).join(word_list) + \" \" * r\n else:\n return \"\".join(word_list) + \" \" * spaces", "solution_js": "var reorderSpaces = function(text) {\n let arr = text.split(\" \");\n let totalSpace = arr.length-1;\n arr = arr.filter(w => w !== '');\n let spaceBetween = arr.length > 1 ?\n Math.floor(totalSpace / (arr.length-1)) : 0;\n let spaceLeftOver = arr.length > 1 ?\n totalSpace % (arr.length-1) : totalSpace;\n return (arr.join(\" \".repeat(spaceBetween)) + \" \".repeat(spaceLeftOver));\n // Time Complexity: O(n)\n // Space Complexity: O(n)\n};", "solution_java": "class Solution {\n public String reorderSpaces(String text) {\n int spaces = 0;\n\n //count the spacex\n for(char c: text.toCharArray()){\n if(c==' ')\n spaces++;\n }\n\n //form word array\n String[] words = text.trim().split(\"\\\\s+\");\n int nWords = words.length;\n\n StringBuilder sb = new StringBuilder();\n int spacesToApply=0,extraSpaces=0;\n\n //if there is only 1 word, then all spaces will be at the end\n if(nWords == 1){\n extraSpaces=spaces;\n }\n\n //if there are multiple words, find the spaces to apply between words and also any extra space\n else{\n spacesToApply = spaces / (nWords-1);\n extraSpaces = spaces % (nWords-1);\n }\n\n //append every word and then apply spaces\n for(int i=0;i v;\n for (int i=0; i 1)?ct % (v.size()-1):ct;\n while(j--) text += ' ';\n\n return text;\n }\n};" }, { "title": "Valid Square", "algo_input": "Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.\n\nThe coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.\n\nA valid square has four equal sides with positive length and four equal angles (90-degree angles).\n\n \nExample 1:\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput: true\n\n\nExample 2:\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\nOutput: false\n\n\nExample 3:\n\nInput: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\nOutput: true\n\n\n \nConstraints:\n\n\n\tp1.length == p2.length == p3.length == p4.length == 2\n\t-104 <= xi, yi <= 104\n\n", "solution_py": "class Solution:\n def validSquare(self, p1, p2, p3, p4):\n\n def cal(A, B):\n return abs(A[0] - B[0]) + abs(A[1] - B[1])\n\n d = [cal(p1, p2), cal(p1, p3), cal(p1, p4), cal(p2, p3), cal(p2, p4), cal(p3, p4)]\n d.sort()\n\n return 0 < d[0] == d[1] == d[2] == d[3] and d[4] == d[5]", "solution_js": "var validSquare = function(p1, p2, p3, p4) {\n const distance = (a, b) => {\n const [aX, aY] = a;\n const [bX, bY] = b;\n return (aX - bX) ** 2 + (aY - bY) ** 2;\n };\n\n const set = new Set([\n distance(p1, p2),\n distance(p1, p3),\n distance(p1, p4),\n distance(p2, p3),\n distance(p2, p4),\n distance(p3, p4),\n ]);\n\n return !set.has(0) && set.size === 2;\n};", "solution_java": "class Solution {\n // This method returns true if the given 4 points form a square, false otherwise\n public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n // We use a set to store the distances between the points\n Set set = new HashSet();\n // Calculate the distances between all pairs of points and add them to the set\n set.add(distanceSquare(p1,p2));\n set.add(distanceSquare(p1,p3));\n set.add(distanceSquare(p1,p4));\n set.add(distanceSquare(p2,p3));\n set.add(distanceSquare(p2,p4));\n set.add(distanceSquare(p3,p4));\n // A square must have 4 equal sides, so the set must contain 2 different values (the lengths of the sides and the diagonals)\n // The set should not contain 0, as that would mean that two points have the same coordinates\n return !set.contains(0) && set.size() == 2;\n }\n // This method calculates the distance between two points and returns its square\n private int distanceSquare(int[] a, int[] b){\n // We use the Pythagorean theorem to calculate the distance between the points\n return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]);\n }\n}", "solution_c": "class Solution {\npublic:\n bool validSquare(vector& p1, vector& p2, vector& p3, vector& p4) {\n vector> p{p1, p2, p3, p4};\n unsigned short ans{0};\n double scal;\n vector bar(2);\n /* compute the barycenter */ \n bar[0] = (p1[0] + p2[0] + p3[0] + p4[0]) / 4.;\n bar[1] = (p1[1] + p2[1] + p3[1] + p4[1]) / 4.;\n const double length = pow(p1[0]-bar[0],2) + pow(p1[1] - bar[1],2);\n for (size_t i=0; i<4; i++) {if ((pow(p[i][0]-bar[0], 2) + pow(p[i][1] - bar[1], 2)) != length) return false; \n for (size_t j=i+1; j<4;j++){\n scal = (bar[0] - p[i][0])*(bar[0] - p[j][0]) + (bar[1] - p[i][1])*(bar[1]- p[j][1]);\n ans += (scal==0.)?1:0;}}\n return ans==4;\n }\n};" }, { "title": "Minimum Deletions to Make Array Beautiful", "algo_input": "You are given a 0-indexed integer array nums. The array nums is beautiful if:\n\n\n\tnums.length is even.\n\tnums[i] != nums[i + 1] for all i % 2 == 0.\n\n\nNote that an empty array is considered beautiful.\n\nYou can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.\n\nReturn the minimum number of elements to delete from nums to make it beautiful.\n\n \nExample 1:\n\nInput: nums = [1,1,2,3,5]\nOutput: 1\nExplanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.\n\n\nExample 2:\n\nInput: nums = [1,1,2,2,3,3]\nOutput: 2\nExplanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 105\n\n", "solution_py": "class Solution:\n def minDeletion(self, nums: List[int]) -> int:\n # Greedy !\n # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n # at the begining, we consider the num on the even index\n # when we delete a num, we need consider the num on the odd index\n # then repeat this process\n # at the end we check the requirement 1: nums.length is even or not\n \n n = len(nums)\n count = 0\n # flag is true then check the even index\n # flag is false then check the odd index\n flag = True\n \n for i in range(n):\n # check the even index\n if flag:\n if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = False\n # check the odd index\n elif not flag:\n if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]:\n count += 1\n flag = True\n \n curLength = n - count\n \n return count if curLength % 2 == 0 else count + 1", "solution_js": "var minDeletion = function(nums) {\n const n = nums.length;\n const res = [];\n\n for (let i = 0; i < n; ++i) {\n const num = nums[i];\n\n if (res.length % 2 === 0 || res.at(-1) != num) {\n res.push(num);\n }\n }\n\n if (res.length % 2 === 1) res.pop();\n\n return n - res.length;\n};", "solution_java": "class Solution {\n public int minDeletion(int[] nums) {\n\n int deletion = 0, n = nums.length;\n\n for (int i=0; i& nums) {\n int res=0,n=nums.size(),i;\n int flag=1;\n for(i=0;i bool:\n psum = {0:-1}\n currentSum = 0\n for i in range(len(nums)):\n currentSum += nums[i]\n remainder = currentSum % k\n if remainder not in psum:\n psum[remainder] = i\n else:\n if i - psum[remainder] > 1:\n return True\n return False", "solution_js": "var checkSubarraySum = function(nums, k) {\n\tconst hash = new Map([[0, -1]]);\n\tlet sum = 0;\n\n\tfor (let index = 0; index < nums.length; index++) {\n\t\tsum += nums[index];\n\t\tconst r = sum % k;\n\n\t\tif (hash.has(r)) {\n\t\t\tif (index - hash.get(r) > 1) return true;\n\t\t}\n\t\telse hash.set(r, index);\n\t}\n\treturn false;\n};", "solution_java": "class Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n boolean t[]=new boolean[nums.length+1];\n Arrays.fill(t,false);\n return help(nums.length,nums,k,0,0,t);\n }\n public boolean help(int i,int nums[],int k,int sum,int size,boolean t[]){\n if(size>=2&&sum%k==0){\n return true;\n }\n if(i==0){\n return false;\n }\n if(t[i-1]!=false){\n return t[i-1];\n }\n if(size>0){\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t);\n }\n return t[i]=help(i-1,nums,k,sum+nums[i-1],size+1,t)||help(i-1,nums,k,sum,size,t);\n }\n}\n---------------------------------------------------------------------------------------------\nclass Solution {\n public boolean checkSubarraySum(int[] nums, int k) {\n int sum=0;\n HashMaph=new HashMap<>();\n h.put(0,-1);\n for(int i=0;i=2){\n return true;\n }\n h.put(sum,h.getOrDefault(sum,i));\n } \n return false;\n }\n}", "solution_c": "class Solution {\npublic:\n bool checkSubarraySum(vector& nums, int k) {\n unordered_set s;\n int sum = 0;\n int pre = 0;\n for(int i = 0; i < nums.size(); i++)\n {\n sum += nums[i];\n int remainder = sum%k;\n if (s.find(remainder) != s.end())\n {\n return true;\n }\n s.insert(pre);\n pre = remainder;\n }\n return false;\n }" }, { "title": "Reconstruct Itinerary", "algo_input": "You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.\n\nAll of the tickets belong to a man who departs from \"JFK\", thus, the itinerary must begin with \"JFK\". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.\n\n\n\tFor example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"].\n\n\nYou may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.\n\n \nExample 1:\n\nInput: tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nOutput: [\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]\n\n\nExample 2:\n\nInput: tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nOutput: [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\nExplanation: Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.\n\n\n \nConstraints:\n\n\n\t1 <= tickets.length <= 300\n\ttickets[i].length == 2\n\tfromi.length == 3\n\ttoi.length == 3\n\tfromi and toi consist of uppercase English letters.\n\tfromi != toi\n\n", "solution_py": "class Solution: \n def findTicketsAdjList(self, tickets):\n ticket = {}\n for src,dest in tickets:\n if src in ticket:\n ticket[src].append(dest)\n else:\n ticket[src] = [dest]\n\n for src,dest in ticket.items():\n if len(dest)>1:\n ticket[src] = sorted(ticket[src], reverse=True)\n \n return ticket\n \n def reconstructItinerary(self, source, tickets, itinerary):\n if source in tickets:\n while tickets[source]: \n destination = tickets[source].pop()\n self.reconstructItinerary(destination, tickets, itinerary)\n itinerary.append(source)\n return itinerary\n \n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n if len(tickets)==1:\n if \"JFK\" not in tickets[0]:\n return []\n \n ticketsAdj = self.findTicketsAdjList(tickets)\n if \"JFK\" not in ticketsAdj:\n return []\n itinerary = []\n itinerary = self.reconstructItinerary(\"JFK\", ticketsAdj, itinerary)\n \n return itinerary[::-1]\n ", "solution_js": "function dfs(edges,s=`JFK`,ans=[`JFK`]){ //run dfs, starting node being `JFK`\n if(!edges[s] || edges[s].length==0){ //if currenctly reached node has its adjacent list empty\n let isAllTravelled=1;\n Object.values(edges).forEach(ele=> {if(ele.length>0) isAllTravelled=0}) // check if every edge has been travelled i.e all adjacentLists should be empty\n if(!isAllTravelled) return false; //returns false when there are more edges to travel , but from current node we cannot move anywhere else \n else return ans; // return true if from current node we cannot move anywhere else and all the edges have been travelled as well\n }\n \n let myAL= edges[s].sort(); // sort the Adjacency List of current node lexicographically\n for(let i=0;i{\n if(!edges[ticket[0]]){\n edges[ticket[0]]=[];\n }\n edges[ticket[0]].push(ticket[1]);\n })\n \n let ans= dfs(edges); // run dfs \n return ans;\n};", "solution_java": "class Solution {\n LinkedList res = new LinkedList<>();\n\n public List findItinerary(List> tickets) {\n HashMap> map= new HashMap<>();\n for(int i=0;i temp = new PriorityQueue();\n map.put(a,temp);\n }\n map.get(a).add(b);\n }\n\n dfs(\"JFK\",map);\n return res;\n\n }\n private void dfs(String departure,HashMap> map){\n PriorityQueue arrivals= map.get(departure);\n while(arrivals!=null &&!arrivals.isEmpty()){\n dfs(arrivals.poll(),map);\n }\n res.addFirst(departure);\n }\n}", "solution_c": "class Solution {\npublic:\n vector findItinerary(vector>& tickets) {\n unordered_map> myMap;\n stack myStack;\n vector ans;\n for (int i=0; i None:\n left, right = 0, len(self.intervals) - 1\n while left <= right:\n mid = (left + right) // 2\n e = self.intervals[mid]\n if e[0] <= val <= e[1]: return\n elif val < e[0]:right = mid - 1\n else:left = mid + 1\n pos = left\n self.intervals.insert(pos, [val, val])\n if pos + 1 < len(self.intervals) and val + 1 == self.intervals[pos+1][0]:\n self.intervals[pos][1] = self.intervals[pos+1][1]\n del self.intervals[pos+1]\n if pos - 1 >= 0 and val - 1 == self.intervals[pos-1][1]:\n self.intervals[pos-1][1] = self.intervals[pos][1]\n del self.intervals[pos]\n\n def getIntervals(self) -> List[List[int]]:\n return self.intervals", "solution_js": "var SummaryRanges = function() {\n this.tree = null // { val, left?, right? }\n};\n\n/** \n * @param {number} val\n * @return {void}\n */\nSummaryRanges.prototype.addNum = function(val) {\n if (!this.tree) {\n this.tree = { val }\n } else {\n let node = this.tree\n let parent, side\n while (node) {\n if (node.val === val) { return }\n parent = node\n side = node.val > val ? 'left' : 'right'\n node = node[side]\n }\n parent[side] = { val }\n }\n};\n\n/**\n * @return {number[][]}\n */\nSummaryRanges.prototype.getIntervals = function() {\n // travel from left to right\n // generate intervals\n\t// > (x === last[1] + 1) ? update last[1] : create a new one\n const travel = (node, check) => {\n if (!node) { return }\n travel(node.left, check)\n check(node.val)\n travel(node.right, check)\n }\n const result = []\n const check = val => {\n if (!result.length || val > result[result.length - 1][1] + 1) {\n\t\t\tresult.push([val, val])\n\t\t} else {\n\t\t\tresult[result.length - 1][1] = val\n }\n }\n travel(this.tree, check)\n return result\n};\n\n/** \n * Your SummaryRanges object will be instantiated and called as such:\n * var obj = new SummaryRanges()\n * obj.addNum(val)\n * var param_2 = obj.getIntervals()\n */", "solution_java": "class SummaryRanges {\n\n Map st;\n Map end;\n Set pending;\n int[][] prev = new int[0][];\n Set seen = new HashSet<>();\n int INVALID = -1;\n public SummaryRanges() {\n st = new HashMap<>();\n end= new HashMap<>();\n pending = new HashSet<>();\n }\n\n public void addNum(int val) { // [TC: O(1)]\n if (!seen.contains(val)){ // only add if not seen.\n pending.add(val); // pending processing list\n }\n }\n\n public int[][] getIntervals() { // [TC: O(pending list length (= k)) best case (all merges), O(n)+O(klogk) worst case (all inserts)]\n Set addSet = new HashSet<>();\n for (int n : pending){\n if (st.containsKey(n+1)&&end.containsKey(n-1)){ // merge intervals on both ends, a new interval form -> add to addSet\n int[] s = st.get(n+1);\n int[] e = end.get(n-1);\n int[] m = new int[]{e[0], s[1]};\n st.remove(n+1);\n end.remove(n-1);\n st.put(m[0], m);\n end.put(m[1], m);\n s[0]=e[0]=INVALID;\n addSet.remove(s); // may be in addSet, remove them\n addSet.remove(e);\n addSet.add(m);\n }else if (st.containsKey(n+1)){ // merge with the next interval, no other action required.\n st.get(n+1)[0]--;\n st.put(n, st.get(n+1));\n st.remove(n+1);\n }else if (end.containsKey(n-1)){ // merge with the previous interval, no other action required.\n end.get(n-1)[1]++;\n end.put(n, end.get(n-1));\n end.remove(n-1);\n }else{ // new interval -> add to AddSet\n int[] m = new int[]{n, n};\n addSet.add(m);\n st.put(n, m);\n end.put(n, m);\n }\n }\n\n seen.addAll(pending);\n pending.clear(); // remember to clear the pending list.\n\n if (!addSet.isEmpty()){ // IF there is no new intervals to insert, we SKIP this.\n List addList = new ArrayList<>(addSet);\n addList.sort(Comparator.comparingInt(o -> o[0]));\n int i = 0, j = 0; // two pointers because both prev & addList are sorted.\n List ans = new ArrayList<>();\n while(i < prev.length || j < addList.size()){\n if (i < prev.length && prev[i][0]==INVALID){\n i++;\n }else if (j == addList.size() || i < prev.length && prev[i][0]addList.get(j)[0]){\n ans.add(addList.get(j++));\n }\n }\n prev = ans.toArray(new int[0][]);\n }\n\n return prev;\n }\n}", "solution_c": "class SummaryRanges {\npublic:\n\n struct DSU {\n mapparent;\n mapsz;\n\n int find_parent(int a) {\n if(!parent.count(a)) {\n parent[a] = a;\n sz[a] = 1;\n }\n\n if(parent[a] == a) return a;\n return parent[a] = find_parent(parent[a]);\n }\n\n void union_sets(int a, int b) {\n if(!parent.count(a)) {\n parent[a] = a;\n sz[a] = 1;\n }\n\n if(!parent.count(b)) {\n parent[b] = b;\n sz[b] = 1;\n }\n\n\n a = find_parent(a);\n b = find_parent(b);\n\n if(a == b) return;\n\n parent[b] = a;\n sz[a] += sz[b];\n\n\n }\n\n void add(int a) {\n\n\n if(!parent.count(a)) {\n parent[a] = a;\n sz[a] = 1;\n } else return;\n\n\n\n if(parent.count(a + 1)) {\n union_sets(a, a + 1);\n }\n if(parent.count(a - 1)) {\n union_sets(a - 1, a);\n }\n }\n\n vector>getIntervals() {\n vector>intervals;\n for(auto [a, b]: parent) {\n if(a == b) {\n intervals.push_back({a, a + sz[a] - 1});\n }\n }\n\n return intervals;\n }\n\n };\n \n DSU dsu;\n\n SummaryRanges() {\n this->dsu = DSU();\n }\n \n void addNum(int val) {\n dsu.add(val);\n }\n \n vector> getIntervals() {\n return dsu.getIntervals();\n }\n};" }, { "title": "Execution of All Suffix Instructions Staying in a Grid", "algo_input": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).\n\nYou are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).\n\nThe robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:\n\n\n\tThe next instruction will move the robot off the grid.\n\tThere are no more instructions left to execute.\n\n\nReturn an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.\n\n \nExample 1:\n\nInput: n = 3, startPos = [0,1], s = \"RRDDLU\"\nOutput: [1,5,4,3,1,0]\nExplanation: Starting from startPos and beginning execution from the ith instruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st: \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th: \"U\". If moving up, it would move off the grid.\n\n\nExample 2:\n\nInput: n = 2, startPos = [1,1], s = \"LURD\"\nOutput: [4,1,0,0]\nExplanation:\n- 0th: \"LURD\".\n- 1st: \"URD\".\n- 2nd: \"RD\".\n- 3rd: \"D\".\n\n\nExample 3:\n\nInput: n = 1, startPos = [0,0], s = \"LRUD\"\nOutput: [0,0,0,0]\nExplanation: No matter which instruction the robot begins execution from, it would move off the grid.\n\n\n \nConstraints:\n\n\n\tm == s.length\n\t1 <= n, m <= 500\n\tstartPos.length == 2\n\t0 <= startrow, startcol < n\n\ts consists of 'L', 'R', 'U', and 'D'.\n\n", "solution_py": "class Solution:\n def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:\n result = []\n for idx in range(len(s)):\n count, row, col = 0, startPos[0],startPos[1]\n while idx < len(s):\n if s[idx] == 'D':\n row += 1\n if row >= n:\n break\n count += 1\n elif s[idx] == 'U':\n row -= 1\n if row < 0:\n break\n count += 1\n elif s[idx] == 'R':\n col += 1\n if col >= n:\n break\n count += 1\n else:\n col -= 1\n if col < 0:\n break\n count += 1\n idx += 1\n result.append(count)\n return result", "solution_js": "// Time: O(n^2)\nvar executeInstructions = function(n, startPos, s) {\n let answers = [];\n for (i = 0; i < s.length; i++) {\n let movement = 0;\n let [row, col] = startPos;\n for (j = i; j < s.length; j++) {\n if (s[j] == \"R\") col++;\n else if (s[j] == \"L\") col--;\n else if (s[j] == \"D\") row++;\n else row--;\n if(row>n-1 || col > n-1 || row < 0 || col < 0) {\n break;\n }\n movement++;\n }\n answers[i] = movement;\n }\n return answers;\n};", "solution_java": "class Solution {\n public int[] executeInstructions(int n, int[] startPos, String s) {\n //Make array of length equal to string length\n int ans[]=new int[s.length()];\n\n //Now use two for loops\n for(int i=0;i=n || yIndex<0 || yIndex>=n){\n break;\n }\n else{\n countMoves++;\n }\n }\n\n ans[i]=countMoves;\n\n }\n return ans;\n\n }\n}", "solution_c": "class Solution {\npublic:\n\tvector executeInstructions(int n, vector& start, string s) {\n\t\tint m=s.size();\n\t\tvector ans(m);\n\t\tfor(int l=0;l=0){\n\t\t\t\t\t\tj--;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t}\n\t\t\t\telse if(s[k]=='R'){\n\t\t\t\t\tif(j+1=0){\n\t\t\t\t\t\ti--;\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\t\t\t\t\telse break;\n\t\t\t\t} \n\t\t\t\telse{\n\t\t\t\t\tif(i+1 List[List[int]]:\n def find(v, parent):\n if parent[v] != v:\n parent[v] = find(parent[v], parent)\n return parent[v]\n def union(u,v, parent):\n parent[find(u,parent)] = find(v,parent)\n edges = [(u,v,w,i) for i, (u,v,w) in enumerate(edges)]\n edges.sort(key = lambda e:e[2])\n def find_mst_without_this_edge(idx):\n parent = list(range(n))\n res = 0\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx: continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n def find_mst_with_this_edge(idx):\n parent = list(range(n))\n u0, v0, w0, _ = edges[idx]\n res = w0\n union(u0,v0,parent)\n for i, (u, v, w, _) in enumerate(edges):\n if i == idx:\n continue\n if find(u, parent) != find(v, parent):\n res += w\n union(u, v, parent)\n root = find(0, parent)\n return res if all(find(i, parent) == root for i in range(n)) else float('inf')\n base_mst_wgt = find_mst_without_this_edge(-1)\n cri, pcri = set(), set()\n for i in range(len(edges)):\n wgt_excl = find_mst_without_this_edge(i)\n if wgt_excl > base_mst_wgt:\n cri.add(edges[i][3])\n else:\n wgt_incl = find_mst_with_this_edge(i)\n if wgt_incl == base_mst_wgt:\n pcri.add(edges[i][3])\n return [cri, pcri]", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @return {number[][]}\n */\nvar findCriticalAndPseudoCriticalEdges = function(n, edges) {\n\t// find and union utils\n const find = (x, parent) => {\n if (parent[x] === -1) { return x }\n const y = find(parent[x], parent)\n parent[x] = y\n return y\n }\n const union = (a, b, parent) => {\n a = find(a, parent)\n b = find(b, parent)\n if (a === b) { return false }\n parent[a] = b\n return true\n }\n\n\t// sort and group edges by cost\n const map = {}\n edges.forEach(([a, b, cost], i) => {\n map[cost] = map[cost] || []\n map[cost].push([a, b, i])\n })\n const costs = Object.keys(map).sort((a, b) => a - b)\n\n\t// check by group\n const check = (edges, parent) => {\n let nextParent\n let count\n\n\t\t// travel with a skipped point\n\t\t// if skip === -1, skip nothing and update count and nextParent.\n const travel = skip => {\n const p = [...parent]\n const result = []\n edges.forEach(([a, b, i]) => {\n if (i === skip) { return }\n if (union(a, b, p)) { result.push(i) }\n })\n if (skip === -1) {\n count = result.length\n nextParent = p\n }\n return result\n }\n\n\t\t// get default count and nextParent.\n travel(-1)\n\n\t\t// special case: there is only one edge in this group\n if (edges.length === 1) {\n if (count === 0) { return [[], [], 0, parent] }\n return [[edges[0][2]], [], 1, nextParent]\n }\n\n\t\t// aList -> critical, bList -> pseudo\n const aList = {}\n const bList = {}\n edges.forEach(([a, b, i]) => {\n if (find(a, parent) === find(b, parent)) { return }\n const result = travel(i)\n result.length < count ? aList[i] = true : bList[i] = true\n })\n return [Object.keys(aList), Object.keys(bList), count, nextParent]\n }\n\n\t// init traversal state\n const critical = []\n const pseudo = []\n let count = 0\n let parent = new Array(n).fill(-1)\n\n\t// travel by cost group until all points visited\n for (let i = 0; i < costs.length; i++) {\n const [aList, bList, newCount, nextParent] = check(map[costs[i]], parent)\n critical.push(...aList)\n pseudo.push(...bList)\n count += newCount\n parent = nextParent\n if (count === n - 1) { break }\n }\n\n\treturn [critical, pseudo]\n};", "solution_java": "class Solution {\n static class UnionFind{\n int[]parent;\n int[]rank;\n int comp = 0;\n UnionFind(int n){\n parent = new int[n];\n rank = new int[n];\n comp = n;\n for(int i=0;i{\n int u;\n int v;\n int wt;\n Edge(int u,int v,int wt){\n this.u = u;\n this.v = v;\n this.wt = wt;\n }\n public int compareTo(Edge o){\n return this.wt - o.wt;\n } \n }\n public int buildMST(int n,int[][]edges,int[]edgeSkip,int[]edgePick){\n PriorityQueue pq = new PriorityQueue<>();\n \n for(int[]edge : edges){\n if(edge == edgeSkip){\n continue;\n }else if(edge == edgePick){\n continue;\n }\n int u = edge[0];\n int v = edge[1];\n int wt = edge[2];\n pq.add(new Edge(u,v,wt));\n }\n \n UnionFind uf = new UnionFind(n);\n int cost = 0;\n \n if(edgePick != null){\n uf.union(edgePick[0],edgePick[1]);\n cost += edgePick[2];\n }\n while(pq.size() > 0){\n Edge rem = pq.remove();\n if(uf.union(rem.u,rem.v) == true){\n cost += rem.wt;\n }\n }\n \n if(uf.isConnected() == true){\n return cost;\n }else{\n return Integer.MAX_VALUE;\n }\n }\n \n public List> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n int mstCost = buildMST(n,edges,null,null);\n \n ArrayList critical = new ArrayList<>();\n ArrayList pcritical = new ArrayList<>();\n \n for(int i=0;i mstCost){\n critical.add(i); //Critical edge index\n }else{\n int mstCostWithEdge = buildMST(n,edges,null,edge);\n if(mstCostWithEdge > mstCost){\n //redundant\n }else{\n pcritical.add(i); //pseduo critical edge index\n }\n }\n }\n \n List> res = new ArrayList<>();\n res.add(critical);\n res.add(pcritical);\n return res;\n }\n}", "solution_c": "class UnionFind{\nprivate:\n vector parent_;\n vector rank_;\n int sets_;\npublic:\n UnionFind(int n)\n {\n init(n);\n }\n void init(int n)\n {\n sets_ = n;\n parent_.resize(n);\n rank_.resize(n);\n iota(parent_.begin(),parent_.end(),0);\n fill(rank_.begin(),rank_.end(),1);\n }\n int find(int u)\n {\n return parent_[u] == u ? u: parent_[u] = find(parent_[u]);\n }\n bool join(int u,int v)\n {\n u = find(u);\n v = find(v);\n\n if(u==v)\n {\n return false;\n }\n \n if(rank_[u] edges_idx_;\n int kruskal(const int n, const int removed_edge_idx,const int init_edge_idx,\n const vector> &edges)\n {\n UnionFind graph(n);\n int edges_size = edges.size();\n int total = 0;\n\n if(init_edge_idx != -1)\n {\n graph.join(edges[init_edge_idx][0],edges[init_edge_idx][1]);\n total += edges[init_edge_idx][2];\n }\n\n \n for(int i = 0; i> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) {\n int edges_size = edges.size();\n\n edges_idx_.resize(edges_size);\n\n iota(edges_idx_.begin(),edges_idx_.end(),0);\n \n sort(edges_idx_.begin(),edges_idx_.end(),[&edges](int a, int b){\n return edges[a][2] < edges[b][2];\n });\n\n int mst = kruskal(n,-1,-1,edges);\n \n\n vector critical;\n vector psudo;\n \n for(int i = 0; i< edges_size; ++i)\n {\n int edge_idx = edges_idx_[i];\n int total = kruskal(n,-1,edge_idx,edges);\n \n if(total == mst)\n {\n total = kruskal(n,edge_idx,-1,edges);\n if(total > mst)\n {\n critical.push_back(edge_idx);\n }\n else{\n psudo.push_back(edge_idx);\n }\n }\n }\n\n return {critical,psudo};\n \n }\n};" }, { "title": "4Sum", "algo_input": "Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:\n\n\n\t0 <= a, b, c, d < n\n\ta, b, c, and d are distinct.\n\tnums[a] + nums[b] + nums[c] + nums[d] == target\n\n\nYou may return the answer in any order.\n\n \nExample 1:\n\nInput: nums = [1,0,-1,0,-2,2], target = 0\nOutput: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n\n\nExample 2:\n\nInput: nums = [2,2,2,2,2], target = 8\nOutput: [[2,2,2,2]]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 200\n\t-109 <= nums[i] <= 109\n\t-109 <= target <= 109\n\n", "solution_py": "class Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n \n if len(nums) < 4: return []\n \n nums.sort()\n res = []\n \n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n l = j+1\n r = len(nums)-1\n while l < r:\n\n sum_ = nums[i]+nums[j]+nums[l]+nums[r]\n a = [nums[i], nums[j], nums[l], nums[r]]\n \n if sum_ == target and a not in res:\n res.append(a)\n \n if sum_ > target:\n r -= 1\n \n else:\n l += 1\n while l < r and nums[l-1] == nums[l]:\n l += 1\n \n return res\n \n # An Upvote will be encouraging\n \n ", "solution_js": "var fourSum = function(nums, target) {\n nums.sort((a, b) => a - b);\n const res = [];\n \n for(let i=0; i target) \n max--;\n else\n min++\n }\n while(nums[j] === nums[j+1]) j++;\n }\n while(nums[i] === nums[i+1]) i++;\n }\n \n return res;\n};", "solution_java": "class Solution {\n public List> fourSum(int[] nums, int target) {\n Arrays.sort(nums);\n List> llans = new LinkedList<>();\n if(nums == null || nums.length <= 2){\n return llans;\n }\n for(int i=0;i ll = new LinkedList<>();\n ll.add(nums[i]);\n ll.add(nums[j]);\n ll.add(nums[l]);\n ll.add(nums[r]);\n llans.add(ll);\n\n while( l> fourSum(vector& nums, int target) {\n\n int n = nums.size();\n\n vector > answer;\n\n if(n<4) return answer;\n\n sort(nums.begin(),nums.end());\n\n for(int i=0;i vect{nums[i] , nums[j] , nums[left] , nums[right]};\n answer.push_back(vect);\n\n //skipping duplicates while moving right\n int k = 1;\n while((left+k)=n) break;\n else left = left+k;\n\n //skipping duplicates while moving left\n k = 1;\n while((right-k)>=0 && nums[right-k]==nums[right]) ++k;\n\n if((right-k)<0) break;\n else right = right-k;\n\n }\n else{\n\n if(x>nums[left]+nums[right]){\n\n //skipping duplicates while moving right\n int k = 1;\n while((left+k)=n) break;\n else left = left+k;\n\n }\n else{\n\n //skipping duplicates while moving left\n int k = 1;\n while((right-k)>=0 && nums[right-k]==nums[right]) ++k;\n\n if((right-k)<0) break;\n else right = right-k;\n\n }\n\n }\n\n }\n\n //skipping duplicates while moving right\n int k = 1;\n while((j+k)=n) break;\n else j = j+k;\n\n }\n\n //skipping duplicates while moving right\n int k = 1;\n while((i+k)=n) break;\n else i = i+k;\n }\n\n return answer;\n }\n};" }, { "title": "Minimum Area Rectangle", "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 a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.\n\n \nExample 1:\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput: 4\n\n\nExample 2:\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput: 2\n\n\n \nConstraints:\n\n\n\t1 <= points.length <= 500\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 minAreaRect(self, points: List[List[int]]) -> int:\n points = sorted(points, key=lambda item: (item[0], item[1]))\n cols = defaultdict(list)\n \n for x,y in points:\n cols[x].append(y)\n \n lastx = {}\n ans = float('inf')\n \n for x in cols:\n col = cols[x]\n for i, y1 in enumerate(col):\n for j in range(i):\n y2 = col[j]\n if (y2,y1) in lastx:\n ans = min(ans, abs((x-lastx[y2,y1])*(y2-y1)))\n lastx[y2,y1] = x\n \n return 0 if ans==float('inf') else ans", "solution_js": "var minAreaRect = function(points) {\n const mapOfPoints = new Map();\n let minArea = Infinity;\n for(const [x,y] of points) {\n let keyString = `${x}:${y}`\n mapOfPoints.set(keyString, [x, y]);\n }\n for(const [xLeftBottom, yLeftBottom] of points) {\n for(const [xRightTop, yRightTop] of points) {\n if(!foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop)) continue;\n let leftTopCorner = `${xLeftBottom}:${yRightTop}`;\n let rightBottomCorner = `${xRightTop}:${yLeftBottom}`;\n \n if(mapOfPoints.has(leftTopCorner) && mapOfPoints.has(rightBottomCorner)) {\n const x2 = mapOfPoints.get(rightBottomCorner)[0];\n const x1 = xLeftBottom;\n const y1 = yLeftBottom;\n const y2 = mapOfPoints.get(leftTopCorner)[1]\n const area = calculateArea(x1, x2, y1, y2);\n \n minArea = Math.min(minArea,area);\n }\n }\n \n }\n return minArea === Infinity ? 0 : minArea;\n};\n\n\nfunction calculateArea(x1, x2, y1, y2) {\n return ((x2-x1) * (y2-y1))\n}\n\nfunction foundDiagonal(xLeftBottom, yLeftBottom, xRightTop, yRightTop) {\n return (xRightTop > xLeftBottom && yRightTop > yLeftBottom);\n}", "solution_java": "class Solution {\n\n public int minAreaRect(int[][] points) {\n\n Map> map = new HashMap<>();\n\n\t\t// Group the points by x coordinates\n for (int[] point : points) {\n if (!map.containsKey(point[0])) map.put(point[0], new HashSet<>());\n map.get(point[0]).add(point[1]);\n }\n\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < points.length - 1; i++) {\n\n int x1 = points[i][0];\n int y1 = points[i][1];\n for (int j = i + 1; j < points.length; j++) {\n int x2 = points[j][0];\n int y2 = points[j][1];\n if (x1 == x2 || y1 == y2) // We are looking for diagonal point, so if j is neighbour point, then continue\n continue;\n\n // Note - We are calculating area first (before checking whether these points form the correct rectangle), because\n // cost of checking rectangle is very higher than calculating area. So if area less than the prev area (min), then only \n // it makes sense to check rectangle and override min (if these points forms the correct rectangle)\n int area = Math.abs(x1 - x2) * Math.abs(y1 - y2);\n if (area < min) {\n boolean isRectangle = map.get(x1).contains(y2) && map.get(x2).contains(y1);\n if (isRectangle) min = area;\n }\n }\n }\n\n return min == Integer.MAX_VALUE ? 0 : min;\n }\n}", "solution_c": "class Solution {\npublic:\n int minAreaRect(vector>& points) {\n unordered_map> pts;\n for(auto p : points)\n {\n pts[p[0]].insert(p[1]);\n }\n \n int minArea = INT_MAX;\n int n = points.size();\n for(int i=0; i0 && pts[p2[0]].count(p1[1])>0) {\n minArea = min(minArea, (abs(p1[0]-p2[0]) * abs(p1[1]-p2[1])) );\n }\n }\n \n }\n }\n return minArea == INT_MAX ? 0 : minArea;\n }\n};" }, { "title": "Sort Array By Parity II", "algo_input": "Given an array of integers nums, half of the integers in nums are odd, and the other half are even.\n\nSort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.\n\nReturn any answer array that satisfies this condition.\n\n \nExample 1:\n\nInput: nums = [4,2,5,7]\nOutput: [4,5,2,7]\nExplanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n\n\nExample 2:\n\nInput: nums = [2,3]\nOutput: [2,3]\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 2 * 104\n\tnums.length is even.\n\tHalf of the integers in nums are even.\n\t0 <= nums[i] <= 1000\n\n\n \nFollow Up: Could you solve it in-place?\n", "solution_py": "class Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n arr = [None]*len(nums)\n even,odd = 0,1\n for i in(nums):\n if i % 2 == 0:\n arr[even] = i\n even +=2\n for i in (nums):\n if i % 2 != 0:\n arr[odd] = i\n odd+=2\n return arr", "solution_js": "var sortArrayByParityII = function(nums) {\n let arrEven = []\n let arrOdd = []\n let result = []\n for(let i in nums){\n nums[i]%2==0 ? arrEven.push(nums[i]) : arrOdd.push(nums[i])\n }\n for(let i in arrEven){\n result.push(arrEven[i])\n result.push(arrOdd[i])\n }\n return result\n};", "solution_java": "class Solution {\n public int[] sortArrayByParityII(int[] nums) {\n \n int[] ans = new int[nums.length];\n \n int even_pointer = 0;\n int odd_pointer = 1;\n \n for(int i = 0; i < nums.length; i++){\n \n if(nums[i] % 2 == 0){\n ans[even_pointer] = nums[i];\n even_pointer += 2;\n } else{\n ans[odd_pointer] = nums[i];\n odd_pointer += 2;\n }\n \n }\n \n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector sortArrayByParityII(vector& nums) {\n\n vectorans(nums.size());\n\n int even_idx=0;\n int odd_idx=1;\n\n for(int i=0;i int:\n return abs((date.fromisoformat(date2) - date.fromisoformat(date1)).days)", "solution_js": "var daysBetweenDates = function(date1, date2) {\n let miliSecondInaDay = 24*60*60*1000;\n if(date1>date2) return (new Date(date1) - new Date(date2)) / miliSecondInaDay\n else return (new Date(date2) - new Date(date1)) / miliSecondInaDay\n};", "solution_java": "class Solution {\n public int daysBetweenDates(String date1, String date2) {\n String[] d1 = date1.split(\"-\");\n String[] d2 = date2.split(\"-\");\n return (int)Math.abs(\n daysFrom1971(Integer.parseInt(d1[0]), Integer.parseInt(d1[1]), Integer.parseInt(d1[2]))\n - daysFrom1971(Integer.parseInt(d2[0]), Integer.parseInt(d2[1]), Integer.parseInt(d2[2])));\n }\n private int daysFrom1971(int year, int month, int day) {\n int total = 0;\n\t\t// count years first\n total += (year - 1971) * 365;\n for (int i = 1972; i < year; i += 4) {\n if (isLeapYear(i)) total++;\n } \n int feb = isLeapYear(year) ? 29 : 28;\n\t\t// sum months and days\n switch (month) {\n case 12: \n total += 30; // 11\n case 11:\n total += 31; // 10\n case 10: \n total += 30; // 9\n case 9:\n total += 31; // 8\n case 8:\n total += 31; // 7\n case 7: \n total += 30; // 6\n case 6:\n total += 31; // 5\n case 5:\n total += 30; // 4\n case 4: \n total += 31; // 3\n case 3: \n total += feb; // 2\n case 2:\n total += 31;\n case 1:\n total += day; \n }\n return total;\n }\n private boolean isLeapYear(int i) {\n return (i % 4 == 0) && ((i % 100 == 0 && i % 400 == 0) || i % 100 != 0);\n }\n}", "solution_c": "class Solution\n{\npublic:\n int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n bool isLeap(int y)\n {\n return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));\n }\n int calc(string s)\n {\n int y = stoi(s.substr(0, 4));\n int m = stoi(s.substr(5, 2));\n int d = stoi(s.substr(8));\n for (int i = 1971; i < y; i++)\n d += isLeap(i) ? 366 : 365;\n d += accumulate(begin(days), begin(days) + m - 1, 0);\n d += (m > 2 && isLeap(y)) ? 1 : 0;\n return d;\n }\n int daysBetweenDates(string date1, string date2)\n {\n int ans = abs(calc(date2) - calc(date1));\n return ans;\n }\n};" }, { "title": "Super Pow", "algo_input": "Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.\n\n \nExample 1:\n\nInput: a = 2, b = [3]\nOutput: 8\n\n\nExample 2:\n\nInput: a = 2, b = [1,0]\nOutput: 1024\n\n\nExample 3:\n\nInput: a = 1, b = [4,3,3,8,5,2]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= a <= 231 - 1\n\t1 <= b.length <= 2000\n\t0 <= b[i] <= 9\n\tb does not contain leading zeros.\n\n", "solution_py": "class Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n mod = 1337\n ans = 1\n\n for power in b:\n ans = ((pow(ans,10)%mod)*(pow(a,power)%mod))%mod\n\n return ans", "solution_js": "var superPow = function(a, b) {\n const MOD = 1337;\n const pow = (num, n) => {\n let result = 1;\n for (let index = 0; index < n; index++) {\n result = result * num % MOD;\n }\n return result;\n };\n\n return b.reduceRight((result, n) => {\n a %= MOD;\n const powNum = result * pow(a, n) % MOD;\n\n a = pow(a, 10);\n return powNum;\n }, 1);\n};", "solution_java": "import java.math.BigInteger;\nclass Solution {\n public int superPow(int a, int[] b) {\n StringBuilder bigNum = new StringBuilder();\n Arrays.stream(b).forEach(i -> bigNum.append(i));\n \n return \n BigInteger.valueOf(a)\n .modPow(new BigInteger(bigNum.toString()), BigInteger.valueOf(1337))\n .intValue();\n }\n}", "solution_c": "class Solution {\npublic:\n int binaryExp(int a, int b, int M)\n {\n int ans = 1;\n a %= M;\n while(b)\n {\n if(b&1) ans = (ans * a)%M;\n a = (a*a)%M, b = b>>1;\n }\n return ans;\n }\n \n int superPow(int a, vector& b) {\n int bmod = 0;\n for(auto it : b)\n {\n bmod = (bmod * 10 + it)%1140;\n }\n \n return binaryExp(a, bmod, 1337);\n }\n};" }, { "title": "Construct Binary Search Tree from Preorder Traversal", "algo_input": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.\n\nIt is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.\n\nA binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.\n\nA preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.\n\n \nExample 1:\n\nInput: preorder = [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\n\n\nExample 2:\n\nInput: preorder = [1,3]\nOutput: [1,null,3]\n\n\n \nConstraints:\n\n\n\t1 <= preorder.length <= 100\n\t1 <= preorder[i] <= 1000\n\tAll the values of preorder are unique.\n\n", "solution_py": "class Solution:\n\tdef bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n\t\tif not preorder:\n\t\t\treturn None\n\t\tnode = preorder.pop(0)\n\t\troot = TreeNode(node)\n\t\tl = []\n\t\tr = []\n\n\t\tfor val in preorder:\n\t\t\tif val < node:\n\t\t\t\tl.append(val)\n\t\t\telse:\n\t\t\t\tr.append(val)\n\n\t\troot.left = self.bstFromPreorder(l)\n\t\troot.right = self.bstFromPreorder(r)\n\t\treturn root", "solution_js": "var bstFromPreorder = function(preorder) {\n let head = new TreeNode(preorder[0]);\n for (let i = 1, curr; icurr.val) \n if (curr.right !=null) { curr = curr.right; }\n else { curr.right = new TreeNode(preorder[i]); break; }\n else\n if (curr.left !=null) { curr = curr.left; }\n else { curr.left = new TreeNode(preorder[i]); break; }\n } \n } \n return head; \n};", "solution_java": "class Solution {\n public TreeNode bstFromPreorder(int[] preorder) {\n return bst(preorder, 0, preorder.length-1);\n }\n\n public TreeNode bst(int[] preorder, int start, int end){\n if(start > end) return null;\n\n TreeNode root = new TreeNode(preorder[start]);\n int breakPoint = start+1;\n while(breakPoint <= end && preorder[breakPoint] < preorder[start]){\n breakPoint++;\n }\n\n root.left = bst(preorder, start+1, breakPoint-1);\n root.right = bst(preorder, breakPoint, end);\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 TreeNode* help(int &i,vector& preorder, int bound ){\n if(i==preorder.size() || preorder[i] > bound)\n return NULL;\n TreeNode* root = new TreeNode(preorder[i++]);\n root->left = help(i,preorder,root->val);\n root->right = help(i,preorder,bound);\n return root;\n }\n TreeNode* bstFromPreorder(vector& preorder) {\n \n int i=0;\n return help(i,preorder,INT_MAX);\n }\n};" }, { "title": "Palindrome Partitioning", "algo_input": "Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.\n\nA palindrome string is a string that reads the same backward as forward.\n\n \nExample 1:\nInput: s = \"aab\"\nOutput: [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\nExample 2:\nInput: s = \"a\"\nOutput: [[\"a\"]]\n\n \nConstraints:\n\n\n\t1 <= s.length <= 16\n\ts contains only lowercase English letters.\n\n", "solution_py": "\"\"\"\nwe can approach this problem using manacher's algorithm with backtracking and recursion\n\"\"\"\nclass Solution:\n def partition(self, s: str) -> List[List[str]]:\n lookup = {\"\": [[]]}\n def lps(s):\n if s in lookup:\n return lookup[s]\n\n final_res = []\n result_set = set()\n for k in range(len(s)):\n i, j = k, k\n\n # check for odd length palindromes\n while i>= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n\n # check for even length palindromes\n i, j = k, k+1\n while i >= 0 and j < len(s) and s[i] == s[j]:\n # palindrome found\n res = []\n for partition in lps(s[:i]):\n res.append(partition + [s[i:j+1]])\n for partition in res:\n for part in lps(s[j+1:]):\n temp = partition + part\n if tuple(temp) not in result_set:\n result_set.add(tuple(temp))\n final_res.append(temp)\n i-=1\n j+=1\n lookup[s] = final_res\n return final_res\n return lps(s)", "solution_js": "var partition = function(s) {\n let result = []\n backtrack(0, [], s, result)\n return result\n};\n\nfunction backtrack(i, partition, s, result){\n if(i === s.length){\n result.push([...partition])\n return\n }\n\n for(let j=i;j> partition(String s) {\n List> result = new ArrayList<>();\n if(s == null || s.length() == 0)\n return result;\n helper(s, 0, new ArrayList(), result);\n return result;\n }\n private void helper(String s, int start, List list, List> result){\n if(start == s.length()){\n result.add(new ArrayList<>(list));\n return;\n }\n for(int i = start; i < s.length(); i++){\n if(isPalindrome(s, start, i)){\n list.add(s.substring(start, i+1));\n helper(s, i+1, list, result);\n list.remove(list.size()-1);\n }\n }\n }\n private boolean isPalindrome(String s, int start, int end){\n while(start < end){\n if(s.charAt(start++) != s.charAt(end--))\n return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool check(string k)\n {\n string l=k;\n reverse(l.begin(),l.end());\n if(k==l)return true;\n return false;\n }\n void solve(string &s,vector>&ans,\n vectortemp,int pos)\n {\n if(pos>=s.size()){ans.push_back(temp); return;}\n string m;\n for(int i=pos;i> partition(string s) {\n vector>ans;\n vectortemp;\n solve(s,ans,temp,0);\n return ans;\n }\n};" }, { "title": "Element Appearing More Than 25% In Sorted Array", "algo_input": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.\n\n \nExample 1:\n\nInput: arr = [1,2,2,6,6,6,6,7,10]\nOutput: 6\n\n\nExample 2:\n\nInput: arr = [1,1]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t1 <= arr.length <= 104\n\t0 <= arr[i] <= 105\n\n", "solution_py": "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n l=len(arr)\n c=(l//4)+1\n d={}\n for i in arr:\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n if d[i]>=c:\n return i", "solution_js": "function binarySearch(array, target, findFirst) {\n function helper(start, end) {\n if (start > end) {\n return -1;\n } \n \n const middle = Math.floor((start + end) / 2);\n const value = array[middle];\n \n if (value === target) {\n if (findFirst) {\n if (middle === 0 || array[middle - 1] !== value) {\n return middle;\n }\n \n return helper(start, middle - 1);\n } else {\n if (middle === array.length -1 || array[middle + 1] !== value) {\n return middle;\n }\n \n return helper(middle + 1, end);\n }\n } else if (value < target) {\n return helper(middle + 1, end); \n }\n \n return helper(start, middle - 1);\n }\n \n return helper(0, array.length - 1)\n}\n\nconst findFirstOccurance = (array, target) => binarySearch(array, target, true);\nconst findLastOccurance = (array, target) => binarySearch(array, target, false);\n\nvar findSpecialInteger = function(arr) {\n for (const i of [Math.floor(arr.length / 4), Math.floor(arr.length / 2), Math.floor(3 * arr.length / 4)]) {\n const firstOccurance = findFirstOccurance(arr, arr[i]);\n const lastOccurance = findLastOccurance(arr, arr[i]);\n \n if (lastOccurance - firstOccurance + 1 > arr.length / 4) {\n return arr[i]\n }\n }\n \n return -1;\n};", "solution_java": "class Solution {\n public int findSpecialInteger(int[] arr) {\n if (arr.length == 1) {\n return arr[0];\n }\n int count = (int) Math.ceil(arr.length / 4);\n System.out.println(count);\n\n Map map = new HashMap<>();\n\n for (Integer i : arr) {\n map.put(i, map.getOrDefault(i, 0) + 1);\n if (map.get(i) > count) {\n return i;\n }\n }\n return -1;\n }\n}", "solution_c": "class Solution {\npublic:\n int findSpecialInteger(vector& arr) {\n \n int freq = 0.25 * arr.size();\n mapm;\n for(int i: arr)\n m[i]++;\n \n int k;\n for(auto i: m)\n {\n if(i.second > freq)\n {\n k = i.first;\n break;\n }\n }\n return k;\n }\n};" }, { "title": "Where Will the Ball Fall", "algo_input": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.\n\nEach cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.\n\n\n\tA board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.\n\tA board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.\n\n\nWe drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box.\n\nReturn an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.\n\n \nExample 1:\n\n\n\nInput: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput: [1,-1,-1,-1,-1]\nExplanation: This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\n\n\nExample 2:\n\nInput: grid = [[-1]]\nOutput: [-1]\nExplanation: The ball gets stuck against the left wall.\n\n\nExample 3:\n\nInput: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput: [0,1,2,3,4,-1]\n\n\n \nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 <= m, n <= 100\n\tgrid[i][j] is 1 or -1.\n\n", "solution_py": "class Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n\n m,n=len(grid),len(grid[0])\n for i in range(m):\n grid[i].insert(0,1)\n grid[i].append(-1)\n res=[]\n\n for k in range(1,n+1):\n i , j = 0 , k\n struck = False\n while i=grid[0].length)\n return -1;\n\n if(grid[i][j]==1 && j+1=0 && grid[i][j-1]==-1)\n return dfs(grid,i+1,j-1);\n\n return -1;\n }\n public int[] findBall(int[][] grid) {\n int m = grid[0].length;\n int[] ar = new int[m];\n\n for(int j=0;j>&grid,bool top,int i,int j)\n {\n if(top==0&&i==grid.size()-1)return j;\n if(top==1)\n {\n if(grid[i][j]==1)\n {\n if(j+1>=grid[0].size()||grid[i][j+1]==-1)return -1;\n return util(grid,!top,i,j+1);\n }\n else\n {\n if(j-1<0||grid[i][j-1]==1)return -1;\n return util(grid,!top,i,j-1);\n }\n }\n else\n {\n return util(grid,!top,i+1,j);\n }\n }\n vector findBall(vector>& grid) {\n vectorans(grid[0].size(),-1);\n for(int i=0;i int:\n nums.sort()\n left = 0\n right = len(nums) - 1\n ans = 0\n while left < right:\n cur = nums[left] + nums[right]\n if cur == k:\n ans += 1\n left += 1\n right -= 1\n elif cur < k:\n left += 1\n else:\n right -= 1\n \n return ans", "solution_js": "var maxOperations = function(nums, k) {\nlet freq = new Map(),count=0; \nfor (let i = 0; i < nums.length; i++) {\n if (freq.get(k-nums[i])) {\n if(freq.get(k-nums[i])==1) freq.delete(k-nums[i])\n else freq.set(k-nums[i],freq.get(k-nums[i])-1)\n count++;\n }else freq.set(nums[i],freq.get(nums[i])+1||1)\n} \nreturn count;\n};", "solution_java": "class Solution {\n public int maxOperations(int[] nums, int k) {\n HashMapmap=new HashMap<>();\n int count=0;\n for(int i=0;i0){\n count++;\n map.put(k-nums[i],map.get(k-nums[i])-1);\n }else{\n //getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1\n //and if some value is present then it return that value \"similar to map.get(i)\" and I added 1 on it \n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int maxOperations(vector& nums, int k) {\n unordered_map Map;\n for (auto &num: nums) Map[num]++; // count freq of nums\n int ans = 0;\n \n for(auto it=Map.begin(); it!=Map.end(); ++it){\n int num = it->first, count = it->second;\n if(k - num == num) ans += count/2; // if num is half of k add half of it's count in ans\n else if(Map.count(k - num)){ // find k-num in nums and add min freq of num or k-num to ans\n int Min = min(count, Map[k-num]);\n ans += Min;\n Map[num] -= Min;\n Map[k-num] -= Min;\n }\n }\n \n return ans;\n }\n};" }, { "title": "Assign Cookies", "algo_input": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.\n\nEach child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.\n\n \nExample 1:\n\nInput: g = [1,2,3], s = [1,1]\nOutput: 1\nExplanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.\n\n\nExample 2:\n\nInput: g = [1,2], s = [1,2,3]\nOutput: 2\nExplanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.\n\n\n \nConstraints:\n\n\n\t1 <= g.length <= 3 * 104\n\t0 <= s.length <= 3 * 104\n\t1 <= g[i], s[j] <= 231 - 1\n\n", "solution_py": "class Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort()\n s.sort()\n cont = 0\n c = 0\n k = 0\n while k< len(s) and c < len(g):\n if s[k] >= g[c]:\n c+=1\n k+=1\n cont+=1\n else:\n k+=1\n return cont", "solution_js": "var findContentChildren = function(g, s) {\n\tg.sort(function(a, b) {\n\t\treturn b - a;\n\t});\n\ts.sort(function(a, b) {\n\t\treturn a - b;\n\t});\n\t\n let content = 0;\n for (let curG of g) {\n for (let curS of s) {\n if (curS >= curG) {\n s.pop();\n\t\t\t\tcontent++;\t\n\t\t\t break;\n }\n }\n }\n\n\treturn content;\n}", "solution_java": "class Solution {\n public int findContentChildren(int[] g, int[] s) {\n int i =0,j=0,c=0;\n \n Arrays.sort(g);\n Arrays.sort(s);\n \n \n for(;i< g.length;i++)\n {\n // System.out.println(s[j]+\" \"+g[i]);\n \n while(j=g[i] )\n {\n // System.out.println(s[j]+\" \"+g[i]);\n j++;c++;\n break;\n }\n j++;\n }\n }\n \n return c;\n \n }\n}", "solution_c": "class Solution {\npublic:\n int findContentChildren(vector& g, vector& s) {\n int n=g.size();\n int m=s.size();\n if(n==0 or m==0)return 0;\n sort(g.begin(),g.end());\n sort(s.begin(),s.end());\n int i=0,j=0;\n while(i=g[j])\n j++;\n i++;\n }\n return j;\n }\n};" }, { "title": "Split a String in Balanced Strings", "algo_input": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters.\n\nGiven a balanced string s, split it into some number of substrings such that:\n\n\n\tEach substring is balanced.\n\n\nReturn the maximum number of balanced strings you can obtain.\n\n \nExample 1:\n\nInput: s = \"RLRRLLRLRL\"\nOutput: 4\nExplanation: s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.\n\n\nExample 2:\n\nInput: s = \"RLRRRLLRLL\"\nOutput: 2\nExplanation: s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2nd and 5th substrings are not balanced.\n\nExample 3:\n\nInput: s = \"LLLLRRRR\"\nOutput: 1\nExplanation: s can be split into \"LLLLRRRR\".\n\n\n \nConstraints:\n\n\n\t2 <= s.length <= 1000\n\ts[i] is either 'L' or 'R'.\n\ts is a balanced string.\n\n", "solution_py": "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n r_count=l_count=t_count=0\n for i in s:\n if i=='R':\n r_count+=1\n elif i=='L':\n l_count+=1\n if r_count==l_count:\n t_count+=1\n r_count=0\n l_count=0\n continue\n return t_count", "solution_js": "var balancedStringSplit = function(s) {\n let r_count = 0;\n let l_count = 0;\n let ans =0;\n for(let i = 0 ; i < s.length;i++){\n if(s[i]==='R') r_count++;\n else l_count++;\n\n if(l_count==r_count) {\n l_count=0\n r_count=0;\n ans++\n }\n\n }\n return ans\n};", "solution_java": "class Solution {\n public int balancedStringSplit(String s) {\n int nl = 0;\n int nr = 0;\n int count = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.substring(i,i+1).equals(\"L\")) ++nl;\n else ++nr;\n if (nr == nl) {\n ++count;\n }\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n\tint balancedStringSplit(string s) {\n\n\t\tint left = 0;\n\t\tint right = 0;\n\t\tint cnt = 0;\n\n\t\tfor(int i=0 ; i bool:\n groups = ['-'.join(str(s) for s in group) for group in groups]\n nums = '-'.join(str(s) for s in nums)\n j = k = 0\n while k < len(groups):\n group = groups[k]\n i = nums.find(group, j)\n if i == -1: return False\n if i == 0 or i > 0 and nums[i-1] == '-':\n j = i + len(group)\n k += 1\n else: j += 1\n return True ", "solution_js": "/**\n * @param {number[][]} groups\n * @param {number[]} nums\n * @return {boolean}\n */\nvar canChoose = function(groups, nums) {\n let i=0;\n for(let start=0;i>& groups, vector& nums) {\n int m = nums.size();\n int index = 0;\n for(auto group : groups){\n int n = group.size();\n //Step-1 Generate LPS\n vectorlps(n,0);\n for(int i = 1;i0 && group[i] != group[j]){\n j = lps[j-1];\n }\n if(group[i] == group[j]){\n j++;\n }\n lps[i] = j;\n }\n\n //Step 2 - Matching\n int j = 0;\n while(index0){\n j=lps[j-1];\n }else{\n index++;\n }\n }\n }\n if(j != n)\n return false;\n }\n\n return true;\n }\n};" }, { "title": "Find K Pairs with Smallest Sums", "algo_input": "You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.\n\nDefine a pair (u, v) which consists of one element from the first array and one element from the second array.\n\nReturn the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.\n\n \nExample 1:\n\nInput: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput: [[1,2],[1,4],[1,6]]\nExplanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n\n\nExample 2:\n\nInput: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput: [[1,1],[1,1]]\nExplanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n\n\nExample 3:\n\nInput: nums1 = [1,2], nums2 = [3], k = 3\nOutput: [[1,3],[2,3]]\nExplanation: All possible pairs are returned from the sequence: [1,3],[2,3]\n\n\n \nConstraints:\n\n\n\t1 <= nums1.length, nums2.length <= 105\n\t-109 <= nums1[i], nums2[i] <= 109\n\tnums1 and nums2 both are sorted in ascending order.\n\t1 <= k <= 104\n\n", "solution_py": "import heapq\nclass Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n\n ans = []\n\n heapq.heapify(ans)\n\n for i in range(min(k,len(nums1))):\n for j in range(min(k,len(nums2))):\n pairs = [nums1[i],nums2[j]]\n if len(ans)-ans[0][0]:\n break\n heapq.heappush(ans,[-(nums1[i]+nums2[j]),pairs])\n heapq.heappop(ans)\n\n res = []\n for i in range(len(ans)):\n res.append(ans[i][1])\n\n return res", "solution_js": "/**\n * @param {number[]} nums1\n * @param {number[]} nums2\n * @param {number} k\n * @return {number[][]}\n */\n\nvar kSmallestPairs = function(nums1, nums2, k) {\n const h = new MinHeap();\n h.sortKey = 'id';\n for(i =0; i>1;\n\t\tif(pI<0) return;\n\t\tif(this.id(i)=this.heap.length) return;\n\t\tconst v = Math.min(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MAX_VALUE:this.id(rI));\n\t\tif(v==this.id(i)) return;\n\t\tif(v==this.id(lI)){\n\t\t\tthis.swap(i, lI);\n\t\t\treturn this.heapDown(lI);\n\t\t}\n\t\tthis.swap(i, rI);\n\t\tthis.heapDown(rI);\n\t}\n}\n\n\nclass MaxHeap extends Heap{\n\theapUp(i){\n\t\tconst pI = (i-1)>>1;\n\t\tif(pI<0) return;\n\t\tif(this.id(i)>this.id(pI)){\n\t\t \tthis.swap(i, pI);\n\t\t \treturn this.heapUp(pI);\n\t\t}\n\t}\n\n\theapDown(i){\n\t\tconst lI = i*2+1;\n\t\tconst rI = i*2+2;\n\t\tif(lI>=this.heap.length) return;\n\t\tconst v = Math.max(this.id(i), this.id(lI), (rI>=this.heap.length)?Number.MIN_VALUE:this.id(rI));\n\t\tif(v==this.id(i)) return;\n\t\tif(v==this.id(lI)){\n\t\t\tthis.swap(i, lI);\n\t\t\treturn this.heapDown(lI);\n\t\t}\n\t\tthis.swap(i, rI);\n\t\tthis.heapDown(rI);\n\t}\n}", "solution_java": "class Solution {\n public List> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n PriorityQueue pq = new PriorityQueue<>(\n (a, b) -> (a[0] + a[1]) - (b[0] + b[1])\n );\n for(int i = 0; i < nums1.length && i < k; i++){\n pq.add(new int[]{nums1[i], nums2[0], 0});\n }\n\n List> res = new ArrayList<>();\n for(int i = 0; i < k && !pq.isEmpty(); i++){\n int [] curr = pq.poll();\n res.add(Arrays.asList(curr[0], curr[1]));\n int idx2 = curr[2];\n if(idx2 < nums2.length - 1){\n pq.add(new int[]{curr[0], nums2[idx2 + 1], idx2 + 1});\n }\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> kSmallestPairs(vector& nums1, vector& nums2, int k) {\n priority_queue>> pq;\n int m=nums1.size(),n=nums2.size();\n\n for(int i=0;i> ans;\n while(!pq.empty()){\n auto p=pq.top().second;\n pq.pop();\n\n ans.push_back({p.first,p.second});\n }\n\n return ans;\n }\n};" }, { "title": "Binary Tree Pruning", "algo_input": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.\n\nA subtree of a node node is node plus every node that is a descendant of node.\n\n \nExample 1:\n\nInput: root = [1,null,0,0,1]\nOutput: [1,null,0,null,1]\nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\n\n\nExample 2:\n\nInput: root = [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\n\nExample 3:\n\nInput: root = [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 200].\n\tNode.val is either 0 or 1.\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 pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \n def dfs(node):\n if not node:\n return None\n \n left = dfs(node.left)\n right = dfs(node.right)\n if node.val == 0 and not left and not right:\n return None\n else:\n node.left = left\n node.right = right\n return node\n \n return dfs(root)\n ", "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 pruneTree = function(root) {\n let rec = function(node){\n if(node==null) return null;\n if(node.val===0 && node.left == null && node.right == null){\n return null\n }\n node.left = rec(node.left);\n node.right = rec(node.right);\n // For updated tree structure if threre are leaf nodes with zero value present, if yes then return null otherewise return node itself.\n if(node.val===0 && node.left == null && node.right == null){\n return null\n }\n return node;\n }\n rec (root);\n if(root.val == 0 && root.left == null && root.right == null) return null\n\n return root;\n};", "solution_java": "class Solution {\n public TreeNode pruneTree(TreeNode root) {\n \n if(root == null) return root;\n \n root.left = pruneTree(root.left);\n root.right = pruneTree(root.right);\n \n if(root.left == null && root.right == null && root.val == 0) return null;\n else return root;\n }\n}", "solution_c": "class Solution {\npublic:\n TreeNode* pruneTree(TreeNode* root) {\n if(!root) return NULL;\n root->left = pruneTree(root->left);\n root->right = pruneTree(root->right);\n if(!root->left && !root->right && root->val==0) return NULL;\n return root;\n }\n \n \n};" }, { "title": "Apply Discount to Prices", "algo_input": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.\n\n\n\tFor example, \"$100\", \"$23\", and \"$6\" represent prices while \"100\", \"$\", and \"$1e5\" do not.\n\n\nYou are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.\n\nReturn a string representing the modified sentence.\n\nNote that all prices will contain at most 10 digits.\n\n \nExample 1:\n\nInput: sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\nOutput: \"there are $0.50 $1.00 and 5$ candies in the shop\"\nExplanation: \nThe words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".\n\n\nExample 2:\n\nInput: sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\nOutput: \"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\nExplanation: \nApplying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".\n\n\n \nConstraints:\n\n\n\t1 <= sentence.length <= 105\n\tsentence consists of lowercase English letters, digits, ' ', and '$'.\n\tsentence does not have leading or trailing spaces.\n\tAll words in sentence are separated by a single space.\n\tAll prices will be positive numbers without leading zeros.\n\tAll prices will have at most 10 digits.\n\t0 <= discount <= 100\n\n", "solution_py": "class Solution:\n def discountPrices(self, sentence: str, discount: int) -> str:\n s = sentence.split() # convert to List to easily update\n m = discount / 100 \n for i,word in enumerate(s):\n if word[0] == \"$\" and word[1:].isdigit(): # Check whether it is in correct format\n num = int(word[1:]) * (1-m) # discounted price\n w = \"$\" + \"{:.2f}\".format(num) #correctly format\n s[i] = w #Change inside the list\n \n return \" \".join(s) #Combine the updated list\n\t\t```", "solution_js": "var discountPrices = function(sentence, discount) {\n let isNum = (num) => {\n if(num.length <= 1 || num[0] != '$') return false;\n for(let i = 1; i < num.length; ++i)\n if(!(num[i] >= '0' && num[i] <= '9'))\n return false;\n return true;\n };\n let x = sentence.split(' ');\n discount = 1 - (discount/100);\n for(let i = 0; i < x.length; ++i) \n !isNum(x[i]) || (x[i] = `$${(Number(x[i].slice(1))*discount).toFixed(2)}`);\n return x.join(' ');\n};", "solution_java": "class Solution {\n\n public String discountPrices(String sentence, int discount) {\n String x[] = sentence.split(\" \");\n StringBuilder sb = new StringBuilder();\n for (String s : x) {\n if (isPrice(s)) sb.append(calc(Double.parseDouble(s.substring(1)), discount) + \" \"); \n else sb.append(s + \" \");\n }\n sb.deleteCharAt(sb.length() - 1);\n return sb.toString();\n }\n\n boolean isPrice(String s) {\n return s.startsWith(\"$\") && s.substring(1).matches(\"\\\\d+\");\n }\n\n String calc(double num, double discount) {\n double ans = num - (double) ((double) num * discount / 100.00);\n return \"$\" + String.format(\"%.2f\", ans);\n }\n}", "solution_c": "class Solution {\npublic:\n string discountPrices(string sentence, int discount) {\n \n\t\t// doit is a function\n auto doit = [&](string word) {\n\t\t\n int n(size(word));\n if (word[0] != '$' or n == 1) return word;\n \n long long price = 0;\n for (int i=1; i> word) {\n res += doit(word)+\" \";\n }\n \n res.pop_back();\n return res;\n }\n};" }, { "title": "Cherry Pickup", "algo_input": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.\n\n\n\t0 means the cell is empty, so you can pass through,\n\t1 means the cell contains a cherry that you can pick up and pass through, or\n\t-1 means the cell contains a thorn that blocks your way.\n\n\nReturn the maximum number of cherries you can collect by following the rules below:\n\n\n\tStarting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).\n\tAfter reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.\n\tWhen passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.\n\tIf there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.\n\n\n \nExample 1:\n\nInput: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput: 5\nExplanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.\n\n\nExample 2:\n\nInput: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput: 0\n\n\n \nConstraints:\n\n\n\tn == grid.length\n\tn == grid[i].length\n\t1 <= n <= 50\n\tgrid[i][j] is -1, 0, or 1.\n\tgrid[0][0] != -1\n\tgrid[n - 1][n - 1] != -1\n\n", "solution_py": "class Solution:\n def cherryPickup(self, grid):\n n = len(grid)\n dp = [[-1] * (n + 1) for _ in range(n + 1)]\n dp[1][1] = grid[0][0]\n for m in range(1, (n << 1) - 1):\n for i in range(min(m, n - 1), max(-1, m - n), -1):\n for p in range(i, max(-1, m - n), -1):\n j, q = m - i, m - p\n if grid[i][j] == -1 or grid[p][q] == -1:\n dp[i + 1][p + 1] = -1\n else:\n dp[i + 1][p + 1] = max(dp[i + 1][p + 1], dp[i][p + 1], dp[i + 1][p], dp[i][p])\n if dp[i + 1][p + 1] != -1: dp[i + 1][p + 1] += grid[i][j] + (grid[p][q] if i != p else 0)\n return max(0, dp[-1][-1])", "solution_js": "var cherryPickup = function(grid) {\n let result = 0, N = grid.length, cache = {}, cherries;\n \n const solve = (x1, y1, x2, y2) => {\n if(x1 === N -1 && y1 === N-1) \n return grid[x1][y1] !== -1 ? grid[x1][y1] : -Infinity;\n if(x1 > N -1 || y1 > N-1 || x2 > N-1 || y2 > N-1 || grid[x1][y1] === -1 ||grid[x2][y2] === -1) \n return -Infinity;\n \n let lookup_key = `${x1}:${y1}:${x2}:${y2}`;\n if(cache[lookup_key]) return cache[lookup_key];\n \n if(x1 === x2 && y1 === y2) \n cherries = grid[x1][y1];\n else\n cherries = grid[x1][y1] + grid[x2][y2];\n \n result = cherries + Math.max(solve(x1 + 1, y1, x2 + 1, y2),\n solve(x1, y1 + 1, x2, y2 + 1),\n solve(x1 + 1, y1, x2, y2 + 1),\n solve(x1, y1 + 1, x2 + 1, y2));\n \n cache[lookup_key] = result;\n return result;\n };\n \n result = solve(0, 0, 0, 0);\n return result > 0 ? result : 0;\n};", "solution_java": "class Solution {\n public int cherryPickup(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n //For O(N^3) Dp sapce solution\n dp2 = new Integer[m][n][m];\n int ans=solve2(0,0,0,grid,0,m,n);\n if(ans==Integer.MIN_VALUE) return 0;\n return ans;\n }\n \n private Integer[][][] dp2;\n private int solve2(int x1, int y1, int x2, int[][] g, int cpsf, int m, int n){\n int y2 = x1+y1+-x2;\n if(x1>=m||x2>=m||y1>=n||y2>=n||g[x1][y1]==-1||g[x2][y2]==-1) return Integer.MIN_VALUE;\n if(x1==m-1&&y1==n-1) return g[x1][y1];\n //If both p1 and p2 reach (m-1,n-1)\n if(dp2[x1][y1][x2]!=null) return dp2[x1][y1][x2];\n int cherries=0;\n //If both p1 and p2 are at same position then we need to add the cherry only once.\n if(x1==x2&&y1==y2){\n cherries+=g[x1][y1];\n }\n //If p1 and p2 are at different positions then repective cherries can be added.\n else{\n cherries+=g[x1][y1]+g[x2][y2];\n }\n //4 possibilites for p1 and p2 from each point\n int dd=solve2(x1+1,y1,x2+1,g,cpsf+cherries,m,n); //both moves down\n int dr=solve2(x1+1,y1,x2,g,cpsf+cherries,m,n); //p1 moves down and p2 moves right\n int rr=solve2(x1,y1+1,x2,g,cpsf+cherries,m,n); //both moves right \n int rd=solve2(x1,y1+1,x2+1,g,cpsf+cherries,m,n); //p1 moves right and p2 moves down\n \n //We take maximum of 4 possiblities\n int max=Math.max(Math.max(dd,dr), Math.max(rr,rd));\n if(max==Integer.MIN_VALUE) return dp2[x1][y1][x2]=max;\n return dp2[x1][y1][x2]=cherries+=max;\n }\n}", "solution_c": "class Solution {\npublic:\n \n int solve(int r1,int c1,int r2,vector>& grid, vector>> &dp)\n {\n //Calculating c2 : \n /*\n (r1 + c1) = (r2 + c2)\n c2 = (r1 + c1) - r2\n */\n int c2 = (r1+c1)-r2 ; \n \n //Base condition\nif(r1 >= grid.size() || r2 >= grid.size() || c1 >= grid[0].size() || c2 >= grid[0].size() || grid[r1][c1] == -1 || grid[r2][c2] == -1)\n {\n return INT_MIN;\n }\n if(r1 == grid.size()-1 && c1 == grid[0].size()-1)\n { \n return grid[r1][c1] ;\n }\n \n if(dp[r1][c1][r2] != -1)\n {\n return dp[r1][c1][r2];\n }\n int ch = 0;\n if(r1 == r2 && c1 == c2)\n {\n ch += grid[r1][c1]; \n //if both players are at the same place than collect cherry only one time.\n }\n else\n {\n ch += grid[r1][c1] + grid[r2][c2];\n }\n cout<>& grid) \n {\n \n int n = grid.size();\n \n vector>>dp(n, vector>(n, vector(n,-1)));\n \n int ans = solve(0,0,0,grid,dp) ;\n \n if(ans == INT_MIN || ans <0)\n {\n return 0;\n }\n \n return ans; \n \n }\n};" }, { "title": "Most Visited Sector in a Circular Track", "algo_input": "Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]\n\nReturn an array of the most visited sectors sorted in ascending order.\n\nNotice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).\n\n \nExample 1:\n\nInput: n = 4, rounds = [1,3,1,2]\nOutput: [1,2]\nExplanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\n\nExample 2:\n\nInput: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput: [2]\n\n\nExample 3:\n\nInput: n = 7, rounds = [1,3,5,7]\nOutput: [1,2,3,4,5,6,7]\n\n\n \nConstraints:\n\n\n\t2 <= n <= 100\n\t1 <= m <= 100\n\trounds.length == m + 1\n\t1 <= rounds[i] <= n\n\trounds[i] != rounds[i + 1] for 0 <= i < m\n\n", "solution_py": "class Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n hash_map = {}\n for i in range(0 , len(rounds)-1):\n if i == 0:\n start = rounds[i]\n elif rounds[i] == n:\n start = 1\n else:\n start = rounds[i] + 1\n end = rounds[i+1]\n if start <= end:\n for i in range(start , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n else:\n for i in range(start , n + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n for i in range(1 , end + 1):\n if i in hash_map:\n hash_map[i] += 1\n else:\n hash_map[i] = 1\n k = list(hash_map.keys())\n v = list(hash_map.values())\n ans = []\n m = -1\n i = 0\n j = 0\n while i < len(k) and j < len(v):\n if len(ans) == 0:\n ans.append(k[i])\n m = v[j]\n elif m < v[j]:\n ans = []\n ans.append(k[i])\n m = v[j]\n elif m == v[j]:\n ans.append(k[i])\n i += 1\n j += 1\n ans = sorted(ans)\n return ans", "solution_js": "var mostVisited = function(n, rounds) {\n const first = rounds[0];\n const last = rounds[rounds.length - 1];\n \n const result = [];\n \n if (first <= last) {\n for (let i = last; i >= first; i--) result.unshift(i)\n } else {\n for (let i = 1; i <= last; i++) result.push(i);\n for (let i = first; i <= n; i++) result.push(i);\n }\n \n return result;\n};", "solution_java": "class Solution {\n public List mostVisited(int n, int[] rounds) {\n int[]psum=new int[n+2];\n psum[rounds[0]]+=1;\n psum[rounds[1]+1]-=1;\n if(rounds[0]>rounds[1])\n psum[1]+=1;\n for(int i=2;irounds[i])\n psum[1]+=1;\n }\n int max_=0;\n for(int i=1;i<=n;i++){\n psum[i]+=psum[i-1];\n if(psum[i]>max_)\n max_=psum[i];\n }\n Listans=new ArrayList<>();\n for(int i=1;i<=n;i++){\n if(psum[i]==max_)\n ans.add(i);\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n vector mostVisited(int n, vector& rounds) {\n vector ans;\n int size = rounds.size();\n \n if(rounds[0] <= rounds[size-1]) {\n for(int i=rounds[0]; i<= rounds[size-1]; i++) {\n ans.push_back(i);\n }\n return ans;\n }\n else {\n for(int i=1; i<= rounds[size-1]; i++) {\n ans.push_back(i);\n } \n \n for(int i=rounds[0]; i<=n; i++) {\n ans.push_back(i);\n }\n }\n \n return ans;\n }\n};" }, { "title": "Longest Repeating Character Replacement", "algo_input": "You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.\n\nReturn the length of the longest substring containing the same letter you can get after performing the above operations.\n\n \nExample 1:\n\nInput: s = \"ABAB\", k = 2\nOutput: 4\nExplanation: Replace the two 'A's with two 'B's or vice versa.\n\n\nExample 2:\n\nInput: s = \"AABABBA\", k = 1\nOutput: 4\nExplanation: Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 105\n\ts consists of only uppercase English letters.\n\t0 <= k <= s.length\n\n", "solution_py": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n # Initialize variables\n window_start = 0\n max_length = 0\n max_count = 0\n char_count = {}\n\n # Traverse the string s\n for window_end in range(len(s)):\n # Increment the count of the current character\n char_count[s[window_end]] = char_count.get(s[window_end], 0) + 1\n # Update the maximum count seen so far\n max_count = max(max_count, char_count[s[window_end]])\n \n # Shrink the window if required\n if window_end - window_start + 1 > max_count + k:\n char_count[s[window_start]] -= 1\n window_start += 1\n \n # Update the maximum length of the substring with repeating characters seen so far\n max_length = max(max_length, window_end - window_start + 1)\n \n return max_length", "solution_js": "// O(n) time | O(26) -> O(1) space - only uppercase English letters\nvar characterReplacement = function(s, k) {\n const sLen = s.length, \n charCount = {};\n if (k >= sLen) return sLen;\n let maxLen = 0,\n windowStart = 0,\n maxRepeatChar = 0;\n for (let windowEnd = 0; windowEnd < sLen; windowEnd++) {\n // increment charCount\n charCount[s[windowEnd]] ? charCount[s[windowEnd]]++ : charCount[s[windowEnd]] = 1;\n // calc max repeating char\n maxRepeatChar = Math.max(maxRepeatChar, charCount[s[windowEnd]]);\n // calc number of char that is not (or has fewer chars) repeating in window\n const remainingChar = windowEnd - windowStart + 1 - maxRepeatChar;\n // slide window by incrementing start of window\n if (remainingChar > k) {\n // decrement charCount\n charCount[s[windowStart]]--;\n windowStart++;\n }\n // calc maxLen\n maxLen = Math.max(maxLen, windowEnd - windowStart + 1);\n }\n return maxLen;\n};", "solution_java": "class Solution {\n public int characterReplacement(String s, int k) {\n HashMap map=new HashMap<>();\n int i=-1;\n int j=-1;\n int ans=0;\n while(true){\n boolean f1=false;\n boolean f2=false;\n while(i map,char ch){\n if(map.get(ch)==1) map.remove(ch);\n else map.put(ch,map.get(ch)-1);\n }\n}", "solution_c": "class Solution {\npublic:\n int characterReplacement(string s, int k) {\n int n = s.length();\n if(n == k) return n;\n if(n == 1) return 1;\n\n int res = 0;\n int maxCnt = 0;\n \n unordered_map mp;\n \n for(int l = 0, r = 0; r < n; r++)\n {\n mp[s[r]]++;\n maxCnt = max(maxCnt,mp[s[r]]);\n while(r - l + 1 - maxCnt > k){\n mp[s[l]]--;\n l++;\n }\n res = max(r - l + 1, res);\n }\n return res;\n }\n};" }, { "title": "Find All Lonely Numbers in the Array", "algo_input": "You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.\n\nReturn all lonely numbers in nums. You may return the answer in any order.\n\n \nExample 1:\n\nInput: nums = [10,6,5,8]\nOutput: [10,8]\nExplanation: \n- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.\n\n\nExample 2:\n\nInput: nums = [1,3,5,3]\nOutput: [1,5]\nExplanation: \n- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 106\n\n", "solution_py": "class Solution:\n def findLonely(self, nums: List[int]) -> List[int]:\n m = Counter(nums)\n return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]", "solution_js": "var findLonely = function(nums) {\n let countMap = new Map();\n let result = [];\n for (let num of nums) {\n countMap.set(num, (countMap.get(num) || 0) + 1);\n }\n for (let num of nums) {\n if (!countMap.has(num - 1) && !countMap.has(num + 1) && countMap.get(num) === 1) {\n\n result.push(num);\n }\n\n }\n return result;\n};", "solution_java": "class Solution {\n public List findLonely(int[] nums) {\n Arrays.sort(nums);\n ArrayList list = new ArrayList<>();\n for (int i = 1; i < nums.length - 1; i++) {\n if (nums[i - 1] + 1 < nums[i] && nums[i] + 1 < nums[i + 1]) {\n list.add(nums[i]);\n }\n }\n if (nums.length == 1) {\n list.add(nums[0]);\n }\n if (nums.length > 1) {\n if (nums[0] + 1 < nums[1]) {\n list.add(nums[0]);\n }\n if (nums[nums.length - 2] + 1 < nums[nums.length - 1]) {\n list.add(nums[nums.length - 1]);\n }\n }\n return list;\n }\n}", "solution_c": "class Solution {\npublic:\n vector findLonely(vector& nums) {\n int n=nums.size();\n unordered_map ump;\n vector sol;\n for(int i=0;i int:\n \n \n # zero_as_last: the count of S0, good sequence ending in 0\n # one_as_last : the count of S1: good sequence ending in 1\n # zero_exist: existence flag of 0 in given binary\n \n dp = {\"zero_as_last\": 0, \"one_as_last\": 0, \"zero_exist\": 0}\n \n for bit in map(int, binary):\n \n if bit:\n # current good = ( S0 concate with 1 ) + ( S1 concate with 1 ) + 1 alone\n # + \"1\" is allowed because leading 1 is valid by description\n dp[\"one_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"] + 1\n \n else:\n # current good = ( S0 concate with 0 ) + ( S1 concate with 0 ) \n # + \"0\" is NOT allowed because leading 0 is invalid by description\n dp[\"zero_as_last\"] = dp[\"zero_as_last\"] + dp[\"one_as_last\"]\n \n # check the existence of 0\n dp[\"zero_exist\"] |= (1-bit)\n \n \n return sum( dp.values() ) % ( 10**9 + 7 )", "solution_js": "const MOD = 1000000007;\n\nvar numberOfUniqueGoodSubsequences = function(binary) {\n let endsZero = 0;\n let endsOne = 0;\n let hasZero = 0;\n for (let i = 0; i < binary.length; i++) {\n if (binary[i] === '1') {\n endsOne = (endsZero + endsOne + 1) % MOD;\n } else {\n endsZero = (endsZero + endsOne) % MOD;\n hasZero = 1;\n }\n }\n return (endsZero + endsOne + hasZero) % MOD;\n};", "solution_java": "class Solution {\n public int numberOfUniqueGoodSubsequences(String binary) {\n int initialZeroCount= 0;\n while(initialZeroCount < binary.length() && binary.charAt(initialZeroCount) == '0') initialZeroCount++;\n if(initialZeroCount == binary.length()) return 1;\n long[] dp = new long[binary.length()];\n dp[initialZeroCount] = 1;\n int lastOne = 0, lastZero = 0;\n long mod = (long) Math.pow(10, 9)+7;\n for(int i=initialZeroCount+1;i 0 ? dp[j-1] : 0;\n dp[i] = 2 * dp[i-1] - dup;\n if(dp[i] < 0) dp[i] += mod;\n dp[i] %= mod;\n if(binary.charAt(i) == '0') lastZero = i;\n else lastOne = i;\n }\n \n int hasZero = 0;\n if(binary.contains(\"0\")) hasZero = 1;\n \n \n return (int) (dp[binary.length()-1] + hasZero);\n }\n}", "solution_c": "class Solution {\n int MOD = 1000000007;\npublic:\n int numberOfUniqueGoodSubsequences(string binary) {\n int zero = 0;\n long long ones = 0;\n long long zeros = 0;\n \n for (int i = binary.size() - 1; i >= 0; --i) {\n if (binary[i] == '1') {\n ones = (ones + zeros + 1) % MOD;\n } else {\n zero = 1;\n zeros = (ones + zeros + 1) % MOD;\n }\n }\n return (ones + zero) % MOD;\n }\n};" }, { "title": "Largest Palindrome Product", "algo_input": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.\n\n \nExample 1:\n\nInput: n = 2\nOutput: 987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987\n\n\nExample 2:\n\nInput: n = 1\nOutput: 9\n\n\n \nConstraints:\n\n\n\t1 <= n <= 8\n\n", "solution_py": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n return [0, 9, 987, 123, 597, 677, 1218, 877, 475][n]\n\n \n def isPalindrome(x):\n return str(x) == str(x)[::-1]\n\n def solve(n):\n best = 0\n for i in range(10**n-1, 0, -1):\n for j in range(max(i, (best-1)//i+1), 10**n):\n if isPalindrome(i*j):\n #print(i, j, i*j)\n best = i*j\n return best", "solution_js": "/**\n * @param {number} n\n * @return {number}\n */\nvar largestPalindrome = function(n) {\n if (n === 1) return 9;\n let hi = BigInt(Math.pow(10, n) - 1);\n let num = hi;\n while(num > 0) {\n num -= 1n;\n const palindrome = BigInt(String(num) + String(num).split('').reverse().join(''));\n for (let i = hi; i >= 2n; i -= 2n) {\n const j = palindrome / i; \n if (j > hi) break;\n if (palindrome % i === 0n) {\n return String(palindrome % 1337n);\n };\n }\n }\n};", "solution_java": "class Solution {\n public int largestPalindrome(int n) {\n if(n == 1 ){\n return 9;\n }\n if(n == 2){\n return 987;\n }\n if(n == 3){\n return 123;\n }\n if(n == 4){\n return 597;\n }\n if(n == 5){\n return 677;\n }\n if(n == 6){\n return 1218;\n }\n if(n == 7){\n return 877;\n }\n return 475;\n \n }\n}", "solution_c": "class Solution {\npublic:\n int largestPalindrome(int n) {\n if(n==1)\n {\n return 9;\n }\n int hi=pow(10,n)-1;\n int lo=pow(10,n-1);\n int kk=1337;\n for(int i=hi;i>=lo;i--)\n {\n string s=to_string(i);\n string k=s;\n reverse(k.begin(),k.end());\n s+=k;\n long long int ll=stol(s);\n for(int j=hi;j>=sqrtl(ll);j--)\n {\n if(ll%j==0)\n {\n return ll%kk;\n }\n }\n \n }\n return 0;\n }\n};" }, { "title": "Angle Between Hands of a Clock", "algo_input": "Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.\n\nAnswers within 10-5 of the actual value will be accepted as correct.\n\n \nExample 1:\n\nInput: hour = 12, minutes = 30\nOutput: 165\n\n\nExample 2:\n\nInput: hour = 3, minutes = 30\nOutput: 75\n\n\nExample 3:\n\nInput: hour = 3, minutes = 15\nOutput: 7.5\n\n\n \nConstraints:\n\n\n\t1 <= hour <= 12\n\t0 <= minutes <= 59\n\n", "solution_py": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n \n x = abs(minutes * 6 -(hour * 30 + minutes/2))\n return min(360-x , x)", "solution_js": "var angleClock = function(hour, minutes) {\n const angle = Math.abs((hour * 30) - 5.5 * minutes)\n return angle > 180 ? 360 - angle : angle\n};", "solution_java": "class Solution {\n public double angleClock(int hour, int minutes) {\n // Position of hour hand in a circle of 0 - 59\n double hrPos = 5 * (hour % 12);\n\n // Adjust hour hand position according to minute hand\n hrPos += (5 * minutes/60.0);\n\n double units = Math.abs(minutes - hrPos);\n\n // Take the min of distance between minute & hour hand and hour & minute hand\n return Math.min(units, 60-units) * 6;\n }\n}", "solution_c": "class Solution {\npublic:\n double angleClock(int hour, int minutes) {\n\n double hourAngle = 30*(double(hour) + double(minutes/60.0));\n\n double minuteAngle = 6 * (double)minutes;\n\n return 180 - abs(180 - abs(minuteAngle - hourAngle));\n\n }\n};" }, { "title": "Decode Ways", "algo_input": "A message containing letters from A-Z can be encoded into numbers using the following mapping:\n\n'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"\n\n\nTo decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n\n\n\t\"AAJF\" with the grouping (1 1 10 6)\n\t\"KJF\" with the grouping (11 10 6)\n\n\nNote that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\n\nGiven a string s containing only digits, return the number of ways to decode it.\n\nThe test cases are generated so that the answer fits in a 32-bit integer.\n\n \nExample 1:\n\nInput: s = \"12\"\nOutput: 2\nExplanation: \"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).\n\n\nExample 2:\n\nInput: s = \"226\"\nOutput: 3\nExplanation: \"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).\n\n\nExample 3:\n\nInput: s = \"06\"\nOutput: 0\nExplanation: \"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts contains only digits and may contain leading zero(s).\n\n", "solution_py": "class Solution:\n def numDecodings(self, s: str) -> int:\n if s[0] == '0' or '00' in s:\n return 0\n l = len(s)\n if l == 1:\n return 1\n elif l == 2:\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n return 1\n else:\n return 0\n else:\n if int(s) <= 26:\n return 2\n else:\n return 1\n dp = [1]\n if s[1] == '0':\n if s[0] == '1' or s[0] == '2':\n dp.append(1)\n else:\n return 0\n else:\n if int(s[:2]) <= 26:\n dp.append(2)\n else:\n dp.append(1)\n for i in range(2, l):\n num = 0\n if s[i] == '0':\n if s[i-1] != '1' and s[i-1] != '2':\n return 0\n else:\n num = dp[i-2]\n elif s[i-1] == '1' or (s[i-1] == '2' and int(f'{s[i-1]}{s[i]}') <= 26):\n num = dp[i-1]+dp[i-2]\n else:\n num = dp[i-1]\n dp.append(num)\n return dp[l-1]", "solution_js": "var numDecodings = function(s) {\n let dp = Array(s.length).fill(0); // dp[i] means, the total ways of decode for substring up to i\n dp[0] = (s[0] !== '0') ? 1 : 0;\n \n for(let i = 1; i < s.length; i++){\n\t//case1\n if(s[i] !== '0'){\n dp[i] = dp[i - 1];\n }\n //case2\n if(s[i-1] === '1' || (s[i-1] === '2' && parseInt(s[i]) <= 6)){\n dp[i] += dp[i - 2] ?? 1;\n }\n }\n \n return dp[s.length - 1];\n};", "solution_java": "class Solution {\n public int numDecodings(String s) {\n int[]dp = new int[s.length() + 1];\n dp[0] = 1;\n dp[1] = s.charAt(0) == '0' ? 0 : 1;\n \n for(int i = 2;i<=s.length();i++) {\n int oneDigit = Integer.valueOf(s.substring(i-1,i));\n int twoDigit = Integer.valueOf(s.substring(i-2,i));\n \n if(oneDigit >= 1) {\n dp[i] += dp[i - 1];\n }\n if(twoDigit >= 10 && twoDigit <= 26) {\n dp[i] += dp[i - 2];\n }\n }\n return dp[s.length()];\n }\n}", "solution_c": "class Solution {\npublic:\n int numDecodings(string s) {\n \n if(s[0] == 0)\n return 0;\n int n = s.length();\n vector dp(n+1, 0);\n \n //Storing DP[n-1]\n if(s[n-1] == '0' )\n dp[n-1] = 0;\n else \n dp[n-1] = 1;\n \n if(n == 1)\n return dp[0];\n \n //Storing DP[n-2]\n if(s[n-2] == '0')\n dp[n-2] = 0;\n else\n {\n string temp ;\n temp.push_back(s[n-2]);\n temp.push_back(s[n-1]);\n \n int x = stoi(temp);\n if(x<27)\n dp[n-2] = 1;\n dp[n-2] += dp[n-1];\n }\n \n \n for(int i = n-3; i>=0 ; i--)\n {\n if(s[i] == '0')\n continue;\n \n string temp ;\n temp.push_back(s[i]);\n temp.push_back(s[i+1]);\n \n int x = stoi(temp);\n if(x<27)\n dp[i] = dp[i+2];\n dp[i]+=dp[i+1];\n }\n \n return dp[0];\n }\n};" }, { "title": "Check if Binary String Has at Most One Segment of Ones", "algo_input": "Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.\n\n \nExample 1:\n\nInput: s = \"1001\"\nOutput: false\nExplanation: The ones do not form a contiguous segment.\n\n\nExample 2:\n\nInput: s = \"110\"\nOutput: true\n\n \nConstraints:\n\n\n\t1 <= s.length <= 100\n\ts[i]​​​​ is either '0' or '1'.\n\ts[0] is '1'.\n\n", "solution_py": "class Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return \"01\" not in s", "solution_js": "var checkOnesSegment = function(s) {\n return s.indexOf(\"01\") == -1\n};", "solution_java": "class Solution {\n public boolean checkOnesSegment(String s) {\n return !s.contains(\"01\");\n }\n}", "solution_c": "class Solution {\npublic:\n\tbool checkOnesSegment(string s) {\n\t\tfor(int i = 1; i < s.size(); i++){\n\t\t\tif(s[i - 1] == '0' and s[i] == '1'){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n};" }, { "title": "Number of Subarrays with Bounded Maximum", "algo_input": "Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].\n\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n\n \nExample 1:\n\nInput: nums = [2,1,4,3], left = 2, right = 3\nOutput: 3\nExplanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\n\n\nExample 2:\n\nInput: nums = [2,9,2,5,6], left = 2, right = 8\nOutput: 7\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t0 <= nums[i] <= 109\n\t0 <= left <= right <= 109\n\n", "solution_py": "class Solution:\n def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n n = len(nums)\n stack = []\n next_greater = [n] * n\n prev_greater = [-1] * n\n for i in range(n):\n while len(stack) > 0 and nums[i] > nums[stack[-1]]:\n curr = stack.pop()\n next_greater[curr] = i\n if len(stack) > 0:\n prev_greater[i] = stack[-1]\n stack.append(i)\n res = 0\n for i in range(n):\n if left <= nums[i] <= right:\n l = prev_greater[i]\n r = next_greater[i]\n res += (i - l) * (r - i)\n return res", "solution_js": " var numSubarrayBoundedMax = function(nums, left, right) {\n // si is start index\n // ei is end index\n let si=0, ei=0, finalCount=0, currentCount=0;\n\n while(eiright){\n si=ei+1; // in this case when num is greater than right range we need to move our start index to end+1 because there won't be any subarrays that will fall in range.\n currentCount=0; // we will set current count 0 in such case.\n }\n\n ei++;\n }\n return finalCount;\n\n };", "solution_java": "class Solution {\n public int numSubarrayBoundedMax(int[] nums, int left, int right) {\n int res = 0;\n\n int s = -1;\n int e = -1;\n\n for(int i=0;i= left && nums[i] <= right){\n e = i;\n }else if(nums[i] > right){\n e = s = i;\n }\n\n res += (e - s);\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int numSubarrayBoundedMax(vector& nums, int left, int right) {\n int ans = 0; // store ans\n int j=-1; // starting window\n int sub = 0; // if current element is less than left bound then count how may element before current element which is less than left and must be continues(it means any element which is greater than left bound reset the count to 0 )\n for(int i=0;iright){\n j = i;\n sub = 0;\n }\n else if(nums[i] None:\n for i in range(row1,row2+1):\n for j in range(col1,col2+1):\n self.rectangle[i][j] = newValue\n \n def getValue(self, row: int, col: int) -> int:\n return self.rectangle[row][col]", "solution_js": "/**\n * @param {number[][]} rectangle\n */\nvar SubrectangleQueries = function(rectangle) {\n this.rectangle = rectangle;\n};\n\n/** \n * @param {number} row1 \n * @param {number} col1 \n * @param {number} row2 \n * @param {number} col2 \n * @param {number} newValue\n * @return {void}\n */\nSubrectangleQueries.prototype.updateSubrectangle = function(row1, col1, row2, col2, newValue) {\n for(let i=row1; i<=row2; i++){\n for(let j=col1; j<=col2; j++){\n this.rectangle[i][j] = newValue;\n }\n }\n};\n\n/** \n * @param {number} row \n * @param {number} col\n * @return {number}\n */\nSubrectangleQueries.prototype.getValue = function(row, col) {\n return this.rectangle[row][col];\n};\n\n/** \n * Your SubrectangleQueries object will be instantiated and called as such:\n * var obj = new SubrectangleQueries(rectangle)\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue)\n * var param_2 = obj.getValue(row,col)\n */", "solution_java": "class SubrectangleQueries {\n int[][] rectangle;\n public SubrectangleQueries(int[][] rectangle) {\n this.rectangle = rectangle;\n }\n\n public void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n for(int i=row1;i<=row2;i++){\n for(int j=col1;j<=col2;j++){\n rectangle[i][j] = newValue;\n }\n }\n }\n\n public int getValue(int row, int col) {\n return this.rectangle[row][col];\n }\n}\n\n/**\n * Your SubrectangleQueries object will be instantiated and called as such:\n * SubrectangleQueries obj = new SubrectangleQueries(rectangle);\n * obj.updateSubrectangle(row1,col1,row2,col2,newValue);\n * int param_2 = obj.getValue(row,col);\n */", "solution_c": "class SubrectangleQueries {\npublic:\n vector> rect;\n SubrectangleQueries(vector>& rectangle) {\n rect= rectangle;\n }\n \n void updateSubrectangle(int row1, int col1, int row2, int col2, int newValue) {\n for(int i=row1; i<=row2; ++i){\n for(int j=col1; j<=col2; ++j){\n rect[i][j]= newValue;\n }\n }\n }\n \n int getValue(int row, int col) {\n return rect[row][col];\n }\n};" }, { "title": "Minimum Operations to Halve Array Sum", "algo_input": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)\n\nReturn the minimum number of operations to reduce the sum of nums by at least half.\n\n \nExample 1:\n\nInput: nums = [5,19,8,1]\nOutput: 3\nExplanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\nExample 2:\n\nInput: nums = [3,8,20]\nOutput: 3\nExplanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 105\n\t1 <= nums[i] <= 107\n\n", "solution_py": "class Solution:\n def halveArray(self, nums: List[int]) -> int:\n # Creating empty heap\n maxHeap = []\n heapify(maxHeap) # Creates minHeap \n \n totalSum = 0\n for i in nums:\n # Adding items to the heap using heappush\n # for maxHeap, function by multiplying them with -1\n heappush(maxHeap, -1*i) \n totalSum += i\n \n requiredSum = totalSum / 2\n minOps = 0\n \n while totalSum > requiredSum:\n x = -1*heappop(maxHeap) # Got negative value make it positive\n x /= 2\n totalSum -= x\n heappush(maxHeap, -1*x) \n minOps += 1\n \n return minOps", "solution_js": "var halveArray = function(nums) {\n const n = nums.length;\n const maxHeap = new MaxPriorityQueue({ priority: x => x });\n\n let startSum = 0;\n\n for (const num of nums) {\n maxHeap.enqueue(num);\n startSum += num;\n }\n\n let currSum = startSum;\n\n let numberOfOperations = 0;\n\n while (currSum > startSum / 2) {\n const biggestNum = maxHeap.dequeue().element;\n\n const halfNum = biggestNum / 2;\n\n numberOfOperations += 1;\n currSum -= halfNum;\n\n maxHeap.enqueue(halfNum);\n }\n\n return numberOfOperations;\n};", "solution_java": "class Solution {\n public int halveArray(int[] nums) {\n PriorityQueue q = new PriorityQueue<>(Collections.reverseOrder());\n double sum=0;\n for(int i:nums){\n sum+=(double)i;\n q.add((double)i);\n }\n int res=0;\n double req = sum;\n while(sum > req/2){\n double curr = q.poll();\n q.add(curr/2);\n res++;\n sum -= curr/2;\n }\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int halveArray(vector& nums) {\n\t\tpriority_queue pq;\n double totalSum = 0;\n double requiredSum = 0;\n for(auto x: nums){\n totalSum += x;\n pq.push(x);\n }\n \n requiredSum = totalSum/2;\n int minOps = 0;\n while(totalSum > requiredSum){\n double currtop = pq.top();\n pq.pop();\n currtop = currtop/2;\n totalSum -= currtop;\n pq.push(currtop);\n minOps++;\n }\n return minOps;\n\t}\n}\n\t\t" }, { "title": "Two Sum IV - Input is a BST", "algo_input": "Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.\n\n \nExample 1:\n\nInput: root = [5,3,6,2,4,null,7], k = 9\nOutput: true\n\n\nExample 2:\n\nInput: root = [5,3,6,2,4,null,7], k = 28\nOutput: false\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 104].\n\t-104 <= Node.val <= 104\n\troot is guaranteed to be a valid binary search tree.\n\t-105 <= k <= 105\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 findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n def inorder(root,l):\n if root:\n inorder(root.left,l)\n l.append(root.val)\n inorder(root.right,l)\n l = []\n inorder(root,l)\n left,right=0,len(l)-1\n while left!=right:\n sum = l[left] + l[right]\n if sum > k :\n right -=1\n elif sum {\n if (!root) return false;\n if (set.has(k - root.val)) return true;\n set.add(root.val);\n return search(root.left, k) || search(root.right, k);\n }\n\n return search(root,k);\n};", "solution_java": "class Solution {\n Set set = new HashSet<>();\n public boolean findTarget(TreeNode root, int k) {\n if(root == null){\n return false;\n }\n if(set.contains(k-root.val)){\n return true;\n }\n set.add(root.val);\n return findTarget(root.left,k) || findTarget(root.right,k);\n }\n}", "solution_c": "class Solution {\npublic:\n int countNodes(TreeNode *root) {\n if (root == NULL) {\n return 0;\n }\n return countNodes(root->left) + countNodes(root->right) + 1;\n }\n\n bool findTarget(TreeNode* root, int k) {\n int totalCount = countNodes(root);\n int count = 0;\n stack inorder;\n stack revInorder;\n\n TreeNode* currNode = root;\n while(currNode != NULL){\n inorder.push(currNode); //Store all elements in left of tree\n currNode = currNode->left;\n }\n\n currNode = root;\n while(currNode != NULL){\n revInorder.push(currNode); //Store all elements in right of tree\n currNode = currNode->right;\n }\n\n while(count < totalCount-1){\n TreeNode* inordertop = inorder.top();\n TreeNode* revinordertop = revInorder.top();\n if(inordertop->val + revinordertop->val == k){ // If inordertop + revinordertop is equal to k, we have found a pair, so return true\n return true;\n }\n else if(inordertop->val + revinordertop->val > k){ //If they are greater than k, we have to found a value\n //which is just smaller than revinordertop, which means we have to find predecessor of revinordertop, as\n //we have to reduce the sum to make it equal to k\n TreeNode* currtop = revinordertop;\n count++;\n revInorder.pop();\n if(currtop->left){\n currtop = currtop->left;\n while(currtop){\n revInorder.push(currtop);\n currtop = currtop->right;\n }\n }\n }\n else{\n //If they are smaller than k, we have to found a value which is just larger than inordertop, which means\n //we have to find successor of revinordertop, as we have to increase the sum to make it equal to k\n TreeNode* currtop = inordertop;\n count++;\n inorder.pop();\n if(currtop->right){\n currtop = currtop->right;\n while(currtop){\n inorder.push(currtop);\n currtop = currtop->left;\n }\n }\n }\n }\n return false;\n }\n};" }, { "title": "Excel Sheet Column Title", "algo_input": "Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.\n\nFor example:\n\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n\n\n \nExample 1:\n\nInput: columnNumber = 1\nOutput: \"A\"\n\n\nExample 2:\n\nInput: columnNumber = 28\nOutput: \"AB\"\n\n\nExample 3:\n\nInput: columnNumber = 701\nOutput: \"ZY\"\n\n\n \nConstraints:\n\n\n\t1 <= columnNumber <= 231 - 1\n\n", "solution_py": "class Solution:\n def convertToTitle(self, num: int) -> str:\n\t\t# We make this lookup list, having A-Z in ascending order\n alpha = [chr(x) for x in range(ord(\"A\"), ord(\"Z\")+1)] # range(65, 90+1) -> 91-65 = 26\n res = \"\"\n\n while num > 0:\n res += alpha[(num-1)%26] # since 0 indexed list, num-1 % 26 gives the index of ch in alpha\n num = (num-1) // 26 \n return res[::-1]", "solution_js": "/**\n * @param {number} columnNumber\n * @return {string}\n */\nvar convertToTitle = function(columnNumber) {\n let ans = \"\";\n while(columnNumber >0){\n let n = (--columnNumber) % 26;\n columnNumber = Math.floor(columnNumber/ 26);\n\n // console.log(String.fromCharCode(65+n),)\n ans+=String.fromCharCode(65 + n);\n\n }\n ans = ans.split(\"\").reverse().join(\"\")\n return ans\n};", "solution_java": "class Solution {\n public String convertToTitle(int columnNumber) {\n String ans = \"\";\n while(columnNumber > 0){\n columnNumber--;\n ans = String.valueOf((char)('A' + (int)((26 + (long)columnNumber) % 26))) + ans;\n columnNumber /= 26;\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n string convertToTitle(int columnNumber) {\n string s = \"\";\n while(columnNumber){\n char c = (columnNumber-1)%26+65;\n s = c+s;\n columnNumber = (columnNumber-1)/26;\n }\n return s;\n }\n};" }, { "title": "Number of Provinces", "algo_input": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.\n\nA province is a group of directly or indirectly connected cities and no other cities outside of the group.\n\nYou are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.\n\nReturn the total number of provinces.\n\n \nExample 1:\n\nInput: isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput: 2\n\n\nExample 2:\n\nInput: isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\n\n\n \nConstraints:\n\n\n\t1 <= n <= 200\n\tn == isConnected.length\n\tn == isConnected[i].length\n\tisConnected[i][j] is 1 or 0.\n\tisConnected[i][i] == 1\n\tisConnected[i][j] == isConnected[j][i]\n\n", "solution_py": "class Solution:\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n graph = defaultdict(list)\n for i,x in enumerate(isConnected):\n for j,n in enumerate(x):\n if j!=i and n == 1:\n graph[i].append(j)\n \n visit = set()\n \n def dfs(node):\n if node not in graph:\n return \n for neighbor in graph[node]:\n if neighbor not in visit:\n visit.add(neighbor)\n dfs(neighbor)\n count = 0\n for i in range(len(isConnected)):\n if i in visit:\n continue\n count+=1\n dfs(i)\n return count", "solution_js": "function DisjointSet (size) {\n this.root = []\n this.rank = []\n this.size = size\n for (let i = 0; i < size; i++) {\n this.root.push(i)\n this.rank.push(1)\n }\n this.find = function(x) {\n if (x === this.root[x]) {\n return x\n }\n this.root[x] = this.find(this.root[x])\n return this.root[x]\n }\n this.union = function(x, y) {\n const rootX = this.find(x)\n const rootY = this.find(y)\n if (rootX === rootY) return\n this.size--\n if (this.rank[rootX] > this.rank[rootY]) {\n this.root[rootY] = this.root[rootX]\n }\n else if (this.rank[rootX] < this.rank[rootY]) {\n this.root[rootX] = this.root[rootY]\n }\n else {\n this.root[rootY] = this.root[rootX]\n this.rank[rootX]++\n }\n }\n}\n\n/**\n * @param {number[][]} isConnected\n * @return {number}\n */\nvar findCircleNum = function(isConnected) {\n const n = isConnected.length\n const disjointSet = new DisjointSet(isConnected.length)\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n if (isConnected[i][j]) {\n disjointSet.union(i, j)\n }\n }\n }\n return disjointSet.size\n};", "solution_java": "class Solution {\n public int findCircleNum(int[][] isConnected) {\n int size = isConnected.length;\n boolean[] isCheck = new boolean[size+1];\n int ans = 0;\n\n for(int i=1; i<=size; i++){\n\n if(!isCheck[i]){ // Doing BFS if it's false in isCheck[]\n Queue q = new LinkedList<>();\n q.add(i);\n ans++; // No. of queue = No. of Graphs\n\n while(!q.isEmpty()){\n int temp = q.remove();\n isCheck[temp] = true;\n\n for(int j=0; j> &graph,int n,vector &vis){\n\n vis[node] = true;\n\n for(int j = 0; j < graph[node].size(); j++){\n if(graph[node][j] == 1 and !vis[j]){\n dfs(j,graph,n,vis);\n }\n }\n\n }\npublic:\n int findCircleNum(vector>& isConnected) {\n\n int n = isConnected.size();\n\n vector vis(n,false);\n\n int ans = 0;\n\n for(int i = 0; i < n; i++){\n if(!vis[i]){\n ans++;\n dfs(i,isConnected,n,vis);\n }\n }\n\n return ans;\n\n }\n};" }, { "title": "Minimum Number of Days to Make m Bouquets", "algo_input": "You are given an integer array bloomDay, an integer m and an integer k.\n\nYou want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.\n\nThe garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.\n\nReturn the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.\n\n \nExample 1:\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput: 3\nExplanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.\n\n\nExample 2:\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput: -1\nExplanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\n\n\nExample 3:\n\nInput: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput: 12\nExplanation: We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.\n\n\n \nConstraints:\n\n\n\tbloomDay.length == n\n\t1 <= n <= 105\n\t1 <= bloomDay[i] <= 109\n\t1 <= m <= 106\n\t1 <= k <= n\n\n", "solution_py": "class Solution:\n \n def minDays(self, listOfFlowerBloomDays: List[int], targetNumberOfBouquets: int, flowersPerBouquet: int) -> int:\n \n def numberOfBouquetsWeCanMakeOnThisDay(dayThatWeAreChecking):\n \n currentListOfAdjacentBloomedFlowers = []\n numberOfBouquetsWeCanMakeOnThisDay = 0\n \n for dayThatFlowerBlooms in listOfFlowerBloomDays:\n \n # check if the flower has bloomed on this day \n if dayThatFlowerBlooms <= dayThatWeAreChecking:\n \n # add to the list an adjacent bloomed flowers, I use 'x' because the description uses an 'x'\n currentListOfAdjacentBloomedFlowers.append('x')\n \n else:\n # we've hit a day where we don't have a bloomed flower, so the list of adjacent bloomed flowers has to be reset\n # BUT FIRST figure out how many bouquets we can make with this list of adjacent bloomed flowers\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n # RESET list of adjacent bloomed flowers cause we're on a day where the a flower has not bloomed yet\n currentListOfAdjacentBloomedFlowers = []\n \n # we've gone through the entire listOfFlowerBloomDays list and need to check if the \"residual\" current list \n # of adjacent bloomed flowers can make a bouquet ... so handle it here\n numberOfBouquetsWeCanMakeOnThisDay += len(currentListOfAdjacentBloomedFlowers)//flowersPerBouquet\n \n return numberOfBouquetsWeCanMakeOnThisDay\n \n \n # if the TOTAL amount of flowers we need doesn't match the number of possible flowers we can grow,\n # then the given inputs are impossible for making enough bouquets (we don't have enough flowers)\n totalNumberOfFlowersNeeded = targetNumberOfBouquets*flowersPerBouquet\n numberOfFlowersWeCanGrow = len(listOfFlowerBloomDays)\n if numberOfFlowersWeCanGrow < totalNumberOfFlowersNeeded: \n return -1\n \n # no need to go past the day of the flower with the longest bloom date\n leftDay = 0\n rightDay = max(listOfFlowerBloomDays)\n \n while leftDay < rightDay:\n \n # currentDay is functioning as the \"mid\" of a binary search\n currentDay = leftDay + (rightDay-leftDay)//2\n \n # as in most binary searches, we check if the mid (which I'm calling 'currentDay') satisfies the constraint\n # that is, if we can make the target amount of bouquets on this day\n if numberOfBouquetsWeCanMakeOnThisDay(currentDay) < targetNumberOfBouquets:\n \n # womp womp, we can't make enough bouquets on this day, so set up for next iteration\n # the \"correct day\" is on the right side, so we get rid of all the \"incorrect days\" on the left side\n # by updating the left to the currentDay+1\n leftDay = currentDay+1\n else:\n \n # yay, we can make enough bouquets on this day, but we don't know if this is the \"minimum day\"\n # we discard the right side to keep searching\n rightDay = currentDay\n \n # leftDay >= rightDay, so we've found the \"minimum day\"\n return leftDay\n\t\t", "solution_js": "var minDays = function(bloomDay, m, k) {\n if (m * k > bloomDay.length) {\n return -1;\n }\n\n let left = 0;\n let right = 0;\n\n for (const day of bloomDay) {\n left = Math.min(day, left);\n right = Math.max(day, right);\n }\n\n let ans = right;\n\n while (left < right) {\n const day = Math.floor((left + right) / 2);\n\n let count = 0;\n let current = 0;\n\n for (let j = 0; j < bloomDay.length; j++) {\n if (bloomDay[j] <= day) {\n current++;\n } else {\n current = 0;\n }\n\n if (current === k) {\n count++;\n current = 0;\n }\n }\n\n if (count === m) {\n ans = Math.min(ans, day);\n }\n\n if (count < m) {\n left = day + 1;\n } else {\n right = day;\n }\n }\n\n return ans;\n};", "solution_java": "class Solution {\n public int minDays(int[] bloomDay, int m, int k) {\n if(m*k > bloomDay.length) return -1;\n \n int low = Integer.MAX_VALUE, high = 0;\n for(int i:bloomDay){\n low = Math.min(low,i);\n high = Math.max(high,i);\n }\n while(low<=high){\n int mid = low + (high-low)/2;\n if(isPossible(bloomDay,mid,m,k)) high = mid - 1;\n else low = mid + 1;\n }\n return low;\n }\n private boolean isPossible(int[] bloomDay,int maxDays,int m,int k){\n for(int i=0;i &v, int m, int k)\n {\n int n=v.size();\n int cnt=0;// taking cnt for the no of k adjacent bouquets possible\n for(int i=0;ichecking for adjacent count\n }\n cnt+=c/k;\n }\n }\n if(cnt>=m)\n return true;\n return false;\n\n }\n int minDays(vector& bloomDay, int m, int k) {\n int s=*min_element(bloomDay.begin(),bloomDay.end());\n int e=*max_element(bloomDay.begin(),bloomDay.end());\n int ans=e;\n if((m*k)>bloomDay.size())\n return -1;\n while(s<=e)\n {\n int mid=s+(e-s)/2;\n if(check(mid,bloomDay,m,k))\n {\n ans=mid;\n e=mid-1;\n }\n else\n s=mid+1;\n }\n return ans;\n }\n};" }, { "title": "Find the Winner of the Circular Game", "algo_input": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.\n\nThe rules of the game are as follows:\n\n\n\tStart at the 1st friend.\n\tCount the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.\n\tThe last friend you counted leaves the circle and loses the game.\n\tIf there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.\n\tElse, the last friend in the circle wins the game.\n\n\nGiven the number of friends, n, and an integer k, return the winner of the game.\n\n \nExample 1:\n\nInput: n = 5, k = 2\nOutput: 3\nExplanation: Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n\nExample 2:\n\nInput: n = 6, k = 5\nOutput: 1\nExplanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n\n\n \nConstraints:\n\n\n\t1 <= k <= n <= 500\n\n\n \nFollow up:\n\nCould you solve this problem in linear time with constant space?\n", "solution_py": "class Solution:\ndef findTheWinner(self, n: int, k: int) -> int:\n ls=list(range(1,n+1))\n while len(ls)>1:\n i=(k-1)%len(ls)\n ls.pop(i)\n ls=ls[i:]+ls[:i]\n \n return ls[0]", "solution_js": "/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar findTheWinner = function(n, k) {\n let friends = Array.from({length: n}, (_, index) => index + 1)\n let start = 0;\n while(friends.length != 1){\n start += (k - 1)\n start = start % friends.length\n friends.splice(start,1)\n }\n return friends[0]\n};", "solution_java": "class Solution {\n public int findTheWinner(int n, int k) {\n\t // Initialisation of the LinkedList\n LinkedList participants = new LinkedList<>();\n for (int i = 1; i <= n; i++) {\n\t\t participants.add(i);\n\t\t}\n\t\t\n\t\tint lastKilled = 0;\n\t\t// Run the game\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < k-1; j++) {\n\t\t\t participants.add(participants.poll());\n\t\t\t}\n lastKilled = participants.poll();\n }\n // Return the last one killed\n return lastKilled;\n }\n}", "solution_c": "class Solution {\npublic:\n int findTheWinner(int n, int k) {\n vectortemp;\n\n for(int i=1;i<=n;i++) temp.push_back(i);\n\n int i=0;\n\n while(temp.size()>1){\n int t=temp.size();\n i=(i+k-1)%t;\n temp.erase(temp.begin()+i);\n }\n return *temp.begin();\n }\n};" }, { "title": "Maximize Distance to Closest Person", "algo_input": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\n\nThere is at least one empty seat, and at least one person sitting.\n\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized. \n\nReturn that maximum distance to the closest person.\n\n \nExample 1:\n\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\n\n\nExample 2:\n\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\n\n\nExample 3:\n\nInput: seats = [0,1]\nOutput: 1\n\n\n \nConstraints:\n\n\n\t2 <= seats.length <= 2 * 104\n\tseats[i] is 0 or 1.\n\tAt least one seat is empty.\n\tAt least one seat is occupied.\n\n", "solution_py": "class Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n # strategy is greedy solution:\n # calculate local maximum for each interval: (b-a)//2\n # then take max of local maximums\n # the solution is O(n)\n # I find this solution clear, but uses 5 passes\n \n # get all the occupied seat nums\n seat_nums = [ix for ix, val in enumerate(seats) if val == 1]\n \n # check the ends\n left_max, right_max = min(seat_nums), len(seats)-max(seat_nums)-1\n \n # calculate max distance for each gap\n dists = [(y-x)//2 for x, y in zip(seat_nums, seat_nums[1:])]\n \n # take max of sitting on either end + each gap\n return max([left_max, right_max, *dists])", "solution_js": "/**\n * @param {number[]} seats\n * @return {number}\n */\nvar maxDistToClosest = function(seats) {\n let arr = seats.join('').split('1');\n for(let i = 0; i < arr.length;i++){\n if(arr[i] == '')\n arr[i] = 0;\n else{\n let middle = true;\n if(i == 0 || i == arr.length-1){\n arr[i] = arr[i].length;\n }else {\n arr[i] = Math.ceil(arr[i].length/2);\n }\n }\n }\n return arr.sort((a,b) => (a >= b)?-1:1)[0]\n};", "solution_java": "class Solution {\n public int maxDistToClosest(int[] seats) {\n int size = seats.length;\n int max = 0;\n int start = -1;\n int end = -1;\n\n for(int i = 0; i& seats) {\n vector d;\n int cnt = -1, ans = 0;\n\n for(int i=0; i 0 && i < d.size() - 1) d[i] /= 2;\n ans = max(ans, d[i]);\n }\n\n return ans;\n }\n};" }, { "title": "Reverse Words in a String III", "algo_input": "Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.\n\n \nExample 1:\nInput: s = \"Let's take LeetCode contest\"\nOutput: \"s'teL ekat edoCteeL tsetnoc\"\nExample 2:\nInput: s = \"God Ding\"\nOutput: \"doG gniD\"\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 * 104\n\ts contains printable ASCII characters.\n\ts does not contain any leading or trailing spaces.\n\tThere is at least one word in s.\n\tAll the words in s are separated by a single space.\n\n", "solution_py": "class Solution:\n def reverseWords(self, s: str) -> str:\n s = s + ' '\n l = len(s)\n t = ''\n w = ''\n for i in range(l):\n if s[i]!=' ':\n t = s[i] + t # t stores the word in reverse order\n else:\n\t\t\t\t# w stores the reversed word in the same order\n w = w + t + ' ' # could have used .join() function and not write .strip()\n t = \"\" # value of t is null so that it won't affect upcoming words\n return w.strip() # removes extra whitespace", "solution_js": "var reverseWords = function(s) {\n // make array of the words from s\n let words = s.split(\" \");\n for (let i in words) {\n\t // replace words[i] with words[i] but reversed\n words.splice(i, 1, words[i].split(\"\").reverse().join(\"\"))\n } return words.join(\" \");\n};", "solution_java": "class Solution {\n public String reverseWords(String s) {\n if(s == null || s.trim().equals(\"\")){\n return null;\n }\n String [] words = s.split(\" \");\n StringBuilder resultBuilder = new StringBuilder();\n for(String word: words){\n for(int i = word.length() - 1; i>=0; i --){\n resultBuilder.append(word.charAt(i));\n }\n resultBuilder.append(\" \");\n }\n return resultBuilder.toString().trim();\n }\n}", "solution_c": "Time: O(n+n) Space: O(1)\n\nclass Solution {\npublic:\n string reverseWords(string s) {\n int i,j;\n for( i=0,j=0;i int:\n @cache\n def dfs(i ,j):\n if i == 0 and j == 0: return 1\n elif i < 0 or j < 0: return 0\n \n return dfs(i-1, j) + dfs(i, j-1)\n return dfs(m-1, n-1)", "solution_js": "var uniquePaths = function(m, n) {\n let count = Array(m)\n for(let i=0; i\n#define vvi vector\nclass Solution {\npublic:\n \n int countPath(vvi& dp,int r,int c, int m , int n){\n if(m==r-1 || n==c-1)\n return 1;\n \n if(dp[m][n]!=-1)\n return dp[m][n];\n \n return dp[m][n] = countPath(dp,r,c,m+1,n) + countPath(dp,r,c,m,n+1);\n }\n int uniquePaths(int m, int n) {\n \n vvi dp(m,vi(n,-1));\n \n return countPath(dp,m,n,0,0);\n }\n};" }, { "title": "Count Number of Pairs With Absolute Difference K", "algo_input": "Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.\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,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n\n\nExample 2:\n\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\n\n\nExample 3:\n\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 200\n\t1 <= nums[i] <= 100\n\t1 <= k <= 99\n\n", "solution_py": "class Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n counter += seen[tmp2]\n \n seen[num] += 1\n \n return counter", "solution_js": "var countKDifference = function(nums, k) {\n nums = nums.sort((b,a) => b- a)\n let count = 0;\n\n for(let i = 0; i< nums.length; i++) {\n for(let j = i + 1; j< nums.length; j++) {\n if(Math.abs(nums[i] - nums[j]) == k) {\n count++\n }\n }\n }\n return count ;\n};", "solution_java": "class Solution {\n public int countKDifference(int[] nums, int k) {\n Map map = new HashMap<>();\n int res = 0;\n\n for(int i = 0;i< nums.length;i++){\n if(map.containsKey(nums[i]-k)){\n res+= map.get(nums[i]-k);\n }\n if(map.containsKey(nums[i]+k)){\n res+= map.get(nums[i]+k);\n }\n map.put(nums[i],map.getOrDefault(nums[i],0)+1);\n }\n\n return res;\n }\n}", "solution_c": "class Solution {\npublic:\n int countKDifference(vector& nums, int k) {\n unordered_map freq;\n int res = 0;\n\n for (auto num : nums) {\n res += freq[num+k] + freq[num-k];\n freq[num]++;\n }\n\n return res;\n }\n};" }, { "title": "Count Unreachable Pairs of Nodes in an Undirected Graph", "algo_input": "You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.\n\nReturn the number of pairs of different nodes that are unreachable from each other.\n\n \nExample 1:\n\nInput: n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput: 0\nExplanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.\n\n\nExample 2:\n\nInput: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput: 14\nExplanation: There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\t0 <= edges.length <= 2 * 105\n\tedges[i].length == 2\n\t0 <= ai, bi < n\n\tai != bi\n\tThere are no repeated edges.\n\n", "solution_py": "'''\n* Make groups of nodes which are connected\n eg., edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\n\n 0 ---- 2 1 --- 6 3\n | |\n | |\n 5 ---- 4\n\n groups will be {0: 4, 1: 2, 3: 1},\n i.e 4 nodes are present in group0, 2 nodes are present in group1 and 1 node is present in group3\n\n* Now, we have [4, 2, 1] as no of nodes in each group, we have to multiply each of no. with remaining\n ans = (4 * 2 + 4 * 1) + (2 * 1)\n but calculating ans this way will give TLE.\n\n* if we notice, (4 * 2 + 4 * 1) + (2 * 1), we can combine, equation like this,\n 4 * 2 + (4 + 2) * 1, using this, we can reduce complexity.\n so, if we have count of groups array as [a, b, c, d], ans will be,\n ans = a * b + (a + b) * c + (a + b + c) * d\n\n* will use, union for generating groups.\n* ps, you can modify UnionFind class as per your need. Have implemented full union-find for beginners.\n'''\n\nclass UnionFind:\n def __init__(self, size):\n self.root = [i for i in range(size)]\n self.rank = [1] * size\n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n rootX = self.find(x)\n rootY = self.find(y)\n if rootX != rootY:\n if self.rank[rootX] > self.rank[rootY]:\n self.root[rootY] = rootX\n elif self.rank[rootX] < self.rank[rootY]:\n self.root[rootX] = rootY\n else:\n self.root[rootY] = rootX\n self.rank[rootX] += 1\n\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]]) -> int:\n dsu = UnionFind(n)\n for u, v in edges:\n dsu.union(u, v)\n C = Counter([dsu.find(i) for i in range(n)])\n groupCounts = list(C.values())\n ans = 0\n firstGroupCount = groupCounts[0]\n for i in range(1, len(groupCounts)):\n ans += firstGroupCount * groupCounts[i]\n firstGroupCount += groupCounts[i]\n return ans", "solution_js": "var countPairs = function(n, edges) {\n const adj = [];\n\n for (let i = 0; i < n; i++) {\n adj.push([]);\n }\n \n for (let [from, to] of edges) {\n adj[from].push(to);\n adj[to].push(from);\n }\n \n const visited = new Set();\n\n function dfs(from) {\n visited.add(from);\n\n let count = 1;\n\n for (const to of adj[from]) {\n if (!visited.has(to)) {\n count += dfs(to);\n }\n }\n \n return count;\n }\n\n const groups = [];\n \n for (let i = 0; i < n; i++) {\n if (!visited.has(i)) {\n const count = dfs(i);\n groups.push(count);\n }\n }\n \n let ans = 0;\n \n for (let i = 0; i < groups.length - 1; i++) {\n for (let j = i + 1; j < groups.length; j++) {\n ans += groups[i] * groups[j];\n }\n }\n \n return ans;\n};", "solution_java": "class Solution {\n public long countPairs(int n, int[][] edges) {\n //Building Graph\n ArrayList < ArrayList < Integer >> graph = new ArrayList < > ();\n for (int i = 0; i < n; i++) graph.add(new ArrayList < Integer > ());\n for (int arr[]: edges) {\n graph.get(arr[0]).add(arr[1]);\n graph.get(arr[1]).add(arr[0]);\n }\n boolean visited[] = new boolean[n];\n long res = 0;\n int prev = 0;\n int count[] = {\n 0\n };\n for (int i = 0; i < graph.size(); i++) { // Running for loop on all connected components of graph\n if (visited[i] == true) continue; // if the node is alredy reached by any of other vertex then we don't need to terverse it again\n dfs(graph, i, visited, count);\n long a = n - count[0]; // (total - current count)\n long b = count[0] - prev; // (current count - prev )\n prev = count[0]; // Now Store count to prev\n res += (a * b);\n }\n return res;\n }\n void dfs(ArrayList < ArrayList < Integer >> graph, int v, boolean vis[], int count[]) {\n vis[v] = true;\n count[0]++; //for counting connected nodes\n for (int child: graph.get(v)) {\n if (!vis[child]) {\n dfs(graph, child, vis, count);\n }\n }\n }\n}", "solution_c": "class Solution {\npublic:\n typedef long long ll;\n void dfs(int node, unordered_map>& m, ll& cnt, vector& vis){\n vis[node] = 1;\n cnt++;\n for(auto& i: m[node]){\n if(vis[i]==0) dfs(i,m,cnt,vis); \n }\n }\n long long countPairs(int n, vector>& edges) {\n unordered_map> m; // making adjacency list\n for(int i=0;i vis(n,0);\n for(int i=0;i int:\n res = 0\n for i in range(32):\n if (a & 1) | (b & 1) != (c & 1):\n if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1\n res += 1\n else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1\n res += (a & 1) + (b & 1)\n a, b, c = a>>1, b>>1, c>>1 # right-shift by 1\n\n return res\n\n# Time: O(1)\n# Space: O(1)", "solution_js": "var minFlips = function(a, b, c) {\n let ans = 0;\n for(let bit = 0; bit < 32; bit++) {\n let bit_a = (a >> bit)&1, bit_b = (b >> bit)&1, bit_c = (c >> bit)&1;\n if(bit_c !== (bit_a | bit_b)) {\n if(bit_c === 1) { //a b will be 0 0\n ans += 1;\n } else { //a b -> 0 1 -> 1 0 -> 1 1\n ans += (bit_a + bit_b === 2 ? 2 : 1);\n }\n }\n }\n return ans;\n};", "solution_java": "class Solution {\n public int minFlips(int a, int b, int c) {\n int j=-1;\n int x=a|b;\n int count=0;\n while(c!=0 || x!=0){\n j++;\n int aa=x%2;\n int bb=c%2;\n if(aa==0 && bb==1)count++;\n else if(aa==1 && bb==0) count+=funcount(j,a,b);\n x=x>>1;\n c=c>>1;\n }\n return count;\n }\n public static int funcount(int shift,int a,int b){\n int cc=0;\n int mask=1<> i) & 1) == 1){\n lastBitA = 1;\n }\n if (((b >> i) & 1) == 1){\n lastBitB = 1;\n }\n if (((c >> i) & 1) == 1){\n lastBitC = 1;\n }\n if(lastBitC == 1){\n if(lastBitA == 0 & lastBitB == 0){\n changeBits++;\n }\n }\n else{\n if(lastBitA == 1 || lastBitB == 1){\n if(lastBitA == 1){\n changeBits++;\n }\n if(lastBitB == 1){\n changeBits++;\n }\n }\n }\n }\n return changeBits;\n }\n};" }, { "title": "Minimum Number of Swaps to Make the String Balanced", "algo_input": "You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.\n\nA string is called balanced if and only if:\n\n\n\tIt is the empty string, or\n\tIt can be written as AB, where both A and B are balanced strings, or\n\tIt can be written as [C], where C is a balanced string.\n\n\nYou may swap the brackets at any two indices any number of times.\n\nReturn the minimum number of swaps to make s balanced.\n\n \nExample 1:\n\nInput: s = \"][][\"\nOutput: 1\nExplanation: You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".\n\n\nExample 2:\n\nInput: s = \"]]][[[\"\nOutput: 2\nExplanation: You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".\n\n\nExample 3:\n\nInput: s = \"[]\"\nOutput: 0\nExplanation: The string is already balanced.\n\n\n \nConstraints:\n\n\n\tn == s.length\n\t2 <= n <= 106\n\tn is even.\n\ts[i] is either '[' or ']'.\n\tThe number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.\n\n", "solution_py": "class Solution:\n def minSwaps(self, s: str) -> int:\n res, bal = 0, 0\n for ch in s:\n bal += 1 if ch == '[' else -1\n if bal == -1:\n res += 1\n bal = 1\n return res", "solution_js": "/**\n * @param {string} s\n * @return {number}\n */\nvar minSwaps = function(s) {\n let stk = []\n for(let c of s){\n if(stk && c == ']') stk.pop()\n else if(c == '[') stk.push(c)\n }\n return (stk.length) / 2\n};", "solution_java": "class Solution {\n public int minSwaps(String s) {\n // remove the balanced part from the given string\n Stack stack = new Stack<>();\n for(char ch : s.toCharArray()) {\n if(ch == '[')\n stack.push(ch);\n else {\n if(!stack.isEmpty() && stack.peek() == '[')\n stack.pop();\n else\n stack.push(ch);\n }\n }\n int unb = stack.size()/2; // # of open or close bracket\n return (unb+1)/2;\n }\n}", "solution_c": "class Solution {\npublic:\n int minSwaps(string s) {\n int ans=0;\n stack stack;\n for(int i=0;i float:\n adj = [[] for i in range(n)]\n for u,v in edges:\n adj[u-1].append(v-1)\n adj[v-1].append(u-1)\n def f(u,p,tt):\n if(u==target-1): return tt==0 or len(adj[u])==(p>=0)\n if(tt==0): return 0\n res = 0\n for v in adj[u]:\n if(p==v): continue\n res = max(res,(1/(len(adj[u])-(p!=-1)))*f(v,u,tt-1))\n return res\n return f(0,-1,t)\n \n \n ", "solution_js": "/**\n * @param {number} n\n * @param {number[][]} edges\n * @param {number} t\n * @param {number} target\n * @return {number}\n */\nfunction dfs(n, map, t, target, visited, prop) {\n // edge case1: if run out of steps, cannot find target\n if(t === 0 && n !== target) return 0;\n // edge case2: if run out of steps, but found target\n if(t === 0 && n === target) return prop;\n\n visited.add(n);\n // get unvisited children/neighbors\n const validChildren = [];\n (map[n] ?? []).forEach((child) => {\n if(!visited.has(child)) validChildren.push(child);\n })\n // edge case3, if still more steps to use, but no more children to move,\n // if already at the targeted node, should just return\n if(n === target && t > 0 && !validChildren.length) return prop;\n // edge case4, if still more steps to use and no more children to move,\n // but current node is not target node, cannot find target, return 0\n if(n !== target && t > 0 && !validChildren.length) return 0;\n\n // go to next valid child/neighbor\n for(let i = 0; i < validChildren.length; i ++) {\n if(visited.has(validChildren[i])) continue;\n let result = dfs(validChildren[i], map, t - 1, target, visited, prop * (1 / validChildren.length))\n if(result !== 0) return result;\n }\n\n return 0;\n}\n\nvar frogPosition = function(n, edges, t, target) {\n const map = new Array(n + 1);\n // make bidirectional edge map\n edges.forEach(item => {\n if(!map[item[0]]) map[item[0]] = [];\n if(!map[item[1]]) map[item[1]] = [];\n map[item[0]].push(item[1]);\n map[item[1]].push(item[0]);\n });\n\n return dfs(1, map, t, target, new Set(), 1);\n};", "solution_java": "class Solution {\n public double frogPosition(int n, int[][] edges, int t, int target) {\n \n List> graph=new ArrayList<>();\n for(int i=0;i<=n;i++) graph.add(new ArrayList<>());\n \n for(int i=0;i> graph,int ver,int t,int tar,boolean[] vis){\n \n int count=0;\n for(Integer child:graph.get(ver)){\n if(!vis[child]) count++;\n }\n \n \n vis[ver]=true;\n if(t<0) return 0;\n \n if(ver==tar){\n if(count==0 || t==0) return 1.0;\n }\n \n if(graph.get(ver).size()==0) return 0;\n \n double ans=0.0;\n \n \n for(Integer child:graph.get(ver)){\n\n // System.out.println(child);\n if(!vis[child])\n ans+=(double)(1.0/count)*Sol(graph,child,t-1,tar,vis);\n }\n // System.out.println(ans);\n vis[ver]=false;\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n double frogPosition(int n, vector>& edges, int t, int target) {\n unordered_map> adjList;\n for(const auto& edge : edges) {\n adjList[edge[0]].push_back(edge[1]);\n adjList[edge[1]].push_back(edge[0]);\n }\n\n // BFS way\n queue> Q;\n Q.push({1, 1.0});\n int time = 0;\n vector visited(n+1, false);\n\n while(not Q.empty()) {\n int size = Q.size();\n\n if (time > t) break;\n\n while(size--) {\n auto pp = Q.front(); Q.pop();\n int node = pp.first;\n double prob = pp.second;\n\n visited[node] = true;\n\n // Count the unvisited nbr\n int nbrCount = 0;\n for(auto& nbr : adjList[node]) {\n if (not visited[nbr]) nbrCount++;\n }\n\n if (node == target) {\n if (time == t) return prob;\n if (time < t) {\n // Check if any unvisited ? if yes, then frog would jump there and not be able to jump back here\n if (nbrCount > 0) return 0.0;\n\n // else return the same prob\n return prob;\n }\n }\n\n for(auto& nbr : adjList[node]) {\n if (not visited[nbr]) {\n // update the prob as it will be divided by number of nbr\n Q.push({nbr, (prob * (1.0/nbrCount))});\n }\n }\n }\n\n time++;\n }\n\n return 0.0;\n }\n};" }, { "title": "Minimum Sideway Jumps", "algo_input": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.\n\nYou are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.\n\n\n\tFor example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.\n\n\nThe frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.\n\n\n\tFor example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.\n\n\nReturn the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.\n\nNote: There will be no obstacles on points 0 and n.\n\n \nExample 1:\n\nInput: obstacles = [0,1,2,3,0]\nOutput: 2 \nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n\n\nExample 2:\n\nInput: obstacles = [0,1,1,3,3,0]\nOutput: 0\nExplanation: There are no obstacles on lane 2. No side jumps are required.\n\n\nExample 3:\n\nInput: obstacles = [0,2,1,0,3,0]\nOutput: 2\nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n\n\n \nConstraints:\n\n\n\tobstacles.length == n + 1\n\t1 <= n <= 5 * 105\n\t0 <= obstacles[i] <= 3\n\tobstacles[0] == obstacles[n] == 0\n\n", "solution_py": "class Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n \n \"\"\"\n # TLE Recursion DP\n @cache\n def dp(curr_lane = 2, point = 0):\n if point == len(obstacles)-1:\n return 0\n if obstacles[point+1] == curr_lane:\n return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n \n return dp(curr_lane, point+1)\n \n \n return dp()\n \n \"\"\"\n \n n = len(obstacles) \n dp = [[0, 0, 0, 0] for _ in range(n)]\n \n for point in range(n-2, -1, -1):\n for curr_lane in range(4):\n if obstacles[point+1] == curr_lane:\n dp[point][curr_lane] = min(dp[point+1][lane] for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1\n else:\n dp[point][curr_lane] = dp[point+1][curr_lane]\n \n return dp[0][2]", "solution_js": "var minSideJumps = function(obstacles) {\n // create a dp cache for tabulation\n const dp = [...obstacles].map(() => new Array(4).fill(Infinity));\n \n // initialize the first positions\n dp[0][2] = 0;\n for (const lane of [1,3]) {\n if (obstacles[0] === lane) continue;\n dp[0][lane] = 1;\n }\n\n // for every index we will do the following\n for (let i = 1; i < obstacles.length; i++) {\n \n // first we find the best way to get to this position from the previous index\n for (let nextLane = 1; nextLane <= 3; nextLane++) {\n if (obstacles[i] === nextLane) continue;\n dp[i][nextLane] = dp[i - 1][nextLane]\n }\n \n // then we find the best way to get to this position from the current index;\n for (let nextLane = 1; nextLane <= 3; nextLane++) {\n for (let prevLane = 1; prevLane <= 3; prevLane++) {\n if (prevLane === nextLane) continue;\n if (obstacles[i] === nextLane) continue;\n dp[i][nextLane] = Math.min(dp[i][nextLane], dp[i][prevLane] + 1)\n }\n }\n }\n\n // return the best result after reaching the end\n return Math.min(...dp[dp.length - 1])\n};", "solution_java": "class Solution {\n public int minSideJumps(int[] obstacles) {\n int[] dp = new int[]{1, 0, 1};\n for(int i=1; i=0) min = Math.min(min, val);\n }\n return min;\n }\n}", "solution_c": "class Solution {\npublic:\n int func(int i,int l,vector&obstacles,vector>&dp){\n if(i==obstacles.size()-2){\n if(obstacles[i+1]==l)return 1;\n return 0;\n }\n\n if(dp[i][l]!=-1)return dp[i][l];\n\n if(obstacles[i+1]!=l){\n return dp[i][l] = func(i+1,l,obstacles,dp);\n }\n\n \n int b=INT_MAX;\n for(int j=1;j<=3;j++){\n if(l==j)continue;\n if(obstacles[i]==j)continue;\n b=min(b,1+func(i,j,obstacles,dp));\n }\n \n\n return dp[i][l] = b;\n }\n\n int minSideJumps(vector& obstacles) {\n int n=obstacles.size();\n vector>dp(n,vector(4,-1));\n return func(0,2,obstacles,dp);\n }\n};" }, { "title": "Minimum Number of Operations to Move All Balls to Each Box", "algo_input": "You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.\n\nIn one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\n\nReturn an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.\n\nEach answer[i] is calculated considering the initial state of the boxes.\n\n \nExample 1:\n\nInput: boxes = \"110\"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n\n\nExample 2:\n\nInput: boxes = \"001011\"\nOutput: [11,8,5,4,3,4]\n\n \nConstraints:\n\n\n\tn == boxes.length\n\t1 <= n <= 2000\n\tboxes[i] is either '0' or '1'.\n\n", "solution_py": "class Solution:\n def minOperations(self, boxes: str) -> List[int]:\n ans = [0]*len(boxes)\n leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n for i in range(1, n):\n if boxes[i-1] == '1': leftCount += 1\n leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n ans[i] = leftCost\n for i in range(n-2, -1, -1):\n if boxes[i+1] == '1': rightCount += 1\n rightCost += rightCount\n ans[i] += rightCost\n return ans", "solution_js": " var minOperations = function(boxes) {\n \n const ans = new Array(boxes.length).fill(0);\n\n let ballsLeft = 0, ballsRight = 0;\n let movesLeft = 0, movesRight = 0;\n\n const len = boxes.length - 1;\n \n for(let i = 0; i <= len; i++) {\n \n movesLeft += ballsLeft;\n movesRight += ballsRight;\n ans[i] += movesLeft;\n ans[len - i] += movesRight;\n ballsLeft += +boxes[i];\n ballsRight += +boxes[len - i];\n }\n\n return ans;\n};", "solution_java": "class Solution{\n public int[] minOperations(String boxes){\n int n = boxes.length();\n int[] ans = new int[n];\n for(int i=0; i minOperations(string boxes) {\n int n = boxes.size();\n vector ans;\n for(int i = 0; i < n; i++)\n {\n int res = 0;\n for(int j = 0; j < n; j++)\n {\n if(boxes[j] == '1')\n {\n res += abs(i-j);\n }\n }\n ans.push_back(res);\n }\n return ans;\n }\n};" }, { "title": "Dungeon Game", "algo_input": "The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.\n\nThe knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.\n\nSome of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).\n\nTo reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n\nReturn the knight's minimum initial health so that he can rescue the princess.\n\nNote that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n\n \nExample 1:\n\nInput: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput: 7\nExplanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\n\n\nExample 2:\n\nInput: dungeon = [[0]]\nOutput: 1\n\n\n \nConstraints:\n\n\n\tm == dungeon.length\n\tn == dungeon[i].length\n\t1 <= m, n <= 200\n\t-1000 <= dungeon[i][j] <= 1000\n\n", "solution_py": "class Solution:\n\n\n\tdef calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n\n\t\tdp = defaultdict(lambda: inf)\n\t\tdp[(len(dungeon), len(dungeon[0]) - 1)] = 1\n\n\t\tfor i in range(len(dungeon) - 1, -1, -1):\n\n\t\t\tfor j in range(len(dungeon[0]) - 1, -1, -1):\n\n\t\t\t\tdp[(i, j)] = min(dp[(i + 1, j)], dp[(i, j + 1)]) - dungeon[i][j]\n\n\t\t\t\tif dp[(i, j)] <= 0:\n\t\t\t\t\tdp[(i, j)] = 1\n\n\t\treturn dp[(0, 0)]", "solution_js": "/**\n * The dynamic programming solution.\n * \n * Time Complexity: O(m*n)\n * Space Complexity: O(1)\n * \n * @param {number[][]} dungeon\n * @return {number}\n */\nvar calculateMinimumHP = function(dungeon) {\n\tconst m = dungeon.length\n\tconst n = dungeon[0].length\n\n\tconst ii = m - 1\n\tconst jj = n - 1\n\n\tfor (let i = ii; i >= 0; i--) {\n\t\tfor (let j = jj; j >= 0; j--) {\n\t\t\tif (i < ii || j < jj) {\n\t\t\t\tconst hc = dungeon[i][j]\n\n\t\t\t\tconst hp1 = (i < ii) ? Math.min(hc, hc + dungeon[i + 1][j]) : -Infinity\n\t\t\t\tconst hp2 = (j < jj) ? Math.min(hc, hc + dungeon[i][j + 1]) : -Infinity\n\n\t\t\t\tdungeon[i][j] = Math.max(hp1, hp2)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn Math.max(1 - dungeon[0][0], 1)\n}", "solution_java": "class Solution {\n Integer[][] min;\n public int calculateMinimumHP(int[][] dungeon) {\n min = new Integer[dungeon.length][dungeon[0].length];\n int answer = min(0, 0, dungeon);\n return Math.max(answer, 1);\n }\n public int min(int i, int j, int[][] dungeon){\n if(i > dungeon.length - 1 || j > dungeon[0].length - 1) return 400000;\n if(i == dungeon.length - 1 && j == dungeon[0].length - 1) return - dungeon[i][j] + 1; \n if(min[i][j] == null){\n int down = min(i + 1, j, dungeon);\n int right = min(i, j + 1, dungeon);\n min[i][j] = Math.min(Math.max(right, 1), Math.max(down, 1)) - dungeon[i][j];\n }\n return min[i][j];\n }\n}", "solution_c": "class Solution {\npublic:\n int solve(int i, int j, int m , int n, vector> &grid)\n {\n // if we come out of the grid simply return a large value\n if(i >= m || j >= n)\n return INT_MAX;\n \n // calucate health by the 2 possible ways\n int down = solve(i + 1, j, m, n, grid);\n int right = solve(i, j + 1, m, n, grid);\n \n\t\t// take the min both both\n int health = min(down, right);\n \n // we reach the destination when both the sides return INT_MAX\n if(health == INT_MAX)\n {\n health = 1; // both are +ve large integers so min health required = 1\n }\n \n int ans = 0;\n if(health - grid[i][j] > 0)\n {\n ans = health - grid[i][j];\n }\n else\n {\n ans = 1;\n }\n \n return ans;\n }\n \n int calculateMinimumHP(vector>& dungeon) \n {\n int m = dungeon.size();\n int n = dungeon[0].size();\n \n return solve(0, 0, m, n, dungeon);\n }\n};" }, { "title": "The K Weakest Rows in a Matrix", "algo_input": "You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.\n\nA row i is weaker than a row j if one of the following is true:\n\n\n\tThe number of soldiers in row i is less than the number of soldiers in row j.\n\tBoth rows have the same number of soldiers and i < j.\n\n\nReturn the indices of the k weakest rows in the matrix ordered from weakest to strongest.\n\n \nExample 1:\n\nInput: mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput: [2,0,3]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].\n\n\nExample 2:\n\nInput: mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput: [0,2]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].\n\n\n \nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t2 <= n, m <= 100\n\t1 <= k <= m\n\tmatrix[i][j] is either 0 or 1.\n\n", "solution_py": "class Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n\n row = []\n for i in range(len(mat)):\n row.append((sum(mat[i]), i))\n\n row.sort()\n ans = [idx for (val, idx) in row[:k]]\n\n return ans", "solution_js": "/**\n * @param {number[][]} mat\n * @param {number} k\n * @return {number[]}\n\n * S: O(N)\n * T: O(N*logN)\n */\nvar kWeakestRows = function(mat, k) {\n return mat.reduce((acc, row, index) => {\n let left = 0;\n let right = row.length - 1;\n\n while(left <= right) {\n let mid = Math.floor( (left + right) / 2);\n\n if(row[mid]) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n\n acc.push({ index, value: left });\n\n return acc;\n }, []).sort((a, b) => a.value - b.value).splice(0, k).map(item => item.index);\n};", "solution_java": "class Solution {\n public int[] kWeakestRows(int[][] mat, int k) {\n Map map = new HashMap<>();\n List list = new ArrayList<>();\n int[] arr = new int[k];\n for (int i = 0; i < mat.length; i++){\n int n = getBits(mat[i]);\n map.put(i, n);\n list.add(n);\n }\n Collections.sort(list);\n int z = 0;\n for (int i = 0; i < k; i++){\n for (Map.Entry m : map.entrySet()){\n if (list.get(i).equals(m.getValue())){\n arr[z++] = m.getKey();\n map.remove(m.getKey(), m.getValue());\n break;\n }\n }\n }\n\n return arr;\n }\n\n private static Integer getBits(int[] arr) {\n int count = 0;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == 1) count++;\n }\n\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n vector kWeakestRows(vector>& mat, int k) {\n // \n vector> freqMapper;\n int civilian = 0;\n for(int i=0; i pair1, pair pair2) {\n if (pair1.second > pair2.second) {\n return true;\n } else if (pair1.second == pair2.second) {\n return pair1.first < pair2.first;\n }\n return pair1.second > pair2.second;\n });\n vector kWeakest;\n for(int i=0; i List[int]:\n col, row = len(matrix[0]), len(matrix)\n l, t, r, b = 0, 0, col - 1, row - 1\n res = []\n while l <= r and t <= b:\n for i in range(l, r):\n res.append(matrix[t][i])\n for i in range(t, b):\n res.append(matrix[i][r])\n \n\t\t\t# Append the orphan left by the open interval\n if t == b:\n res.append(matrix[t][r])\n else:\n # From right to left at the bottom\n for i in range(r, l, -1):\n res.append(matrix[b][i])\n \n\t\t\t# Avoid duplicated appending if it is a square\n if l == r and t != b:\n res.append(matrix[b][r])\n else:\n # From bottom to top at the left\n for i in range(b, t, -1):\n res.append(matrix[i][l])\n l += 1\n t += 1\n r -= 1\n b -= 1\n\n return res", "solution_js": "/**\n * @param {number[][]} matrix\n * @return {number[]}\n */\nvar spiralOrder = function(matrix) {\n let [top, bot, left, right, ans] = [0, matrix.length - 1, 0, matrix[0].length - 1,[]]\n\n while ((top <= bot) && (left <= right)) {\n for (let j = left; j <= right; j++) {\n ans.push(matrix[top][j])\n }\n top ++;\n for (let i = top; i <= bot; i++) {\n ans.push(matrix[i][right])\n }\n right --;\n if ((bot < top) || (right < left)) {\n break\n }\n for (let j = right; left <= j; j--){\n ans.push(matrix[bot][j])\n }\n bot --;\n for (let i = bot; top <= i; i--){\n ans.push(matrix[i][left])\n }\n left ++;\n }\n return ans\n}", "solution_java": "class Solution {\n public List spiralOrder(int[][] matrix) {\n List ans = new ArrayList<>();\n int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;\n\n while (top <= bottom && left <= right) \n {\n for (int i = left; i <= right; i++)\n ans.add(matrix[top][i]);\n top++;\n\n for (int i = top; i <= bottom; i++)\n ans.add(matrix[i][right]);\n right--;\n\n if (top <= bottom) {\n for (int i = right; i >= left; i--)\n ans.add(matrix[bottom][i]);\n bottom--;\n }\n\n if (left <= right) {\n for (int i = bottom; i >= top; i--)\n ans.add(matrix[i][left]);\n left++;\n }\n }\n return ans;\n }\n}", "solution_c": "class Solution {\npublic:\n\n vector _res;\n vector> _visited;\n\n void spin(vector>& matrix, int direction, int i, int j) {\n\n _visited[i][j] = true;\n _res.push_back(matrix[i][j]);\n\n switch (direction){\n // left to right\n case 0:\n if ( j+1 >= matrix[0].size() || _visited[i][j+1]) {\n direction = 1;\n i++;\n } else {\n j++;\n }\n break;\n // up to bottom\n case 1:\n if ( i+1 >= matrix.size() || _visited[i+1][j]) {\n direction = 2;\n j--;\n } else {\n i++;\n }\n break;\n // right to left\n case 2:\n if ( j == 0 || _visited[i][j-1]) {\n direction = 3;\n i--;\n } else {\n j--;\n }\n break;\n // bottom to up\n case 3:\n if ( i == 0 || _visited[i-1][j]) {\n direction = 0;\n j++;\n } else {\n i--;\n }\n break;\n }\n if ( i < 0 || i >= matrix.size() || j < 0 || j >= matrix[0].size() ) {\n return;\n }\n if ( _visited[i][j] ) {\n return;\n }\n spin(matrix, direction, i, j);\n }\n \n vector spiralOrder(vector>& matrix) {\n _res.clear();\n _visited = vector>(matrix.size(), std::vector(matrix[0].size(), false));\n spin(matrix, 0, 0, 0);\n return _res;\n }\n};" }, { "title": "Random Pick Index", "algo_input": "Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.\n\nImplement the Solution class:\n\n\n\tSolution(int[] nums) Initializes the object with the array nums.\n\tint pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.\n\n\n \nExample 1:\n\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\nOutput\n[null, 4, 0, 2]\n\nExplanation\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n\n\n \nConstraints:\n\n\n\t1 <= nums.length <= 2 * 104\n\t-231 <= nums[i] <= 231 - 1\n\ttarget is an integer from nums.\n\tAt most 104 calls will be made to pick.\n\n", "solution_py": "class Solution:\n\n def __init__(self, nums: List[int]):\n #self.nums = nums\n #create a hash of values with their list of indices\n self.map = defaultdict(list)\n for i,v in enumerate(nums):\n self.map[v].append(i)\n \n\n def pick(self, target: int) -> int:\n return random.sample(self.map[target],1)[0]\n '''\n reservoir = 0\n count = 0\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n count+=1\n if random.random() < 1/count:\n reservoir = i\n return reservoir\n\n \n samp = []\n for i in range(len(self.nums)):\n if self.nums[i] == target:\n samp.append(i)\n return (random.sample(samp,1))[0]\n '''\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(nums)\n# param_1 = obj.pick(target)", "solution_js": "var Solution = function(nums) {\n this.map = nums.reduce((result, num, index) => {\n const value = result.get(num) ?? [];\n\n value.push(index);\n result.set(num, value);\n return result;\n }, new Map());\n};\n\nSolution.prototype.pick = function(target) {\n const pick = this.map.get(target);\n const random = Math.random() * pick.length | 0;\n\n return pick[random];\n};", "solution_java": "class Solution {\n ArrayList ll=new ArrayList<>();\n public Solution(int[] nums) {\n for(int i=0;i> itemIndicies;\npublic:\n Solution(vector& nums)\n {\n srand(time(NULL));\n \n for (int i = 0; i < nums.size(); i++)\n {\n if (itemIndicies.find(nums[i]) == itemIndicies.end())\n itemIndicies[nums[i]] = {i};\n else\n itemIndicies[nums[i]].push_back(i);\n }\n }\n \n int pick(int target) {\n int size = itemIndicies[target].size();\n int randomValue = rand() % size;\n return itemIndicies[target][randomValue];\n }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution* obj = new Solution(nums);\n * int param_1 = obj->pick(target);\n */" }, { "title": "Check if All Characters Have Equal Number of Occurrences", "algo_input": "Given a string s, return true if s is a good string, or false otherwise.\n\nA string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).\n\n \nExample 1:\n\nInput: s = \"abacbc\"\nOutput: true\nExplanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.\n\n\nExample 2:\n\nInput: s = \"aaabb\"\nOutput: false\nExplanation: The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.\n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 1000\n\ts consists of lowercase English letters.\n\n", "solution_py": "class Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1", "solution_js": "var areOccurrencesEqual = function(s) {\n var freq = {}\n for (let c of s) freq[c] = (freq[c] || 0) + 1\n var val = freq[s[0]]\n for (let c in freq) if (freq[c] && freq[c] != val) return false;\n return true;\n};", "solution_java": "class Solution {\n public boolean areOccurrencesEqual(String s) {\n int[] freq = new int[26];\n \n for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-'a']++;\n\n int val = freq[s.charAt(0) - 'a'];\n for (int i = 0; i < 26; i++)\n if (freq[i] != 0 && freq[i] != val) return false; \n\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool areOccurrencesEqual(string s) {\n unordered_map freq;\n for (auto c : s) freq[c]++;\n int val = freq[s[0]];\n for (auto [a, b] : freq) if (b != val) return false;\n return true;\n }\n};" }, { "title": "Palindrome Partitioning IV", "algo_input": "Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​\n\nA string is said to be palindrome if it the same string when reversed.\n\n \nExample 1:\n\nInput: s = \"abcbdd\"\nOutput: true\nExplanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n\n\nExample 2:\n\nInput: s = \"bcbddxy\"\nOutput: false\nExplanation: s cannot be split into 3 palindromes.\n\n\n \nConstraints:\n\n\n\t3 <= s.length <= 2000\n\ts​​​​​​ consists only of lowercase English letters.\n\n", "solution_py": "class Solution:\n def checkPartitioning(self, s: str) -> bool:\n n = len(s)\n\n @lru_cache(None)\n def pal(i,j):\n if i == j:\n return True\n if s[i] != s[j]:\n return False\n if i+1 == j:\n return True\n else:\n return pal(i+1,j-1)\n\n for i in range(n-2):\n if pal(0,i):\n for j in range(i+1,n-1):\n if pal(i+1,j) and pal(j+1,n-1):\n return True\n return False", "solution_js": "/**\n * @param {string} s\n * @return {boolean}\n */\nvar checkPartitioning = function(s) {\n // create a dp that will represent the starting and ending index of a substring\n // if dp[i][j] is true that means that the string starting from i and ending at j is a palindrome\n const dp = new Array(s.length).fill(null).map(() => new Array(s.length).fill(false));\n \n // all substrings of length 1 are palindromes so we mark all matching indices as true\n for (let i = 0; i < s.length; i++) {\n dp[i][i] = true;\n }\n \n \n // slowly grow the substring from each index\n // we will know the substring is a palindrom if the substring prior was a palindrome\n for (let lengthOfSubString = 2; lengthOfSubString <= s.length; lengthOfSubString++) {\n for (let startingIndex = 0; startingIndex + lengthOfSubString <= s.length; startingIndex++) {\n \n // if it's not the same character, then it can not be a palindrome\n if (s[startingIndex] !== s[startingIndex + lengthOfSubString - 1]) continue;\n \n if (lengthOfSubString <= 3 || \n \n // this checks if the prior substring was a palindrome\n dp[startingIndex + 1][startingIndex + lengthOfSubString - 2]) {\n \n dp[startingIndex][startingIndex + lengthOfSubString - 1] = true;\n }\n }\n }\n \n // find out if any 3 of the partitions are palindromes\n for (let i = 0; i < s.length; i++) {\n for (let j = i + 1; j < s.length; j++) {\n if (dp[0][i] && dp[i + 1][j] && dp[j + 1][s.length - 1]) return true;\n }\n }\n \n // if we haven't found a partition, return false\n return false;\n};", "solution_java": "class Solution {\n public boolean checkPartitioning(String s) {\n int n = s.length();\n boolean[][] dp = new boolean[n][n];\n for(int g=0 ; g> dp1;\n\tbool isPalindrome(string& s, int i, int j) {\n\t\tif (i >= j) return true;\n\t\tif (dp1[i][j] != -1) return dp1[i][j];\n\t\tif (s[i] == s[j]) return dp1[i][j] = isPalindrome(s, i + 1, j - 1);\n\t\treturn dp1[i][j] = false;\n\t}\n\tbool checkPartitioning(string s) {\n\t\tint n = s.size();\n\t\tdp1.resize(n,vector (n,-1));\n\t\tfor(int i=0;i list[str]:\n\n # Initialize the result\n res = []\n\n # Recursively go through all possible combinations\n def add(open, close, partialRes):\n\n nonlocal res\n\n # If we have added opening and closing parentheses n times, we reaches a solution\n if open == close == n:\n res.append(\"\".join(partialRes))\n return\n\n # Add a closing parenthesis to the partial result if we have at least 1 opening parenthesis\n if close < open:\n add(open, close + 1, partialRes + [\")\"])\n\n # Add an opening parenthesis to the partial result if we haven't added n parenthesis yet\n if open < n:\n add(open + 1, close, partialRes + [\"(\"])\n\n add(0, 0, [])\n\n return res", "solution_js": "var generateParenthesis = function(n) {\n let ans = []\n generate_parenthisis(n, 0, 0, \"\")\n return ans\n\n function generate_parenthisis(n, open, close, res){\n\n if(open==n && close == n){\n ans.push(res)\n return\n }\n\n if(open s = new ArrayList<>();\n public void get(int n, int x, String p)\n {\n if(n==0 && x==0)\n {\n s.add(p);\n return;\n }\n if(n==0)\n {\n get(n,x-1,p+\")\");\n }\n else if(x==0)\n {\n get(n-1,x+1,p+\"(\");\n }\n else\n {\n get(n,x-1,p+\")\");\n get(n-1,x+1,p+\"(\");\n }\n }\n public List generateParenthesis(int n) \n {\n s.clear();\n get(n,0,\"\");\n return s;\n }\n}", "solution_c": "class Solution {\npublic:\n vector generateParenthesis(int n) {\n vector ans;\n \n generate(ans,\"\",n,n);\n \n return ans;\n }\n \n void generate(vector &ans,string s,int open,int close)\n {\n if(open == 0 && close == 0)\n {\n ans.push_back(s);\n return ;\n }\n \n if(open > 0)\n {\n generate(ans,s+'(',open-1,close);\n }\n \n if(open < close)\n {\n generate(ans,s+')',open,close-1);\n }\n }\n};" }, { "title": "Largest Combination With Bitwise AND Greater Than Zero", "algo_input": "The bitwise AND of an array nums is the bitwise AND of all integers in nums.\n\n\n\tFor example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.\n\tAlso, for nums = [7], the bitwise AND is 7.\n\n\nYou are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.\n\nReturn the size of the largest combination of candidates with a bitwise AND greater than 0.\n\n \nExample 1:\n\nInput: candidates = [16,17,71,62,12,24,14]\nOutput: 4\nExplanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.\n\n\nExample 2:\n\nInput: candidates = [8,8]\nOutput: 2\nExplanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.\n\n\n \nConstraints:\n\n\n\t1 <= candidates.length <= 105\n\t1 <= candidates[i] <= 107\n\n", "solution_py": "class Solution:\n def largestCombination(self, candidates: List[int]) -> int:\n return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))", "solution_js": "var largestCombination = function(candidates) {\n const indexArr=Array(24).fill(0)\n\n for(let candidate of candidates){\n let index =0\n while(candidate>0){\n if((candidate&1)===1)indexArr[index]+=1\n candidate>>>=1\n index++\n }\n }\n\n return Math.max(...indexArr)\n};", "solution_java": "class Solution {\n public static int largestCombination(int[] candidates) {\n\t\tint arr[] = new int[32];\n\t\tfor (int i = 0; i < candidates.length; i++) {\n\t\t\tString temp = Integer.toBinaryString(candidates[i]);\n\t\t\tint n = temp.length();\n\t\t\tint index = 0;\n\t\t\twhile (n-- > 0) {\n\t\t\t\tarr[index++] += temp.charAt(n) - '0';\n\t\t\t}\n\t\t}\n\t\tint res = Integer.MIN_VALUE;\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tres = Math.max(res, arr[i]);\n\t\t}\n\t\treturn res;\n\t}\n}", "solution_c": "class Solution {\npublic:\n int largestCombination(vector& candidates) {\n vector bits(32);\n for(int i = 0; i < candidates.size(); i++){\n int temp = 31;\n while(candidates[i] > 0){\n bits[temp] += candidates[i] % 2;\n candidates[i] = candidates[i] / 2;\n temp--;\n }\n }\n int ans = 0;\n for(int i = 0; i < 32; i++){\n //cout< a[1] - b[1]));\n\t//use the index sorted by distance to get the result\n let i = 0;\n for(const x of hashMapNew.keys()) {\n\t\t//do it k times\n if(i === k) break;\n res.push(points[x]);\n i++;\n }\n return res;\n};\nvar calcDis = (b) => {\n return Math.sqrt( Math.pow(b[0], 2) + Math.pow(b[1], 2) );\n}", "solution_java": "class Solution {\n static class Distance {\n int i;\n int j;\n double dist;\n\n public Distance(int i, int j, double dist) {\n this.i = i;\n this.j = j;\n this.dist = dist;\n }\n }\n\n public int[][] kClosest(int[][] points, int k) {\n PriorityQueue pq = new PriorityQueue<>((x,y) -> Double.compare(x.dist, y.dist));\n for(int[] point : points) {\n double dist = calcDistance(point[0], point[1]);\n pq.offer(new Distance(point[0], point[1], dist));\n }\n int cnt = 0;\n ArrayList l = new ArrayList<>();\n while(cnt < k) {\n Distance d = pq.poll();\n l.add(new int[]{d.i, d.j});\n cnt++;\n }\n int[][] res = l.toArray(new int[l.size()][]);\n return res;\n }\n\n private double calcDistance(int i, int j) {\n double dist = Math.sqrt(Math.pow(i,2) + Math.pow(j,2));\n return dist;\n }\n}", "solution_c": "class Solution {\npublic:\n vector> kClosest(vector>& points, int k)\n {\n //max heap\n priority_queue>> pq;//first integer is distance(no need for sq root as comparison is same and next part of pair is coordinate\n int n= points.size();\n for(int i=0;ik)\n pq.pop();\n }\n vector> ans;\n while(!pq.empty())\n {\n vector temp={(pq.top().second.first),pq.top().second.second};\n ans.push_back(temp);\n pq.pop();\n }\n return ans;\n }\n};" }, { "title": "All Nodes Distance K in Binary Tree", "algo_input": "Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.\n\nYou can return the answer in any order.\n\n \nExample 1:\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput: [7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\n\n\nExample 2:\n\nInput: root = [1], target = 1, k = 3\nOutput: []\n\n\n \nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 500].\n\t0 <= Node.val <= 500\n\tAll the values Node.val are unique.\n\ttarget is the value of one of the nodes in the tree.\n\t0 <= k <= 1000\n\n", "solution_py": "class Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n\n # DFS to make the adj List\n adjList = defaultdict(list)\n def dfs(node):\n if not node:\n return\n\n if node.left:\n adjList[node].append(node.left)\n adjList[node.left].append(node)\n\n if node.right:\n adjList[node].append(node.right)\n adjList[node.right].append(node)\n dfs(node.left)\n dfs(node.right)\n\n dfs(root)\n\n # bfs to find the nodes with k distance\n\n q = deque([(target, 0)])\n visit = set()\n visit.add(target)\n res = []\n while q:\n for i in range(len(q)):\n node, dist = q.popleft()\n\n if dist == k:\n res.append(node.val)\n\n if dist > k:\n break\n for nei in adjList[node]:\n if nei not in visit:\n visit.add(nei)\n q.append((nei, dist + 1))\n return res", "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val) {\n * this.val = val;\n * this.left = this.right = null;\n * }\n */\n/**\n * @param {TreeNode} root\n * @param {TreeNode} target\n * @param {number} k\n * @return {number[]}\n */\nvar distanceK = function(root, target, k) {\n if(k === 0)\n return [target.val];\n\n let res = [];\n\n const helper = (node, k, bool) => {\n if(node === null)\n return [false, 0];\n\n if(k === 0 && node.val !== target.val) {\n res.push(node.val);\n return null;\n }\n\n if(bool) {\n helper(node.left, k - 1, bool);\n helper(node.right, k - 1, bool);\n return null;\n }\n\n if(node.val === target.val) {\n //Here nodes of k distance are at bottom\n helper(node.left, k - 1, true);\n helper(node.right, k - 1, true);\n return [true, 1];\n } else {\n\n let [l, d] = helper(node.left, k, false);\n\n //Found target node on left side, now get nodes of k distance from right side as well\n if(l === true) {\n if(k - d === 0) //for current node\n res.push(node.val);\n helper(node.right, k - d - 1, true);\n return [true, d + 1];\n }\n\n let [r, d1] = helper(node.right, k, false);\n\n if(r === true) {\n if(k - d1 === 0)\n res.push(node.val);\n helper(node.left, k - d1 - 1, true);\n return [true, d1 + 1];\n }\n\n return [false, 0];\n }\n\n }\n\n helper(root, k, false);\n\n return res;\n};", "solution_java": "class Solution {\n public List distanceK(TreeNode root, TreeNode target, int k) {\n HashMap map=new HashMap<>();\n get_parent(root,map);\n Queue q=new LinkedList<>();\n q.add(target);\n int distance=0;\n HashSet visited=new HashSet<>();\n visited.add(target);\n while(!q.isEmpty())\n {\n if(distance==k)\n break;\n distance++;\n int size=q.size();\n for(int i=0;i ans=new ArrayList<>();\n while(!q.isEmpty())\n ans.add(q.poll().val);\n return ans;\n \n }\n public void get_parent(TreeNode root,HashMap map)\n {\n Queue q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty())\n {\n int size=q.size();\n for(int i=0;i &parent)\n{\n\tqueue q;\n\tq.push(root);\n\n\twhile(q.empty()==false)\n\t{\n\t\tTreeNode *curr = q.front();\n\t\tq.pop();\n\n\t\tif(curr->left!=NULL)\n\t\t{\n\t\t\tparent[curr->left] = curr;\n\t\t\tq.push(curr->left);\n\t\t}\n\n\t\tif(curr->right!=NULL)\n\t\t{\n\t\t\tparent[curr->right] = curr;\n\t\t\tq.push(curr->right);\n\t\t}\n\t}\n}\n\nclass Solution {\npublic:\n\nvoid solve(TreeNode* target, unordered_map &parent,unordered_map &visited, vector &res, int k)\n{ \n if(k==0){\n res.push_back(target->val);\n return;\n }\n \n queueq;\n int distance = 0;\n \n q.push(target);\n visited[target] = 1;\n \n while(q.empty()==false)\n {\n int count = q.size();\n distance++;// increment distance value for current level of our level order traversal\n \n for(int i=0;ileft!=NULL && visited[curr->left]==false)\n {\n visited[curr->left] = true;\n q.push(curr->left);\n \n if(distance==k)// when we reach the node at distance = k, push it to res\n res.push_back(curr->left->val);\n }\n \n if(curr->right!=NULL && visited[curr->right]==false)\n {\n visited[curr->right] = true;\n q.push(curr->right);\n \n if(distance==k)// when we reach the node at distance = k, push it to res\n res.push_back(curr->right->val);\n }\n \n if(parent[curr] && visited[parent[curr]]==false)\n {\n visited[parent[curr]] = true;\n q.push(parent[curr]);\n \n if(distance==k)// when we reach the node at distance = k, push it to res\n res.push_back(parent[curr]->val);\n }\n }\n \n if(distance==k)// if in curr iteration all k distances nodes have been pushed, we break\n break;\n }\n}\n\nvector distanceK(TreeNode* root, TreeNode* target, int k)\n{\n unordered_map parent;\n makeParent(root,parent);\n \n unordered_map visited;\n vector ans;\n \n solve(target,parent,visited,ans,k);// begin from target Node\n return ans;\n}" }, { "title": "Merge Two Sorted Lists", "algo_input": "You are given the heads of two sorted linked lists list1 and list2.\n\nMerge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\n\nReturn the head of the merged linked list.\n\n \nExample 1:\n\nInput: list1 = [1,2,4], list2 = [1,3,4]\nOutput: [1,1,2,3,4,4]\n\n\nExample 2:\n\nInput: list1 = [], list2 = []\nOutput: []\n\n\nExample 3:\n\nInput: list1 = [], list2 = [0]\nOutput: [0]\n\n\n \nConstraints:\n\n\n\tThe number of nodes in both lists is in the range [0, 50].\n\t-100 <= Node.val <= 100\n\tBoth list1 and list2 are sorted in non-decreasing order.\n\n", "solution_py": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n cur = dummy = ListNode()\n while list1 and list2: \n if list1.val < list2.val:\n cur.next = list1\n list1, cur = list1.next, list1\n else:\n cur.next = list2\n list2, cur = list2.next, list2\n \n if list1 or list2:\n cur.next = list1 if list1 else list2\n \n return dummy.next", "solution_js": "/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} list1\n * @param {ListNode} list2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(list1, list2) {\n\n if(!list1) return list2\n if(!list2) return list1\n\n let mergedList = new ListNode(0);\n let ptr = mergedList;\n let curr1 = list1;\n let curr2 = list2;\n\n while(curr1 && curr2){\n\n let newNode = new ListNode();\n if(!curr2 || curr1.val < curr2.val){\n newNode.val = curr1.val;\n newNode.next = null;\n ptr.next = newNode\n curr1 =curr1.next;\n } else{\n newNode.val = curr2.val;\n newNode.next = null;\n ptr.next = newNode\n curr2 =curr2.next;\n }\n\n ptr = ptr.next\n }\n\n if(curr1 !== null){\n ptr.next = curr1;\n curr1 = curr1.next;\n }\n\n if(curr2 !== null){\n ptr.next = curr2;\n curr2 = curr2.next;\n }\n\n return mergedList.next\n};", "solution_java": "class Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2)\n {\n if(list1==null && list2==null)\n return null;\n if(list1 == null)\n return list2;\n if(list2 == null)\n return list1;\n\n ListNode newHead = new ListNode();\n ListNode newNode = newHead;\n\n while(list1!=null && list2!=null)\n {\n //ListNode newNode = new ListNode();\n if(list1.val <= list2.val)\n {\n newNode.next = list1;\n list1 = list1.next;\n }\n else if(list1.val >= list2.val)\n {\n newNode.next = list2;\n list2 = list2.next;\n }\n newNode = newNode.next;\n }\n if(list1!=null)\n newNode.next = list1;\n else if(list2!=null)\n newNode.next = list2;\n return newHead.next;\n }\n}", "solution_c": "class Solution {\npublic:\n ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n ListNode dummy(INT_MIN);\n ListNode *tail = &dummy;\n \n while (l1 && l2) {\n if (l1->val < l2->val) {\n tail->next = l1;\n l1 = l1->next;\n } else {\n tail->next = l2;\n l2 = l2->next;\n }\n tail = tail->next;\n }\n\n tail->next = l1 ? l1 : l2;\n return dummy.next;\n }\n};" }, { "title": "Find Eventual Safe States", "algo_input": "There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].\n\nA node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).\n\nReturn an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.\n\n \nExample 1:\n\nInput: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput: [2,4,5,6]\nExplanation: The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\n\nExample 2:\n\nInput: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput: [4]\nExplanation:\nOnly node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n\n\n \nConstraints:\n\n\n\tn == graph.length\n\t1 <= n <= 104\n\t0 <= graph[i].length <= n\n\t0 <= graph[i][j] <= n - 1\n\tgraph[i] is sorted in a strictly increasing order.\n\tThe graph may contain self-loops.\n\tThe number of edges in the graph will be in the range [1, 4 * 104].\n\n", "solution_py": "import collections\n\nclass Solution:\n def eventualSafeNodes(self, graph: list[list[int]]) -> list[int]:\n\n n = len(graph)\n ans = []\n \n for i in range(n):\n if not graph[i]:\n ans.append(i)\n \n def loop(key, loops):\n \n loops.append(key)\n for i in graph[key]:\n if i in loops:\n return False\n elif i in ans: \n continue\n else:\n r = loop(i, loops)\n if r == True: \n continue\n else: \n return False\n\n idx = loops.index(key)\n loops.pop(idx)\n return True\n \n for i in range(n):\n loops = []\n if i in ans:\n continue\n r = loop(i, loops)\n if r == True: ans.append(i)\n \n return sorted(ans)", "solution_js": "/**\n * @param {number[][]} graph\n * @return {number[]}\n */\nvar eventualSafeNodes = function(graph) {\n const ans = [];\n const map = new Map();\n for(let i=0; i eventualSafeNodes(int[][] graph) {\n int n=graph.length;\n List ans=new ArrayList<>();\n\n boolean visited[]=new boolean[n];\n boolean dfsVisited[]=new boolean[n];\n\n boolean nodeCycles[]=new boolean[n];\n\n for(int i=0;i eventualSafeNodes(vector>& graph) {\n int n=graph.size();\n vector vis(n, false), curr_vis(n, false), safe(n, true);\n\n for(int i=0; i ans;\n for(int i=0; i &vis, vector &curr_vis, vector &safe, vector>& graph){\n vis[i]=true, curr_vis[i]=true;\n\n for(auto j : graph[i]){\n if(!vis[j]){\n if(dfs(j, vis, curr_vis, safe, graph)==false)\n return safe[i] = false;\n }\n else if(curr_vis[j])\n return safe[i] = false;\n }\n\n curr_vis[i]=false;\n return safe[i];\n }\n};" }, { "title": "Minimum Time to Collect All Apples in a Tree", "algo_input": "Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.\n\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.\n\n \nExample 1:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput: 8 \nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n\n\nExample 2:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput: 6\nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n\n\nExample 3:\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput: 0\n\n\n \nConstraints:\n\n\n\t1 <= n <= 105\n\tedges.length == n - 1\n\tedges[i].length == 2\n\t0 <= ai < bi <= n - 1\n\tfromi < toi\n\thasApple.length == n\n\n", "solution_py": "class Solution:\n\n def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> 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 self.result = set()\n visited = set()\n def dfs(node, path):\n visited.add(node)\n if hasApple[node]:\n temp = path + '|' + str(node)\n temp = temp.split('|')[1:]\n # print(temp)\n for i in range(1, len(temp)):\n self.result.add((temp[i], temp[i-1]))\n for nei in graph_map[node]:\n if nei not in visited:\n dfs(nei, path + '|' + str(node))\n\n dfs(0, \"\")\n # print(self.result)\n return len(self.result) * 2", "solution_js": " var cnvrtAdjLst = (mat) => {//converts the list of edges to adjacency list\n let map = new Map();\n for(let i=0; i {\n visited.add(src);// add root to visited set, as we start exploring the subtree\n let lengthFromNow = 0;//total length of path visited by each child, 0 if no child has apple\n for(let i in adjList[src]){\n if(!visited.has(adjList[src][i])){\n lengthFromNow += dfsForApples(adjList[src][i],len+1);// add child path length to total length\n }\n\n }\n if(lengthFromNow>0){\n //if there is an apple present in the subtree\n return lengthFromNow + 2;\n }\n else if(hasApple[src]){\n //if there is no apple in subtree but apple is present on the root node\n return 2;\n }\n else{\n // if no apple is present in subtree\n return 0;\n }\n }\n visited.add(0);\n let res = dfsForApples(0,0);\n return res?res-2:0;//check if the root node itself has an apple or no apple is present\n};", "solution_java": "class Solution {\n public int minTime(int n, int[][] edges, List hasApple) {\n HashMap> graph = new HashMap<>(n);\n for(int edge[] : edges){\n int a = edge[0], b = edge[1];\n graph.putIfAbsent(a, new LinkedList<>());\n graph.putIfAbsent(b, new LinkedList<>());\n graph.get(a).add(b);\n graph.get(b).add(a);\n }\n \n boolean[] visited = new boolean[n];\n Arrays.fill(visited,false);\n \n int a = move(0,graph,hasApple,n,visited);\n \n return a==-1?0:a;\n }\n \n public int move(int i,HashMap> graph,List hasApple,int n,boolean[] visited){\n visited[i]=true;\n boolean cont = false;\n if(hasApple.get(i)){\n cont=true;\n }\n \n List list = graph.get(i);\n \n if(list==null){\n return cont?0:-1;\n }\n int j = 0;\n for(int k : list){\n if(!visited[k]){\n int a = move(k,graph,hasApple,n,visited);\n if(a!=-1){\n j+=2+a;\n }\n }\n }\n if(j==0 && cont) return 0;\n return j==0?-1:j;\n }\n}", "solution_c": "class DSU{\nprivate:\n vector parent,rank ;\npublic:\n DSU(int n){\n rank.resize(n,1) ;\n parent.resize(n) ;\n iota(begin(parent),end(parent),0) ;\n }\n\n int find_parent(int node){\n if(node == parent[node]) return node ;\n return parent[node] = find_parent(parent[node]) ;\n }\n void Union(int u , int v){\n int U = find_parent(u) , V = find_parent(v) ;\n if(U == V) return ;\n if(rank[U] < rank[V]) swap(U,V) ;\n rank[U] += rank[V] ;\n parent[V] = U ;\n }\n int getRank(int node){\n return rank[parent[node]] ;\n }\n\n};\n\nclass Solution {\npublic:\n vector dp ;\n vector hasApple ;\n vector adj[100001] ;\n vector visited ;\n\n void dfs(int src){\n visited[src] = 1 ;\n for(auto &nbr : adj[src]){\n if(!visited[nbr]){\n dfs(nbr) ;\n dp[src] = dp[src] or dp[nbr] ;\n }\n }\n }\n\n int minTime(int n, vector>& edges, vector& hasApple) {\n DSU dsu(n) ;\n dp = hasApple ; visited.resize(n,0) ; this->hasApple = hasApple ;\n\n for(auto &x : edges) adj[x[0]].push_back(x[1]) , adj[x[1]].push_back(x[0]) ;\n dfs(0) ;\n\n int start = -1 ;\n for(int i = 0 ; i < n ; ++i ){\n if(!dp[i]) continue ;\n if(start == -1){\n start = i ; continue ;\n }\n dsu.Union(start,i) ;\n }\n\n return (dsu.getRank(0) - 1) * 2 ;\n }\n};" }, { "title": "Count Number of Teams", "algo_input": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value.\n\nYou have to form a team of 3 soldiers amongst them under the following rules:\n\n\n\tChoose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).\n\tA team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).\n\n\nReturn the number of teams you can form given the conditions. (soldiers can be part of multiple teams).\n\n \nExample 1:\n\nInput: rating = [2,5,3,4,1]\nOutput: 3\nExplanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). \n\n\nExample 2:\n\nInput: rating = [2,1,3]\nOutput: 0\nExplanation: We can't form any team given the conditions.\n\n\nExample 3:\n\nInput: rating = [1,2,3,4]\nOutput: 4\n\n\n \nConstraints:\n\n\n\tn == rating.length\n\t3 <= n <= 1000\n\t1 <= rating[i] <= 105\n\tAll the integers in rating are unique.\n\n", "solution_py": "class Solution:\n def numTeams(self, ratings: List[int]) -> int:\n upper_dps = [0 for _ in range(len(ratings))]\n lower_dps = [0 for _ in range(len(ratings))]\n \n count = 0\n for i in range(len(ratings)):\n for j in range(i):\n if ratings[j] < ratings[i]:\n count += upper_dps[j]\n upper_dps[i] += 1\n else:\n count += lower_dps[j]\n lower_dps[i] += 1\n \n return count", "solution_js": "// counting bigger / smaller elements\n// if after rating[i] has X bigger elements,\n// and each element has Y bigger elements after them\n// hence total elements that has i < j < k and rating[i] < rating[j] < rating[k]\n// same for the number of smaller elements\n// so the key point here is to know how many elements\n// that smaller and bigger than the current number\nvar numTeams = function(rating) {\n // save total number of elements after i\n // that smaller than rating[i]\n let big = new Array(rating.length).fill(0)\n\n let n = rating.length;\n for (let i = 0; i < n - 1; i++) {\n for (let j = i + 1; j < n; j++) {\n if (rating[j] > rating[i]) big[i]++;\n }\n }\n\n let count = 0;\n for (let i = 0; i < n - 1; i++) {\n for (let j = i + 1; j < n; j++) {\n if (rating[j] > rating[i]) count += big[j]\n\n // because all elements are unique, so\n // we don't need to calculate the number of smaller elements\n // because if there are X bigger elements after rating[i]\n // then there are (n - i - 1 - X) smaller elements after rating[i]\n // or small = n - i - 1 - big\n else count += n - j - 1 - big[j];\n }\n }\n\n return count;\n}", "solution_java": "// Smaller * Larger Solution\n// sum of #smaller * #larger\n// Time complexity: O(N^2)\n// Space complexity: O(1)\nclass Solution {\n public int numTeams(int[] rating) {\n final int N = rating.length;\n int res = 0;\n for (int i = 1; i < N; i++) {\n res += smaller(rating, i, -1) * larger(rating, i, 1);\n res += larger(rating, i, -1) * smaller(rating, i, 1);\n }\n return res;\n }\n \n private int smaller(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] < t) count++;\n i += diff;\n }\n return count;\n }\n \n private int larger(int[] rating, int i, int diff) {\n int t = rating[i], count = 0;\n i += diff;\n while (i >= 0 && i < rating.length) {\n if (rating[i] > t) count++;\n i += diff;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int numTeams(vector& rating) {\n\n int i, j, n = rating.size(), ans = 0;\n vector grt(n, 0), les(n, 0);\n for(i=0;i rating[i])\n grt[i] += 1;\n else\n les[i] += 1;\n }\n }\n\n for(i=0;i rating[i])\n ans += grt[j];\n else\n ans += les[j];\n }\n }\n return ans;\n }\n};" }, { "title": "Remove One Element to Make the Array Strictly Increasing", "algo_input": "Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.\n\nThe array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).\n\n \nExample 1:\n\nInput: nums = [1,2,10,5,7]\nOutput: true\nExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.\n\n\nExample 2:\n\nInput: nums = [2,3,1,2]\nOutput: false\nExplanation:\n[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.\n\nExample 3:\n\nInput: nums = [1,1,1]\nOutput: false\nExplanation: The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.\n\n\n \nConstraints:\n\n\n\t2 <= nums.length <= 1000\n\t1 <= nums[i] <= 1000\n\n", "solution_py": "class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n indx = -1\n count = 0\n n = len(nums)\n \n # count the number of non-increasing elements\n for i in range(n-1):\n if nums[i] >= nums[i+1]:\n indx = i\n count += 1\n \n #the cases explained above\n if count==0:\n return True\n \n if count == 1:\n if indx == 0 or indx == n-2:\n return True\n if nums[indx-1] < nums[indx+1] or(indx+2 < n and nums[indx] < nums[indx+2]):\n return True\n \n return False", "solution_js": "var canBeIncreasing = function(nums) {\n for (let i = 1, used = false, prev = nums[0]; i < nums.length; i++) {\n if (nums[i] > prev) { prev = nums[i]; continue }\n if (used) return false;\n used = true;\n (i === 1 || nums[i] > nums[i - 2]) && (prev = nums[i]);\n }\n return true;\n};", "solution_java": "class Solution {\n public boolean canBeIncreasing(int[] nums) {\n int count=0;\n int p=0;\n for(int i=0;inums[i+1] || nums[i]==nums[i+1]) {\n count++;\n p=i;\n }\n }\n if(count>1) return false;\n else if(count==1){\n if(p==0 || p== nums.length-2) return true;\n if(nums[p+1]>nums[p-1] || nums[p+2]>nums[p]) return true;\n else return false;\n }\n return true;\n }\n}", "solution_c": "class Solution {\npublic:\n bool canBeIncreasing(vector& nums) {\nint count = 0;\n for (int i = 1; i < nums.size(); ++i) {\n if (nums[i] <= nums[i - 1]) {\n if (count == 1)\n return false;\n count++;\n if (i > 1 && nums[i] <= nums[i - 2] )\n nums[i] = nums[i - 1];\n }\n }\n return true;\n }\n};" }, { "title": "Count Number of Texts", "algo_input": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.\n\nIn order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.\n\n\n\tFor example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.\n\tNote that the digits '0' and '1' do not map to any letters, so Alice does not use them.\n\n\nHowever, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.\n\n\n\tFor example, when Alice sent the message \"bob\", Bob received the string \"2266622\".\n\n\nGiven a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.\n\nSince the answer may be very large, return it modulo 109 + 7.\n\n \nExample 1:\n\nInput: pressedKeys = \"22233\"\nOutput: 8\nExplanation:\nThe possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.\n\n\nExample 2:\n\nInput: pressedKeys = \"222222222222222222222222222222222222\"\nOutput: 82876089\nExplanation:\nThere are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n\n\n \nConstraints:\n\n\n\t1 <= pressedKeys.length <= 105\n\tpressedKeys only consists of digits from '2' - '9'.\n\n", "solution_py": "class Solution(object):\n def countTexts(self, pressedKeys):\n \"\"\"\n :type pressedKeys: str\n :rtype: int\n \"\"\"\n dp = [1] + [0]*len(pressedKeys)\n mod = 10**9 + 7\n for i, n in enumerate(pressedKeys):\n dp[i+1] = dp[i]\n # check if is continous\n if i >= 1 and pressedKeys[i-1] == n:\n dp[i+1] += dp[i-1]\n dp[i+1] %= mod\n if i >= 2 and pressedKeys[i-2] == n:\n dp[i+1] += dp[i-2]\n dp[i+1] %= mod\n # Special case for '7' and '9' that can have 4 characters combination\n if i >= 3 and pressedKeys[i-3] == n and (n == \"7\" or n == \"9\"):\n dp[i+1] += dp[i-3]\n dp[i+1] %= mod\n return dp[-1]", "solution_js": "var countTexts = function(pressedKeys) {\n const MOD = 1e9 + 7;\n const n = pressedKeys.length;\n const dp = new Array(n + 1).fill(0);\n\n dp[0] = 1;\n\n let lastChar = \"\";\n let repeatCount = 0;\n\n for (let i = 1; i <= n; ++i) {\n const currChar = pressedKeys[i - 1];\n\n if (currChar != lastChar) repeatCount = 0;\n\n lastChar = currChar;\n repeatCount += 1;\n\n dp[i] = (dp[i] + dp[i - 1]) % MOD;\n\n if (i >= 2 && repeatCount >= 2) dp[i] = (dp[i] + dp[i - 2]) % MOD;\n if (i >= 3 && repeatCount >= 3) dp[i] = (dp[i] + dp[i - 3]) % MOD;\n if ((currChar == \"7\" || currChar == \"9\") && i >= 4 && repeatCount >= 4) dp[i] = (dp[i] + dp[i - 4]) % MOD;\n }\n\n return dp[n];\n};", "solution_java": "class Solution {\n int mod = (1000000007);\n\n public int countTexts(String pressedKeys) {\n int[] key = new int[] { 0, 0, 3, 3, 3, 3, 3, 4, 3, 4 };\n int n = pressedKeys.length();\n return solve(0,pressedKeys,key);\n }\n\n public int solve(int ind, String s, int[] key) {\n if (ind == s.length()) {\n return 1;\n }\n int count = 0;\n int num = s.charAt(ind) - '0';\n int rep = key[num];\n for (int i = 0; i < rep && ind + i < s.length() && s.charAt(ind) == s.charAt(ind + i); i++) {\n count += solve(ind + 1 + i, s, key);\n count %= mod;\n }\n return count;\n }\n}", "solution_c": "class Solution {\npublic:\n int mod = 1e9+7;\n int solve(string &str, int idx) {\n if(idx == str.length()) return 1;\n int maxKeyPress = (str[idx] == '7' || str[idx] == '9') ? 4 : 3;\n long long currIndex = idx, pressFrequency = 1, ans = 0;\n while(pressFrequency <= maxKeyPress && str[currIndex] == str[idx]) {\n ++currIndex;\n ++pressFrequency;\n ans += solve(str, currIndex) % mod;\n }\n return ans%mod;\n }\n int countTexts(string pressedKeys) {\n return solve(pressedKeys, 0) % mod;\n }\n};" }, { "title": "Minimum Number of Steps to Make Two Strings Anagram", "algo_input": "You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.\n\nReturn the minimum number of steps to make t an anagram of s.\n\nAn Anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n\n \nExample 1:\n\nInput: s = \"bab\", t = \"aba\"\nOutput: 1\nExplanation: Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.\n\n\nExample 2:\n\nInput: s = \"leetcode\", t = \"practice\"\nOutput: 5\nExplanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.\n\n\nExample 3:\n\nInput: s = \"anagram\", t = \"mangaar\"\nOutput: 0\nExplanation: \"anagram\" and \"mangaar\" are anagrams. \n\n\n \nConstraints:\n\n\n\t1 <= s.length <= 5 * 104\n\ts.length == t.length\n\ts and t consist of lowercase English letters only.\n\n", "solution_py": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n for ch in s:\n\t\t # Find and replace only one occurence of this character in t\n t = t.replace(ch, '', 1)\n \n return len(t)", "solution_js": "var minSteps = function(s, t) {\n\n let hash1 = hash(s);\n let hash2 = hash(t);\n let steps = 0;\n\n for(let key of Object.keys(hash1)) {\n if( hash2[key]) {\n hash1[key] = hash1[key] - hash2[key];\n }\n if( hash1[key] > 0 ) {\n steps += hash1[key];\n }\n }\n\n return steps;\n};\n\nfunction hash(str) {\n let hash = {};\n for(let i=0; i vec1(26, 0), vec2(26, 0);\n for(int i = 0; i < length; ++i){\n vec1[s[i] - 'a']++;\n vec2[t[i] - 'a']++;\n }\n for(int i = 0; i < 26; ++i){\n if(vec1[i] > vec2[i])\n count += vec1[i] - vec2[i];\n }\n return count;\n }\n};" } ]