Team Ai
Datasetpublic

khaimaitien/leetcode_problem_solution

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

sourceHugging Faceupdated 3y agoView on Hugging Face
2likes65downloads
train.json10954 linesDownload Raw Back to root
1[2    {3        "title": "Stone Game V",4        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= stoneValue.length &lt;= 500\n\t1 &lt;= stoneValue[i] &lt;= 106\n\n",5        "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]",6        "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};",7        "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<sum-temp){\n                ans=Math.max(ans,temp+fnc(a,i,index,temp));\n            }\n            else\n                ans=Math.max(ans,Math.max(sum-temp+fnc(a,index+1,j,sum-temp),temp+fnc(a,i,index,temp)));\n        }\n        dp[i][j]=ans;\n        return dp[i][j];\n    }\n    public int stoneGameV(int[] stoneValue) {\n        int n=stoneValue.length;\n        int sum=0;\n        for(int ele:stoneValue)\n            sum+=ele;\n        dp= new int[n][n];\n        return fnc(stoneValue,0,n-1,sum);\n\n    }\n}",8        "solution_c": "class Solution {\npublic:\n    int dp[501][501];\n\n    int f(vector<int> &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<r) ans=max(ans,l+f(v,i,k));\n            else if(r<l) ans=max(ans,r+f(v,k+1,j));\n            else ans=max(ans,max(l+f(v,i,k),r+f(v,k+1,j)));\n        }\n        return dp[i][j]=ans;\n    }\n\n    int stoneGameV(vector<int>& stoneValue) {\n\n        memset(dp,-1,sizeof(dp));\n        return f(stoneValue,0,stoneValue.size()-1);\n\n    }\n};"9    },10    {11        "title": "Power of Two",12        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t-231 &lt;= n &lt;= 231 - 1\n\n\n&nbsp;\nFollow up: Could you solve it without loops/recursion?",13        "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",14        "solution_js": "var isPowerOfTwo = function(n) {\n    let i=1;\n    while(i<n){\n        i*=2\n    }return i===n\n};",15        "solution_java": "class Solution {\n    public boolean isPowerOfTwo(int n) {\n        return power2(0,n);\n\n    }\n    public boolean power2(int index,int n){\n        if(Math.pow(2,index)==n)\n            return true;\n        if(Math.pow(2,index)>n)\n            return false;\n        return power2(index+1,n);\n    }\n}",16        "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};"17    },18    {19        "title": "N-Queens",20        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 9\n\n",21        "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                ",22        "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};",23        "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<List<String>> ans = new LinkedList<>();\n    int n;\n    public List<List<String>> 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<String> 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}",24        "solution_c": "class Solution {\n    bool isSafe(vector<string> 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<n && col>=0){\n            if(board[row][col]=='Q') return false;\n            row++;\n            col--;\n        }\n        \n        return true;\n    }\n    \n    void solve(vector<vector<string>> &ans, vector<string> &board, int n, int col){\n        if(col==n){\n            ans.push_back(board);\n            return;\n        }\n        \n        for(int row=0;row<n;row++){\n            if(isSafe(board,row,col,n)){\n                board[row][col]='Q';\n                solve(ans,board,n,col+1);\n                board[row][col]='.';\n            }\n        }\n    }\n    \n    \npublic:\n    vector<vector<string>> solveNQueens(int n) {\n        vector<vector<string>> ans;\n        vector<string> board;\n        string s(n,'.');\n        for(int i=0;i<n;i++) board.push_back(s);\n        \n        solve(ans,board,n,0);\n        \n        return ans;\n    }\n};"25    },26    {27        "title": "Check if Array Is Sorted and Rotated",28        "algo_input": "Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.\n\nThere may be duplicates in the original array.\n\nNote: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.\n\n&nbsp;\nExample 1:\n\nInput: nums = [3,4,5,1,2]\nOutput: true\nExplanation: [1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].\n\n\nExample 2:\n\nInput: nums = [2,1,3,4]\nOutput: false\nExplanation: There is no sorted array once rotated that can make nums.\n\n\nExample 3:\n\nInput: nums = [1,2,3]\nOutput: true\nExplanation: [1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 100\n\n",29        "solution_py": "class Solution:\n    def check(self, num: List[int]) -> 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",30        "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};",31        "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<length; i++) {\n            if (nums[i] > nums[(i + 1) % length])\n                irregularities += 1;\n        }\n        return irregularities > 1 ? false : true;\n    }\n}",32        "solution_c": "class Solution {\npublic:\n    bool check(vector<int>& nums) {\n        int count=0;\n        for(int i=0;i<nums.size();i++){\n            if(nums[i]>nums[(i+1)%nums.size()])\n                count++;\n        }\n        return (count<=1);\n    }\n};"33    },34    {35        "title": "Special Positions in a Binary Matrix",36        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= m, n &lt;= 100\n\tmat[i][j] is either 0 or 1.\n\n",37        "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",38        "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};",39        "solution_java": "class Solution {\n    public int numSpecial(int[][] mat) {\n      int count=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]==1){\n                    int flag=0;\n                    for(int k=0;k<mat.length;k++){\n                        if(mat[k][j]!=0 && k!=i){\n                            flag=1;break;\n                        }\n                    }\n                    if(flag==1) continue;\n                    for(int k=0;k<mat[0].length;k++){\n                        if(mat[i][k]!=0 && k!=j){\n                            flag=1;\n                            break;\n                        }\n                    }\n                    if(flag==0) count++;\n                }\n            }\n        }\n        return count;\n    }\n}",40        "solution_c": "class Solution {\npublic:\n    int numSpecial(vector<vector<int>>& mat) {\n        vector<vector<int>>v;\n        map<int,vector<int>>m;\n\n        for(int i=0;i<mat.size();i++){\n            vector<int>temp = mat[i];\n\n            for(int j=0;j<temp.size();j++){\n                m[j].push_back(temp[j]);\n            }\n        }\n        for(auto i:m){\n            v.push_back(i.second);\n        }\n        int counter = 0;\n        for(int i=0;i<mat.size();i++){\n            int onecount = 0;\n            int column = 0;\n            for(int j=0;j<mat[i].size();j++){\n                if(mat[i][j]==1){\n                    column = j;\n                    onecount++;\n                }\n            }\n            if(onecount==1){\n                int countone = 0;\n                vector<int>temp = 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};"41    },42    {43        "title": "Design Circular Deque",44        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= 1000\n\t0 &lt;= value &lt;= 1000\n\tAt most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.\n\n",45        "solution_py": "class MyCircularDeque {\npublic:\n    \n    deque<int> 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};",46        "solution_js": "class MyCircularDeque {\npublic:\n    \n    deque<int> 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};",47        "solution_java": "class MyCircularDeque {\npublic:\n    \n    deque<int> 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};",48        "solution_c": "class MyCircularDeque {\npublic:\n\n    deque<int> 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};"49    },50    {51        "title": "Sum of All Subset XOR Totals",52        "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.&nbsp;\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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 12\n\t1 &lt;= nums[i] &lt;= 20\n\n",53        "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)",54        "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.length; i++){\n            arr.push(nums[i]);\n            backtrack(i+1, arr);\n            arr.pop();\n       }\n    }\n};",55        "solution_java": "class Solution {\n    int sum=0;\n    public int subsetXORSum(int[] nums) {\n        sum=0;\n        return getAns(nums,0,0);\n    }\n    \n    int getAns(int[] arr,int i,int cur){\n        if(i==arr.length){\n            return cur;\n        }\n        return getAns(arr,i+1,cur^arr[i]) + getAns(arr,i+1,cur);\n    }\n}",56        "solution_c": "class Solution {\npublic:\n\n    int subsetXORSum(vector<int>& nums)\n    {\n        int ans=0;\n        for(int i=0; i<32; i++)\n        {\n            int mask=1<<i;\n            int count=0;\n            for(int j=0; j<nums.size(); j++)\n            {\n                if(nums[j]&mask) count++;\n            }\n            if(count)\n            {\n                ans+=mask*(1<<(count-1))*(1<<(nums.size()-count));\n            }\n        }\n        return ans;\n    }\n};"57    },58    {59        "title": "Maximum Performance of a Team",60        "algo_input": "You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.\n\nChoose at most k different engineers out of the n engineers to form a team with the maximum performance.\n\nThe performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.\n\nReturn the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput: 60\nExplanation: \nWe have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n\n\nExample 2:\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput: 68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n\n\nExample 3:\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput: 72\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= n &lt;= 105\n\tspeed.length == n\n\tefficiency.length == n\n\t1 &lt;= speed[i] &lt;= 105\n\t1 &lt;= efficiency[i] &lt;= 108\n\n",61        "solution_py": "class Solution:\n    def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> 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)<k-1:\n                heappush(h,l[i][1])\n                mx_sum+=l[i][1]\n            elif k!=1:\n                x=0\n                if h:\n                    x = heappop(h)\n                heappush(h,max(x,l[i][1]))\n                mx_sum = mx_sum - x + max(x,l[i][1])\n        return res%mod\n            ",62        "solution_js": "var maxPerformance = function(n, speed, efficiency, k) {\n    let ord = Array.from({length: n}, (_,i) => 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};",63        "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<Engineer> engineers = new ArrayList<>();\n        for(int i=0;i<n;i++) {\n            engineers.add(new Engineer(speed[i], efficiency[i]));\n        }\n        engineers.sort((a, b) -> b.efficiency - a.efficiency);\n        PriorityQueue<Engineer> 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}",64        "solution_c": "class Solution {\npublic:\n    \n    int maxPerformance(int n, vector<int>& speed, vector<int>& efficiency, int k) {\n        priority_queue<int, vector<int>, greater<int>> pq;\n        long long sum = 0, ans = 0;\n        const int m = 1e9 + 7;\n        vector<vector<int>> pairs(n, vector<int> (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}; "65    },66    {67        "title": "Minimum Number of Taps to Open to Water a Garden",68        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\tranges.length == n + 1\n\t0 &lt;= ranges[i] &lt;= 100\n\n",69        "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",70        "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};",71        "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;i<ranges.length&&end<n;i++){\n            int j = idx[i];\n            if (j-ranges[j]>cur){\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<n?-1:ans;\n    }\n}",72        "solution_c": "class Solution {\npublic:\n    int minTaps(int n, vector<int>& ranges) {\n        vector<pair<int,int>> v;\n        for(int i=0;i<ranges.size();i++){\n            // making ranges\n            v.push_back({i-ranges[i],i+ranges[i]});\n        }\n        // sorting the intervals\n        sort(v.begin(),v.end());\n        \n        // to keep track from where we need to cover\n        int uncovered = 0;\n        int idx = 0;\n        // number of ranges used\n        int cnt = 0;\n        \n        // to check if its possible\n        bool ok = true;\n        \n        // as long as we have not covered the garden\n        while(uncovered<n){\n            // we will try to cover the uncovered such that new uncovered is maximum possible\n            int new_uncovered = uncovered;\n            while(idx<n+1 && v[idx].first<=uncovered){\n                new_uncovered = max(new_uncovered,v[idx].second);\n                idx++;\n            }\n            // we have used one range\n            cnt++;\n            \n            // it means we were not able to cover with ranges so not possible\n            if(new_uncovered == uncovered){\n                ok = false;\n                break;\n            }\n            // updating uncovered for next iteration\n            uncovered = new_uncovered;\n        }\n        if(ok) return cnt;\n        return -1;\n    }\n};"73    },74    {75        "title": "Next Greater Element III",76        "algo_input": "Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.\n\nNote that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.\n\n&nbsp;\nExample 1:\nInput: n = 12\nOutput: 21\nExample 2:\nInput: n = 21\nOutput: -1\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 231 - 1\n\n",77        "solution_py": "class Solution:\n    def nextGreaterElement(self, n):\n        digits = list(str(n))\n        i = len(digits) - 1\n        while i-1 >= 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",78        "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};",79        "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}",80        "solution_c": "class Solution {\npublic:\n    int nextGreaterElement(int n) {\n       vector<int>vec;\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};"81    },82    {83        "title": "The Time When the Network Becomes Idle",84        "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&nbsp;\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 &lt; 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&nbsp;\nConstraints:\n\n\n\tn == patience.length\n\t2 &lt;= n &lt;= 105\n\tpatience[0] == 0\n\t1 &lt;= patience[i] &lt;= 105 for 1 &lt;= i &lt; n\n\t1 &lt;= edges.length &lt;= min(105, n * (n - 1) / 2)\n\tedges[i].length == 2\n\t0 &lt;= ui, vi &lt; n\n\tui != vi\n\tThere are no duplicate edges.\n\tEach server can directly or indirectly reach another server.\n\n",85        "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",86        "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<edges.length;i++){\n        if(edgesMap[edges[i][0]]===undefined){\n            edgesMap[edges[i][0]] = [];\n        }\n        edgesMap[edges[i][0]].push(edges[i][1]);\n        if(edgesMap[edges[i][1]]===undefined){\n            edgesMap[edges[i][1]] = [];\n        }\n        edgesMap[edges[i][1]].push(edges[i][0]);\n    }\n    \n    let queue=[],node,neighbour;\n    minDistanceFromMasterArr[0]=0;//Distance of source to source is 0 \n    queue.push(0);\n    while(queue[0]!==undefined){\n        node = queue.shift();\n        for(let i=0;i<edgesMap[node].length;i++){\n            neighbour = edgesMap[node][i];   \n            if(minDistanceFromMasterArr[neighbour]===undefined){\n                minDistanceFromMasterArr[neighbour] = minDistanceFromMasterArr[node] + 1;\n                queue.push(neighbour);\n            }\n        }\n    }\n    for(let i=1;i<patience.length;i++){\n        let responseWillBeReceivedAt = minDistanceFromMasterArr[i]*2;\n        let lastMessageSentAt;\n        if(patience[i]<responseWillBeReceivedAt){\n            lastMessageSentAt = Math.floor((responseWillBeReceivedAt-1)/patience[i])*patience[i];\n        }else{\n            lastMessageSentAt=0;\n        }\n        let lastMessageWillTravelTill = lastMessageSentAt + responseWillBeReceivedAt;\n        let firstIdleSecond = lastMessageWillTravelTill+1;\n        ans = Math.max(ans,firstIdleSecond);\n    }\n    \n    return ans;\n};",87        "solution_java": "class Solution {\n    public int networkBecomesIdle(int[][] edges, int[] patience) {\n        int n = patience.length;\n\n        // creating adjacency list\n        ArrayList<ArrayList<Integer>> 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<ArrayList<Integer>> 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<int[]> 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}",88        "solution_c": "class Solution {\npublic:\n    int networkBecomesIdle(vector<vector<int>>& edges, vector<int>& patience) {\n        int n = patience.size();\n        vector <vector <int>> graph(n);\n        vector <int> 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 <int> 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<n; i++) {\n            int extraPayload = (time[i]*2 - 1)/patience[i]; \n\t\t\t// extra number of payload before the first message arrive back to data server.\n\t\t\t// since a data server can only send a message before first message arrives back.\"\n\t\t\t// and first message arrives at time[i]*2. so \"(time[i]*2-1)\"\n\t\t\t\n            int lastOut = extraPayload * patience[i]; // find the last time when a data server sends a message\n            int lastIn = lastOut + time[i]*2; // this is the result for current data server\n\t\t\t\n            res = max(res, lastIn);\n        }\n\t\t\n\t\t// at \"res\" time the last message has arrived at one of the data servers.\n\t\t// so at res+1 no message will be passing between servers.\n\t\t\n        return res+1;\n    }\n};"89    },90    {91        "title": "Maximal Network Rank",92        "algo_input": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.\n\nThe network rank of two different cities is defined as the total number of&nbsp;directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.\n\nThe maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.\n\nGiven the integer n and the array roads, return the maximal network rank of the entire infrastructure.\n\n&nbsp;\nExample 1:\n\n\n\nInput: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput: 4\nExplanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.\n\n\nExample 2:\n\n\n\nInput: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput: 5\nExplanation: There are 5 roads that are connected to cities 1 or 2.\n\n\nExample 3:\n\nInput: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput: 5\nExplanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 100\n\t0 &lt;= roads.length &lt;= n * (n - 1) / 2\n\troads[i].length == 2\n\t0 &lt;= ai, bi&nbsp;&lt;= n-1\n\tai&nbsp;!=&nbsp;bi\n\tEach&nbsp;pair of cities has at most one road connecting them.\n\n",93        "solution_py": "class Solution:\n    def maximalNetworkRank(self, n: int, roads) -> 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",94        "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<n;i++){\n        if(!map.has(i)) continue\n        let uAdj = map.get(i)\n        let uCount = uAdj.size;\n        for(let j=i+1;j<n;j++){\n            if(!map.has(j)) continue\n            let vAdj = map.get(j)\n            let vCount = vAdj.size\n            if(vAdj.has(i)) vCount--\n            res = Math.max(uCount+vCount, res)\n        }\n    }\n    return res\n};",95        "solution_java": "class Solution {\n    public int maximalNetworkRank(int n, int[][] roads) {\n        \n        //number of road connected to city\n        int[] numRoadsConnectedCity = new int[100 + 1];\n        \n        //road exist between two two cities\n        boolean[][] raadExist = new boolean[n][n];\n        \n        for(int[] cities : roads){\n            \n            //increment the count of numbers of connected city\n            numRoadsConnectedCity[cities[0]]++;\n            numRoadsConnectedCity[cities[1]]++;\n            \n            //mark road exist, between two cities\n            raadExist[cities[0]][cities[1]] = true;\n            raadExist[cities[1]][cities[0]] = true;\n        }\n        \n        \n        \n        int maxRank = 0;\n        for(int city1 = 0; city1 < n - 1; city1++){\n            for(int city2 = city1 + 1; city2 < n; city2++){\n                \n                //count total number of road connected to both city\n                int rank = numRoadsConnectedCity[city1] + numRoadsConnectedCity[city2];\n                \n                //just decrement the rank, if both city connected\n                if(raadExist[city1][city2]) rank--;\n                \n                maxRank = Math.max(maxRank, rank);\n            }\n        }\n            \n        \n        return maxRank;\n    }\n}",96        "solution_c": "class Solution {\npublic:\n    int maximalNetworkRank(int n, vector<vector<int>>& roads) {\n        vector<vector<int>>graph(n,vector<int>(n,0));\n        vector<int>degree(n,0);\n        for(int i=0;i<roads.size();i++){\n            int u=roads[i][0];\n            int v=roads[i][1];\n            degree[u]++;\n            degree[v]++;\n            graph[u][v]=1;\n            graph[v][u]=1;\n        }\n        int ans=0;\n        for(int i=0;i<graph.size();i++){\n            for(int j=0;j<graph.size();j++){\n                if(j!=i){\n                    int rank=degree[i]+degree[j]-graph[i][j];\n                    ans=max(ans,rank);\n                }\n            }\n        }\n        return ans;\n    }\n};"97    },98    {99        "title": "Pow(x, n)",100        "algo_input": "Implement pow(x, n), which calculates x raised to the power n (i.e., xn).\n\n&nbsp;\nExample 1:\n\nInput: x = 2.00000, n = 10\nOutput: 1024.00000\n\n\nExample 2:\n\nInput: x = 2.10000, n = 3\nOutput: 9.26100\n\n\nExample 3:\n\nInput: x = 2.00000, n = -2\nOutput: 0.25000\nExplanation: 2-2 = 1/22 = 1/4 = 0.25\n\n\n&nbsp;\nConstraints:\n\n\n\t-100.0 &lt; x &lt; 100.0\n\t-231 &lt;= n &lt;= 231-1\n\t-104 &lt;= xn &lt;= 104\n\n",101        "solution_py": "class Solution:\n    def myPow(self, x: float, n: int) -> 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)",102        "solution_js": "var myPow = function(x, n) {\n    return x**n;\n};",103        "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}",104        "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};"105    },106    {107        "title": "Game of Life",108        "algo_input": "According to&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m, n &lt;= 25\n\tboard[i][j] is 0 or 1.\n\n\n&nbsp;\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",109        "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)<c:\n\t\t\t\t\t\tif board[i+di][j+dj] == 0 or board[i+di][j+dj] == -1 :\n\t\t\t\t\t\t\tdeadcnt+=1\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tlivecnt+=1        \n\t\t\t\tif board[i][j] == 0:\n\t\t\t\t\tif livecnt == 3:\n\t\t\t\t\t\tboard[i][j] = -1\n\t\t\t\telse:\n\t\t\t\t\tif livecnt == 2 or livecnt==3:\n\t\t\t\t\t\tboard[i][j] = 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tboard[i][j] = -2\n\t\tfor i in range(r):\n\t\t\tfor j in range(c):\n\t\t\t\tif board[i][j] == -1:\n\t\t\t\t\tboard[i][j] = 1\n\t\t\t\telif board[i][j] == -2:\n\t\t\t\t\tboard[i][j] = 0",110        "solution_js": "/**\n * @param {number[][]} board\n * @return {void} Do not return anything, modify board in-place instead.\n */\nvar gameOfLife = function(board) {\n    const m = board.length, n = board[0].length;\n    let copy = JSON.parse(JSON.stringify(board));\n\n    const getNeighbor = (row, col) => {\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};",111        "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}",112        "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<vector<int>>& board) {\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                encode(board, i, j);\n            }\n        }\n        for (int i=0; i<m; ++i) {\n            for (int j=0; j<n; ++j) {\n                board[i][j] >>= 1;\n            }\n        }\n        \n    }\n    void encode(vector<vector<int>>& 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};"113    },114    {115        "title": "Get Maximum in Generated Array",116        "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 &lt;= 2 * i &lt;= n\n\tnums[2 * i + 1] = nums[i] + nums[i + 1] when 2 &lt;= 2 * i + 1 &lt;= n\n\n\nReturn the maximum integer in the array numsโ€‹โ€‹โ€‹.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 100\n\n",117        "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])",118        "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};",119        "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}",120        "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};"121    },122    {123        "title": "Cells with Odd Values in a Matrix",124        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 50\n\t1 &lt;= indices.length &lt;= 100\n\t0 &lt;= ri &lt; m\n\t0 &lt;= ci &lt; n\n\n\n&nbsp;\nFollow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?\n",125        "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",126        "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};",127        "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}",128        "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<vector<int>>& indices) {\n        vector<bool> 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<n;i++){\n            if(rows[i]) r++;\n        }\n        \n        for(int i(0);i<m;i++){\n            if(cols[i]) c++;\n        }\n        return r*(m-c) + c*(n-r); // (or) return (r*m + c*n - 2*r*c);\n    }\n};"129    },130    {131        "title": "Largest Sum of Averages",132        "algo_input": "You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.\n\nNote that the partition must use every integer in nums, and that the score is not necessarily an integer.\n\nReturn the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: nums = [9,1,2,3,9], k = 3\nOutput: 20.00000\nExplanation: \nThe best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n\n\nExample 2:\n\nInput: nums = [1,2,3,4,5,6,7], k = 4\nOutput: 20.50000\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t1 &lt;= nums[i] &lt;= 104\n\t1 &lt;= k &lt;= nums.length\n\n",133        "solution_py": "class Solution:\n    def largestSumOfAverages(self, A, k):\n        n = len(A)\n        dp = [0] * n\n        sum = 0\n        for i in range(n-1,-1,-1):\n            sum += A[i]\n            dp[i] = sum / (n-i)\n        for l in range(1,k):\n            for i in range(n-l):\n                sum = 0\n                for j in range(i,n-l):\n                    sum += A[j]\n                    dp[i] = max(dp[i],dp[j+1] + sum / (j-i+1))\n        return dp[0]",134        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar largestSumOfAverages = function(nums, k) {\n    // set length\n    const len = nums.length;\n    // set sum by len fill\n    const sum = new Array(len).fill(0);\n    // set nums first to first of sum\n    sum[0] = nums[0];\n\n    // set every item of sum to the sum of the previous and the corresponding item of nums\n    for (let i = 1; i < len; i++) {\n        sum[i] = sum[i - 1] + nums[i];\n    }\n\n    // set dynamic programming\n    const dp = new Array(k + 1).fill(\"\").map(() => 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};",135        "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(c<k1&&sum>0)\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}",136        "solution_c": "class Solution {\npublic:\n    double solve(vector<int>&nums, int index, int k, vector<vector<double>>&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<int>& nums, int k) {\n        int n = nums.size();\n        vector<vector<double>>dp(n, vector<double>(k+1, -1));\n        return solve(nums, n-1, k, dp);\n    }\n};"137    },138    {139        "title": "Predict the Winner",140        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 20\n\t0 &lt;= nums[i] &lt;= 107\n\n",141        "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",142        "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};",143        "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}",144        "solution_c": "class Solution {\npublic:\n    bool PredictTheWinner(vector<int>& nums) {\n        vector<vector<vector<int>>> dp(nums.size(),vector<vector<int>>(nums.size(),vector<int>(3,INT_MAX)));\n        int t=fun(dp,nums,0,nums.size()-1,1);\n        return t>=0;\n    }\n    int fun(vector<vector<vector<int>>>& dp,vector<int>& 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};"145    },146    {147        "title": "Maximum Element After Decreasing and Rearranging",148        "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]) &lt;= 1 for each i where 1 &lt;= i &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 105\n\t1 &lt;= arr[i] &lt;= 109\n\n",149        "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",150        "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};",151        "solution_java": "class Solution {\n    public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n      Arrays.sort(arr);\n      arr[0] = 1;\n      for(int i = 1;i<arr.length;i++){\n         if(Math.abs(arr[i] - arr[i-1]) > 1)\n            arr[i] = arr[i-1] + 1;    \n      }\n      return arr[arr.length-1];\n    }\n}",152        "solution_c": "class Solution {\npublic:\n    int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n        sort(arr.begin(),arr.end());\n        int n=arr.size();\n        arr[0]=1;\n        for(int i=1;i<n;i++)\n        {\n            if(arr[i]-arr[i-1]>1)\n            {\n                arr[i]=arr[i-1]+1;\n            }\n        }\n        return arr[n-1];\n    }\n};"153    },154    {155        "title": "Permutations",156        "algo_input": "Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 6\n\t-10 &lt;= nums[i] &lt;= 10\n\tAll the integers of nums are unique.\n\n",157        "solution_py": "class Solution:\n    def permute(self, nums: List[int]) -> List[List[int]]:\n        return list(permutations(nums))",158        "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};",159        "solution_java": "class Solution {\n    List<List<Integer>> res = new LinkedList<>();\n\n    public List<List<Integer>> permute(int[] nums) {\n        ArrayList<Integer> 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<Integer> 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}",160        "solution_c": "class Solution {\npublic:\n    void per(int ind, int n, vector<int>&nums, vector<vector<int>> &ans)\n    {\n        if(ind==n)\n        {\n            ans.push_back(nums);\n            return;\n        }\n        for(int i=ind;i<n;i++)\n        {\n            swap(nums[ind],nums[i]);\n            per(ind+1,n,nums,ans);\n            swap(nums[ind],nums[i]);\n        }\n    }\n    vector<vector<int>> permute(vector<int>& nums) {\n        vector<vector<int>> ans;\n        int n=nums.size();\n        per(0,n,nums,ans);\n        return ans;\n    }\n};"161    },162    {163        "title": "H-Index II",164        "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&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == citations.length\n\t1 &lt;= n &lt;= 105\n\t0 &lt;= citations[i] &lt;= 1000\n\tcitations is sorted in ascending order.\n\n",165        "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",166        "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}",167        "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            if(citations[i]>=n-i)\n            {\n                return n-i;\n            }\n        }\n        return res;\n    }\n}",168        "solution_c": "class Solution {\npublic:\n    int hIndex(vector<int>& 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};"169    },170    {171        "title": "Clone Graph",172        "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&lt;Node&gt; neighbors;\n}\n\n\n&nbsp;\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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the graph is in the range [0, 100].\n\t1 &lt;= Node.val &lt;= 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",173        "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",174        "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};",175        "solution_java": "/*\n// Definition for a Node.\nclass Node {\n    public int val;\n    public List<Node> neighbors;\n    public Node() {\n        val = 0;\n        neighbors = new ArrayList<Node>();\n    }\n    public Node(int _val) {\n        val = _val;\n        neighbors = new ArrayList<Node>();\n    }\n    public Node(int _val, ArrayList<Node> _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}",176        "solution_c": "                                          'IF YOU LIKE IT THEN PLS UpVote๐Ÿ˜Ž๐Ÿ˜Ž๐Ÿ˜Ž'\nclass Solution {\n    public:\n    Node* dfs(Node* cur,unordered_map<Node*,Node*>& mp)\n    {\n        vector<Node*> 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<Node*,Node*> 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};"177    },178    {179        "title": "Find K Closest Elements",180        "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| &lt; |b - x|, or\n\t|a - x| == |b - x| and a &lt; b\n\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= arr.length\n\t1 &lt;= arr.length &lt;= 104\n\tarr is sorted in ascending order.\n\t-104 &lt;= arr[i], x &lt;= 104\n\n",181        "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            ",182        "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};",183        "solution_java": "class Solution {\npublic List<Integer> findClosestElements(int[] arr, int k, int x) {\n    List<Integer> 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}",184        "solution_c": "class Solution {\npublic:\n    static bool cmp(pair<int,int>&p1,pair<int,int>&p2)\n    {\n        if(p1.first==p2.first)  //both having equal abs diff\n        {\n            return p1.second<p2.second;\n        }\n        return p1.first<p2.first;\n    }\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        \n        vector<pair<int,int>>v;    //abs diff , ele\n        \n        for(int i=0;i<arr.size();i++)\n        {\n            v.push_back(make_pair(abs(arr[i]-x),arr[i]));\n        }\n        \n        sort(v.begin(),v.end(),cmp);\n        vector<int>ans;\n        for(int i=0;i<k;i++)\n        {\n            ans.push_back(v[i].second);\n        }\n        sort(ans.begin(),ans.end());\n        return ans;   \n    }\n};"185    },186    {187        "title": "Heaters",188        "algo_input": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.\n\nEvery house can be warmed, as long as the house is within the heater's warm radius range.&nbsp;\n\nGiven the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters&nbsp;so that those heaters could cover all houses.\n\nNotice that&nbsp;all the heaters follow your radius standard, and the warm radius will the same.\n\n&nbsp;\nExample 1:\n\nInput: houses = [1,2,3], heaters = [2]\nOutput: 1\nExplanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.\n\n\nExample 2:\n\nInput: houses = [1,2,3,4], heaters = [1,4]\nOutput: 1\nExplanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.\n\n\nExample 3:\n\nInput: houses = [1,5], heaters = [2]\nOutput: 3\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= houses.length, heaters.length &lt;= 3 * 104\n\t1 &lt;= houses[i], heaters[i] &lt;= 109\n\n",189        "solution_py": "class Solution:\n    def findRadius(self, houses: List[int], heaters: List[int]) -> 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)",190        "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};",191        "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}",192        "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<int>& houses, vector<int>& 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};"193    },194    {195        "title": "Minimum Length of String After Deleting Similar Ends",196        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts only consists of characters 'a', 'b', and 'c'.\n\n",197        "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)",198        "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};",199        "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}",200        "solution_c": "class Solution {\npublic:\n    int minimumLength(string s) {\n        int i=0,j=s.length()-1;\n        while(i<j)\n        {\n            if(s[i]!=s[j])\n            {\n                break;\n            }\n            else\n            {\n                char x=s[i];\n                while(s[i]==x)\n                {\n                    i++;\n                }\n                if(i>j)\n                {\n                    return 0;\n                }\n                while(s[j]==x)\n                {\n                    j--;\n                }\n                if(j<i)\n                {\n                    return 0;\n                }\n            }\n        }\n        \n        return j-i+1;\n    }\n};"201    },202    {203        "title": "Find N Unique Integers Sum up to Zero",204        "algo_input": "Given an integer n, return any array containing n unique integers such that they add up to 0.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: [-7,-1,1,3,4]\nExplanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].\n\n\nExample 2:\n\nInput: n = 3\nOutput: [-1,0,1]\n\n\nExample 3:\n\nInput: n = 1\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 1000\n\n",205        "solution_py": "class Solution:\n    def sumZero(self, n: int) -> 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))",206        "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}",207        "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}",208        "solution_c": "class Solution {\npublic:\n    vector<int> sumZero(int n) {\n        if(n == 1){\n            return {0};\n        }else{\n            vector<int> 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};"209    },210    {211        "title": "Minimize Hamming Distance After Swap Operations",212        "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 &lt;= i &lt;= 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == source.length == target.length\n\t1 &lt;= n &lt;= 105\n\t1 &lt;= source[i], target[i] &lt;= 105\n\t0 &lt;= allowedSwaps.length &lt;= 105\n\tallowedSwaps[i].length == 2\n\t0 &lt;= ai, bi &lt;= n - 1\n\tai != bi\n\n",213        "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",214        "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};",215        "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<Integer, Map<Integer, Integer>> map = new HashMap<>();\n        for (int i=0; i<source.length; i++) {\n            int num = source[i];\n            int root = uf.find(i);\n            map.putIfAbsent(root, new HashMap<>());\n            Map<Integer, Integer> store = map.get(root);\n            store.put(num, store.getOrDefault(num, 0) + 1);\n        }\n        for (int i=0; i<source.length; i++) {\n            int num = target[i];\n            int root = uf.find(i);\n            Map<Integer, Integer> 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<n; i++)\n            parent[i] = i;\n    }\n    \n    public int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    public void union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rank[rootQ] > 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}",216        "solution_c": "class Solution {\npublic:\n    vector<int> parents;\n    vector<int> 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<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {\n        int n = source.size();\n        ranks = vector<int>(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<unordered_multiset<int>> 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};"217    },218    {219        "title": "Valid Triangle Number",220        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t0 &lt;= nums[i] &lt;= 1000\n\n",221        "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}",222        "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}",223        "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}",224        "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}"225    },226    {227        "title": "Design Authentication Manager",228        "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&nbsp;\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 &gt;= 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&nbsp;\nConstraints:\n\n\n\t1 &lt;= timeToLive &lt;= 108\n\t1 &lt;= currentTime &lt;= 108\n\t1 &lt;= tokenId.length &lt;= 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",229        "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",230        "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};",231        "solution_java": "class AuthenticationManager {\n    private int ttl;\n    private Map<String, Integer> 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<String, Integer> entry: this.map.entrySet())\n            if (entry.getValue() > currentTime)\n                count++;\n        \n        return count;\n    }\n}",232        "solution_c": "class AuthenticationManager {\n    int ttl;\n    unordered_map<string, int> 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};"233    },234    {235        "title": "Minimum Operations to Make the Array Alternating",236        "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 &lt;= i &lt;= n - 1.\n\tnums[i - 1] != nums[i], where 1 &lt;= i &lt;= 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 105\n\n",237        "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])",238        "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};",239        "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}",240        "solution_c": "class Solution {\npublic:\n    int minimumOperations(vector<int>& nums) {\n\n        int totalEven = 0, totalOdd = 0;\n\n        unordered_map<int,int> mapEven, mapOdd;\n\n        for(int i=0;i<nums.size();i++) {\n            if(i%2==0) {\n                totalEven++;\n                mapEven[nums[i]]++;\n            }\n\n            else {\n                totalOdd++;\n                mapOdd[nums[i]]++;\n            }\n        }\n\n        int firstEvenCount = 0, firstEven = 0;\n        int secondEvenCount = 0, secondEven = 0;\n\n        for(auto it=mapEven.begin();it!=mapEven.end();it++) {\n            int num = it->first;\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};"241    },242    {243        "title": "Valid Mountain Array",244        "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 &gt;= 3\n\tThere exists some i with 0 &lt; i &lt; arr.length - 1 such that:\n\t\n\t\tarr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] \n\t\tarr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]\n\t\n\t\n\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 104\n\t0 &lt;= arr[i] &lt;= 104\n\n",245        "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",246        "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};",247        "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(i<j && arr[i]<arr[i+1]) {\n            i++;\n        }\n        // use j pointer to iterate steep increase from RHS\n        while(j>i && arr[j]<arr[j-1]) {\n            j--;\n        }\n        // both should meet at same place and it be neither start or end.\n        return i==j && i<arr.length-1 && j>0;\n    }\n}",248        "solution_c": "class Solution {\npublic:\n    bool validMountainArray(vector<int>& arr) {\n        int flag = 1;\n        if((arr.size()<=2) || (arr[1] <= arr[0])) return false;\n        for(int i=1; i<arr.size(); i++){\n            if(flag){\n                if(arr[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};****"249    },250    {251        "title": "Binary Tree Cameras",252        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\tNode.val == 0\n\n",253        "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)",254        "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};",255        "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}",256        "solution_c": "class Solution {\npublic:\n    map<TreeNode*, int> 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};"257    },258    {259        "title": "Check if Word Equals Summation of Two Words",260        "algo_input": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -&gt; 0, 'b' -&gt; 1, 'c' -&gt; 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&nbsp;\nExample 1:\n\nInput: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput: true\nExplanation:\nThe numerical value of firstWord is \"acb\" -&gt; \"021\" -&gt; 21.\nThe numerical value of secondWord is \"cba\" -&gt; \"210\" -&gt; 210.\nThe numerical value of targetWord is \"cdb\" -&gt; \"231\" -&gt; 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\" -&gt; \"000\" -&gt; 0.\nThe numerical value of secondWord is \"a\" -&gt; \"0\" -&gt; 0.\nThe numerical value of targetWord is \"aab\" -&gt; \"001\" -&gt; 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\" -&gt; \"000\" -&gt; 0.\nThe numerical value of secondWord is \"a\" -&gt; \"0\" -&gt; 0.\nThe numerical value of targetWord is \"aaaa\" -&gt; \"0000\" -&gt; 0.\nWe return true because 0 + 0 == 0.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= firstWord.length, secondWord.length, targetWord.length &lt;= 8\n\tfirstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive.\n\n",261        "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",262        "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};",263        "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}",264        "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<firstWord.size();i++)\n            first=first*10 + (firstWord[i]-'a');\n        \n        for(int i=0;i<secondWord.size();i++)\n            second=second*10 +(secondWord[i]-'a');\n        \n        for(int i=0;i<targetWord.size();i++)\n            target=target*10 +(targetWord[i]-'a');\n        \n        \n        return first+second == target;\n    }\n};"265    },266    {267        "title": "Satisfiability of Equality Equations",268        "algo_input": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"xi==yi\" or \"xi!=yi\".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.\n\nReturn true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: equations = [\"a==b\",\"b!=a\"]\nOutput: false\nExplanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.\n\n\nExample 2:\n\nInput: equations = [\"b==a\",\"a==b\"]\nOutput: true\nExplanation: We could assign a = 1 and b = 1 to satisfy both equations.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= equations.length &lt;= 500\n\tequations[i].length == 4\n\tequations[i][0] is a lowercase letter.\n\tequations[i][1] is either '=' or '!'.\n\tequations[i][2] is '='.\n\tequations[i][3] is a lowercase letter.\n\n",269        "solution_py": "class Solution:\n    def equationsPossible(self, equations: List[str]) -> bool:\n        from collections import defaultdict\n        g = defaultdict(list)\n        for e in equations:\n            if e[1] == '=':\n                x = e[0]\n                y = e[3]\n                g[x].append(y)\n                g[y].append(x)\n        \n        # marked the connected components as 0,1,2,...,25\n        ccs = defaultdict(lambda: -1) # -1 means unmarked or unseen\n\n        def dfs(node, cc):\n            if node not in ccs:\n                ccs[node] = cc\n                for neighbour in g[node]:\n                    dfs(neighbour, cc)\n        \n        for i in range(26):\n            dfs(chr(i+97), i)\n        \n        for e in equations:\n            if e[1] == '!':\n                x = e[0]\n                y = e[3]\n                if ccs[x] == ccs[y]:\n                    return False\n        return True",270        "solution_js": "/**\n * @param {string[]} equations\n * @return {boolean}\n */\nclass UnionSet {\n    constructor() {\n        this.father = new Array(26).fill(0).map((item, index) => 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};",271        "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}",272        "solution_c": "class Solution {\npublic:    \n    bool equationsPossible(vector<string>& equations) {\n        \n        unordered_map<char,set<char>> equalGraph;       //O(26*26)\n        unordered_map<char,set<char>> 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<char> nbrs = it.second;         //all nbrs that should be unequal\n            if(nbrs.size() == 0) continue;\n                        \n            unordered_map<char,bool> 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<char,bool> &seen, unordered_map<char,set<char>> &equalGraph, set<char> &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};"273    },274    {275        "title": "Fraction to Recurring Decimal",276        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t-231 &lt;=&nbsp;numerator, denominator &lt;= 231 - 1\n\tdenominator != 0\n\n",277        "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])",278        "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};",279        "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<Long, Integer> map = new HashMap<Long, Integer>();\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}",280        "solution_c": "class Solution {\npublic:\n    string fractionToDecimal(int numerator, int denominator) {\n        unordered_map<int, int> 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};"281    },282    {283        "title": "Factorial Trailing Zeroes",284        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t0 &lt;= n &lt;= 104\n\n\n&nbsp;\nFollow up: Could you write a solution that works in logarithmic time complexity?\n",285        "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",286        "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};",287        "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}",288        "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};"289    },290    {291        "title": "Rotate Function",292        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\t-100 &lt;= nums[i] &lt;= 100\n\n",293        "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",294        "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<n;i++) {\n        sum += nums[i];\n        dp += i*nums[i];\n    }\n    let max = dp;\n    for (let i=1; i<n;i++) {\n        dp += sum - nums[n-i]*n;\n        max = Math.max(max, dp);\n    } \n    return max;\n};",295        "solution_java": "class Solution {\n    public int maxRotateFunction(int[] nums) {\n        int sum1 =0,sum2 = 0;\n        for(int i=0;i<nums.length;i++){\n            sum1 += nums[i];\n            sum2 += i*nums[i];\n        }\n        int result = sum2;\n        for(int i=0;i<nums.length;i++){\n            sum2 = sum2-sum1+(nums.length)*nums[i];\n            result = Math.max(result,sum2);\n        }\n        return result;\n    }\n}",296        "solution_c": "class Solution {\npublic:\n    int maxRotateFunction(vector<int>& A) {\n        long sum = 0, fn = 0;\n        int len = A.size();\n        for(int i=0;i<len;i++) {\n            sum += A[i];\n            fn += (i * A[i]);\n        }\n\n        long l = 1, r;\n        long newfn = fn;\n        \n        while(l < len) {\n            r = l + len - 1;\n            \n            long removed = (l-1) * A[l-1];\n            long added = r * A[r%len];\n            \n            newfn = newfn - removed + added - sum;\n            \n            fn = max(fn, newfn);\n            \n            l++;\n        }\n        \n        return (int)fn;\n    }\n};"297    },298    {299        "title": "Valid Parenthesis String",300        "algo_input": "Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.\n\nThe following rules define a valid string:\n\n\n\tAny left parenthesis '(' must have a corresponding right parenthesis ')'.\n\tAny right parenthesis ')' must have a corresponding left parenthesis '('.\n\tLeft parenthesis '(' must go before the corresponding right parenthesis ')'.\n\t'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string \"\".\n\n\n&nbsp;\nExample 1:\nInput: s = \"()\"\nOutput: true\nExample 2:\nInput: s = \"(*)\"\nOutput: true\nExample 3:\nInput: s = \"(*))\"\nOutput: true\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts[i] is '(', ')' or '*'.\n\n",301        "solution_py": "class Solution:\n    def checkValidString(self, s: str) -> 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",302        "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}",303        "solution_java": "class Solution{\n\tpublic boolean checkValidString(String s){\n\t\tStack<Integer> stack = new Stack<>();\n\t\tStack<Integer> star = new Stack<>();\n\t\tfor(int i=0;i<s.length();i++){\n\t\t\tif(s.charAt(i)=='(' ) \n                stack.push(i);\n            else if(s.charAt(i)=='*') \n                star.push(i);\n\t\t\telse {\n                if(!stack.isEmpty())\n                         stack.pop();\n                \n               else if(!star.isEmpty())\n                          star.pop();\n                 else \n                          return false;\n                \n\t\t\t}\n\t\t}\n        while(!stack.isEmpty()){\n            if(star.isEmpty()) \n                return false;\n            else if( stack.peek()<star.peek())                \n            {\n                star.pop();\n                stack.pop();\n            }\n            else\n                 return false;\n        }\n\t\treturn true;\n\t}\n}",304        "solution_c": "class Solution {\npublic:\n    bool checkValidString(string s) {\n        unordered_map<int, unordered_map<int, bool>> 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<int, unordered_map<int, bool>>& 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};"305    },306    {307        "title": "Water Bottles",308        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= numBottles &lt;= 100\n\t2 &lt;= numExchange &lt;= 100\n\n",309        "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)<b: return res \n            a += e\n            new=a//b\n            e = a-(new*b)\n            a=new\n            return sol(a,b,e,res)\n        \n        return sol(a,b,0,0)",310        "solution_js": "var numWaterBottles = function(numBottles, numExchange) {\n    let count = 0;\n    let emptyBottles = 0;\n    while (numBottles > 0) {\n        count += numBottles;\n        emptyBottles += numBottles;\n        numBottles = Math.floor(emptyBottles / numExchange);\n        emptyBottles -= numBottles  * numExchange;\n    }\n    \n    \n    return count;\n};",311        "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}",312        "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<<numBottles<<\" \";\n        }\n        return res;\n    }\n};"313    },314    {315        "title": "Smallest Subsequence of Distinct Characters",316        "algo_input": "Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.\n\n&nbsp;\nExample 1:\n\nInput: s = \"bcabc\"\nOutput: \"abc\"\n\n\nExample 2:\n\nInput: s = \"cbacdcbc\"\nOutput: \"acdb\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts consists of lowercase English letters.\n\n\n&nbsp;\nNote: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/",317        "solution_py": "class Solution:\n    def smallestSubsequence(self, s: str) -> 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)",318        "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};",319        "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<Character> 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}",320        "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<s.size();i++) m[s[i]]++;\n        \n        stack< char> 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;i<s.size();i++){\n            \n            m[ s[i]]--;\n            if(!vis[ s[i]-'a']){\n                while( !t.empty() &&  m[t.top()] >0 && 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};"321    },322    {323        "title": "Nth Magical Number",324        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\t2 &lt;= a, b &lt;= 4 * 104\n\n",325        "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)",326        "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<high){\n        let mid = Math.floor((low+high)/2);\n        let ans = Math.floor(mid/a)+Math.floor(mid/b)-Math.floor(mid/lcmAB);\n        if(ans<n){\n            low = mid + 1;\n        }else{\n            high = mid;\n        }\n    }\n    return high%modulo;\n};",327        "solution_java": "class Solution {\npublic int nthMagicalNumber(int n, int a, int b) {\n    long N=(long)n;\n    long A=(long)a;\n    long B=(long)b;\n    long mod=1000000007;\n    long min=Math.min(A,B);\n    long low=min;\n    long high=min*N;\n    long ans=0;\n    while(low<=high)\n    {\n        long mid=(high-low)/2+low;\n        long x=mid/A+mid/B-mid/lcm(A,B);\n        if(x>=N)\n        {\n            ans=mid;\n            high=mid-1;\n        }\n        else if(x<N)\n        {\n            low=mid+1;\n        }\n        else{\n            high=mid-1;\n        }\n    }\n\n    ans=ans%mod;\n    return (int)ans;\n}\n\nlong lcm(long a,long b)\n{\n    long tmpA=a;\n    long tmpB=b;\n    while(a>0)\n    {\n        long temp=a;\n        a=b%a;\n        b=temp;\n    }\n\n    return tmpA*tmpB/b;\n}\n}",328        "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*/"329    },330    {331        "title": "Search in Rotated Sorted Array II",332        "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 &lt;= k &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5000\n\t-104 &lt;= nums[i] &lt;= 104\n\tnums is guaranteed to be rotated at some pivot.\n\t-104 &lt;= target &lt;= 104\n\n\n&nbsp;\nFollow up: This problem is similar to&nbsp;Search in Rotated Sorted Array, but&nbsp;nums may contain duplicates. Would this affect the runtime complexity? How and why?\n",333        "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",334        "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};",335        "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}",336        "solution_c": "class Solution {\npublic:\n    bool search(vector<int>& 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};"337    },338    {339        "title": "Video Stitching",340        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= clips.length &lt;= 100\n\t0 &lt;= starti &lt;= endi &lt;= 100\n\t1 &lt;= time &lt;= 100\n\n",341        "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]",342        "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};",343        "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}",344        "solution_c": "class Solution {\npublic:\n    static bool comp(vector<int> a, vector<int> b){\n        if(a[0]<b[0]) return true;\n        else if(a[0]==b[0]) return a[1]>b[1];\n        return false;\n    }\n\n    int videoStitching(vector<vector<int>>& clips, int time) {\n        sort(clips.begin(), clips.end(), comp);\n        vector<vector<int>> 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<clips.size(); i++){\n            if(res.back()[1]>=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; i<res.size(); i++){\n            if(res[i][0]>prev) return -1;\n            prev = res[i][1];\n        }\n        //check explicitly for the last value\n        if(res.back()[1]<time) return -1;\n        return res.size();\n    }\n};"345    },346    {347        "title": "Can Place Flowers",348        "algo_input": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.\n\nGiven an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.\n\n&nbsp;\nExample 1:\nInput: flowerbed = [1,0,0,0,1], n = 1\nOutput: true\nExample 2:\nInput: flowerbed = [1,0,0,0,1], n = 2\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= flowerbed.length &lt;= 2 * 104\n\tflowerbed[i] is 0 or 1.\n\tThere are no two adjacent flowers in flowerbed.\n\t0 &lt;= n &lt;= flowerbed.length\n\n",349        "solution_py": "class Solution:\n    def canPlaceFlowers(self, flowerbed: List[int], n: int) -> 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",350        "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.length ; i++) {\n        if((i===0 || flowerbed[i-1]===0) && flowerbed[i]===0 && (i===flowerbed.length-1 || flowerbed[i+1]===0)) {\n            flowerbed[i]=1;\n            n--;\n        }\n    }\n    return n < 1;\n};",351        "solution_java": "class Solution {\n    public boolean canPlaceFlowers(int[] flowerbed, int n) {\n        if(flowerbed[0] != 1){\n            n--;\n            flowerbed[0] = 1;   \n        }\n        for(int i = 1; i < flowerbed.length; i++){\n            if(flowerbed[i - 1] == 1 && flowerbed[i] == 1){\n                flowerbed[i - 1] = 0;\n                n++;\n            }\n            if(flowerbed[i - 1] != 1 && flowerbed[i] != 1){\n                flowerbed[i] = 1;\n                n--;\n            }\n        }\n        return (n <= 0) ? true: false;\n    }\n}",352        "solution_c": "class Solution {\npublic:\n    bool canPlaceFlowers(vector<int>& flowerbed, int n) {\n       int count = 1;\n    int result = 0;\n    for(int i=0; i<flowerbed.size(); i++) {\n        if(flowerbed[i] == 0) {\n            count++;\n        }else {\n            result += (count-1)/2;\n            count = 0;\n        }\n    }\n    if(count != 0) result += count/2;\n    return result>=n; \n    }\n};"353    },354    {355        "title": "Add Minimum Number of Rungs",356        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= rungs.length &lt;= 105\n\t1 &lt;= rungs[i] &lt;= 109\n\t1 &lt;= dist &lt;= 109\n\trungs is strictly increasing.\n\n",357        "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<len(rungs): \n            if rungs[i]-rungs[i-1] > dist:\n                ans+=ceil((rungs[i]-rungs[i-1])/dist)-1\n            i+=1\n        return ans\n\n\n\n            ",358        "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};",359        "solution_java": "class Solution {\n    public int addRungs(int[] rungs, int dist) {\n        int ans = 0;\n        for (int i=0 ; i<rungs.length ; i++) {\n            int d = (i==0) ? rungs[i] : rungs[i] - rungs[i-1];\n            if ( d > dist ) {\n                ans += d/dist;\n                ans += ( d%dist == 0 ) ? -1 : 0;\n            }\n        }\n        return ans;\n    }\n}",360        "solution_c": "class Solution {\npublic:\n    int addRungs(vector<int>& 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\"<<endl;\n                 long long int temp = (rungs[nextposidx] - currpos);\n                 //cout<<\"temp = \"<<temp<<endl;\n                 \n                 if((temp%dist) == 0)\n                 {\n                     long long int val = temp/dist;\n                     count = count + (val - 1);\n                 }\n                 else\n                 {\n                    long long int val = floor(((temp*1.00)/(dist*1.00)));\n                    count = count + (val);\n                 }\n                 currpos = rungs[nextposidx];\n             }\n         }\n         return count;\n    }\n};"361    },362    {363        "title": "Car Pooling",364        "algo_input": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).\n\nYou are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.\n\nReturn true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput: false\n\n\nExample 2:\n\nInput: trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput: true\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= trips.length &lt;= 1000\n\ttrips[i].length == 3\n\t1 &lt;= numPassengersi &lt;= 100\n\t0 &lt;= fromi &lt; toi &lt;= 1000\n\t1 &lt;= capacity &lt;= 105\n\n",365        "solution_py": "class Solution:\n    def carPooling(self, trips: List[List[int]], capacity: int) -> 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        ",366        "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};",367        "solution_java": "class Solution {\n    public boolean carPooling(int[][] trips, int capacity) {\n        Map<Integer, Integer> 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}",368        "solution_c": "class Solution {\ntypedef pair<int, int> pd;\npublic:\n    bool carPooling(vector<vector<int>>& trips, int capacity) {\n        int seat=0;\n        priority_queue<pd, vector<pd>, greater<pd>>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<<pq.top().first<<\" \"<<pq.top().second<<endl;\n            // cout<<\"seat-\"<<seat<<endl;\n            seat+=pq.top().second;\n            if(seat>capacity) return false;\n            pq.pop();\n        }\n        return true;\n    }\n};"369    },370    {371        "title": "Rotate Array",372        "algo_input": "Given an array, rotate the array to the right by k steps, where k is non-negative.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\t0 &lt;= k &lt;= 105\n\n\n&nbsp;\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",373        "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",374        "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};",375        "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<end){\n            int temp = arr[start];\n            arr[start] = arr[end];\n            arr[end] = temp;\n            start++;\n            end--;\n        }\n    }\n}",376        "solution_c": "class Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n\n        vector<int> 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};"377    },378    {379        "title": "License Key Formatting",380        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of English letters, digits, and dashes '-'.\n\t1 &lt;= k &lt;= 104\n\n",381        "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]",382        "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};",383        "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}",384        "solution_c": "class Solution {\npublic:\n    string licenseKeyFormatting(string s, int k) {\n        stack<char>st;\n        string ans=\"\";\n        for(int i=0;i<s.length();i++){\n            if(isalpha(s[i]) || isdigit(s[i])){\n                st.push(s[i]);\n            }\n        }\n        int i=0;\n        while(st.size()>0){\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};"385    },386    {387        "title": "Count the Hidden Sequences",388        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == differences.length\n\t1 &lt;= n &lt;= 105\n\t-105 &lt;= differences[i] &lt;= 105\n\t-105 &lt;= lower &lt;= upper &lt;= 105\n\n",389        "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)))",390        "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};",391        "solution_java": "class Solution {\n    public int numberOfArrays(int[] differences, int lower, int upper) {\n        ArrayList<Integer> 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}",392        "solution_c": "using ll = long long int;\nclass Solution {\n    public:\n    int numberOfArrays(vector<int>& differences, int lower, int upper) {\n        vector<ll> 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}; "393    },394    {395        "title": "All Divisions With the Highest Score of a Binary Array",396        "algo_input": "You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 &lt;= i &lt;= 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= n &lt;= 105\n\tnums[i] is either 0 or 1.\n\n",397        "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",398        "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<n;i++){\n            if(nums[i]==0)zeros[i+1]=zeros[i]+1;\n            else zeros[i+1]=zeros[i];\n        }\n\n        // count no of ones from right to left\n        for(let i=n-1;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;i<n+1;i++){\n            total[i]=ones[i]+zeros[i];\n            if(total[i]>max)max=total[i];\n        }\n\n        // Find occurrence of max elements and return those indexes\n        let ans= [];\n        for(let i=0;i<n+1;i++){\n            if(total[i]==max)ans.push(i);\n        }\n\n        return ans;\n};",399        "solution_java": "class Solution {\n    public List<Integer> maxScoreIndices(int[] nums) {\n        int N = nums.length;\n        List<Integer> 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}",400        "solution_c": "class Solution {\npublic:\n    vector<int> maxScoreIndices(vector<int>& 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<n;i++)\n        {\n            if(nums[i]==1)\n                one++;\n        }\n        if(nums[0]==0)\n            zero++;\n        vector<int> v;\n        v.push_back(one);\n        int ans=one;\n        if(nums[0]==1)\n            one--;\n        \n        for(int i=1;i<n;i++)\n        {\n            if(nums[i]==1)\n            {\n                v.push_back(zero+one);\n                one--;\n            }\n            else\n            {\n                v.push_back(zero+one);\n                zero++;\n            }\n            ans=max(ans,zero+one);   \n        }\n        \n        v.push_back(zero);\n        vector<int> res;\n        for(int i=0;i<=n;i++)\n        {\n            // cout<<v[i]<<\" \";\n            if(v[i]==ans)\n                res.push_back(i);\n        }\n        return res;\n    }\n};"401    },402    {403        "title": "Merge k Sorted Lists",404        "algo_input": "You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n\nMerge all the linked-lists into one sorted linked-list and return it.\n\n&nbsp;\nExample 1:\n\nInput: lists = [[1,4,5],[1,3,4],[2,6]]\nOutput: [1,1,2,3,4,4,5,6]\nExplanation: The linked-lists are:\n[\n  1-&gt;4-&gt;5,\n  1-&gt;3-&gt;4,\n  2-&gt;6\n]\nmerging them into one sorted list:\n1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6\n\n\nExample 2:\n\nInput: lists = []\nOutput: []\n\n\nExample 3:\n\nInput: lists = [[]]\nOutput: []\n\n\n&nbsp;\nConstraints:\n\n\n\tk == lists.length\n\t0 &lt;= k &lt;= 104\n\t0 &lt;= lists[i].length &lt;= 500\n\t-104 &lt;= lists[i][j] &lt;= 104\n\tlists[i] is sorted in ascending order.\n\tThe sum of lists[i].length will not exceed 104.\n\n",405        "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\nfrom heapq import heappush,heappop\nclass Solution:\n    def mergeKLists(self, lists: List[Optional[ListNode]]) -> 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",406        "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};",407        "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}",408        "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<ListNode*>& lists) {\n        priority_queue<ListNode*,vector<ListNode*>,compare>minh;\n        for(int i=0;i<lists.size();i++)\n        {\n           if(lists[i]!=NULL) minh.push(lists[i]);\n        }\n        ListNode* head=new ListNode(0);\n        ListNode* temp=head;\n        while(minh.size()>0)\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};"409    },410    {411        "title": "Minimum Replacements to Sort the Array",412        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 109\n\n",413        "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",414        "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};",415        "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}",416        "solution_c": "class Solution {\npublic:\n    long long minimumReplacement(vector<int>& 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};"417    },418    {419        "title": "Sum of Numbers With Units Digit K",420        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t0 &lt;= num &lt;= 3000\n\t0 &lt;= k &lt;= 9\n\n",421        "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",422        "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};",423        "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}",424        "solution_c": "class Solution {\npublic:\n   \n    //same code as that of coin change\n    int coinChange(vector<int>& coins, int amount) {\n        int Max = amount + 1;\n        vector<int> 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    vector<int>res;\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};"425    },426    {427        "title": "Minimum Operations to Make Array Equal",428        "algo_input": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e.,&nbsp;0 &lt;= i &lt; n).\n\nIn one operation, you can select two indices x and y where 0 &lt;= x, y &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",429        "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])",430        "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<reqNum; i +=2){\n        count += (reqNum-i)\n    }\n    return count\n};",431        "solution_java": "class Solution {\n    public int minOperations(int n) {\n        int ans = (n/2)*(n/2);\n        if(n%2==1){\n            ans += n/2;\n        }\n        return ans;\n    }\n}",432        "solution_c": "class Solution {\npublic:\n    int minOperations(int n) {\n        int s=0;\n        for(int i=0; i<= (n-1)/2; ++i){\n            s += fabs(n-(2*i+1));\n        }\n        return s;\n    }\n};"433    },434    {435        "title": "Keep Multiplying Found Values by Two",436        "algo_input": "You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.\n\nYou then do the following steps:\n\n\n\tIf original is found in nums, multiply it by two (i.e., set original = 2 * original).\n\tOtherwise, stop the process.\n\tRepeat this process with the new number as long as you keep finding the number.\n\n\nReturn the final value of original.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,3,6,1,12], original = 3\nOutput: 24\nExplanation: \n- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.\n\n\nExample 2:\n\nInput: nums = [2,7,9], original = 4\nOutput: 4\nExplanation:\n- 4 is not found in nums. Thus, 4 is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 1000\n\t1 &lt;= nums[i], original &lt;= 1000\n\n",437        "solution_py": "class Solution:\n    def findFinalValue(self, nums: List[int], original: int) -> int:\n        while original in nums:\n            original *= 2\n        return original",438        "solution_js": "var findFinalValue = function(nums, original) {\n    while (nums.includes(original)) {\n        original = original * 2\n    }\n\n    return original\n};",439        "solution_java": "class Solution\n{\n    public int findFinalValue(int[] nums, int original)\n    {\n        HashSet<Integer> 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}",440        "solution_c": "class Solution {\npublic:\n    int findFinalValue(vector<int>& nums, int original) {\n        int n = 1;\n        for(int i = 0; i<n;++i)\n        {\n            if(find(nums.begin(),nums.end(),original) != nums.end())    //find func detailled explanation above\n            {\n                original *= 2;\n                n += 1; //n is incremented by one beacuse questions want us to perform the operation again if element is found again after its double.\n            }\n        }\n        return original;\n    }\n};"441    },442    {443        "title": "Next Permutation",444        "algo_input": "A permutation of an array of integers is an arrangement of its members into a sequence or linear order.\n\n\n\tFor example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].\n\n\nThe next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).\n\n\n\tFor example, the next permutation of arr = [1,2,3] is [1,3,2].\n\tSimilarly, the next permutation of arr = [2,3,1] is [3,1,2].\n\tWhile the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.\n\n\nGiven an array of integers nums, find the next permutation of nums.\n\nThe replacement must be in place and use only constant extra memory.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,2,3]\nOutput: [1,3,2]\n\n\nExample 2:\n\nInput: nums = [3,2,1]\nOutput: [1,2,3]\n\n\nExample 3:\n\nInput: nums = [1,1,5]\nOutput: [1,5,1]\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 100\n\n",445        "solution_py": "class Solution:\n    def nextPermutation(self, nums) -> 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",446        "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};",447        "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}",448        "solution_c": "class Solution {\npublic:\n    void nextPermutation(vector<int>& 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};"449    },450    {451        "title": "Out of Boundary Paths",452        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 50\n\t0 &lt;= maxMove &lt;= 50\n\t0 &lt;= startRow &lt; m\n\t0 &lt;= startColumn &lt; n\n\n",453        "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            ",454        "solution_js": "vector<vector<vector<int>>> 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<vector<vector<int>>>(m, vector<vector<int>>(n, vector<int>(maxMove+1, -1)));\n\t\n    return fun(startRow, startCol,m,n,maxMove);\n}",455        "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}",456        "solution_c": "vector<vector<vector<int>>> 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<vector<vector<int>>>(m, vector<vector<int>>(n, vector<int>(maxMove+1, -1)));\n\t\n    return fun(startRow, startCol,m,n,maxMove);\n}"457    },458    {459        "title": "Count of Range Sum",460        "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 &lt;= j.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-231 &lt;= nums[i] &lt;= 231 - 1\n\t-105 &lt;= lower &lt;= upper &lt;= 105\n\tThe answer is guaranteed to fit in a 32-bit integer.\n\n",461        "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",462        "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};",463        "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}",464        "solution_c": "class Solution {\npublic:\n    using ll = long long;\n\n    int countRangeSum(vector<int>& nums, int lower, int upper) {\n        // Build prefix sums\n        vector<ll> 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<ll> &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<ll> &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<ll> &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<ll> tempNums;\n    int count = 0;\n};"465    },466    {467        "title": "Vertical Order Traversal of a Binary Tree",468        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 1000].\n\t0 &lt;= Node.val &lt;= 1000\n\n",469        "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",470        "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};",471        "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<List<Integer>> verticalTraversal(TreeNode root) {\n        Map<Integer, PriorityQueue<MNode>> map = new TreeMap<>();\n        Queue<MNode> 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<MNode> 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<List<Integer>> ans = new ArrayList<>();\n        for(Integer key: map.keySet()) {\n            List<Integer> 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}",472        "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<vector<int>> verticalTraversal(TreeNode* root) {\n        map<int,vector<int>> mp;\n        queue<pair<TreeNode*,int>> q;\n        q.push({root,0});\n        while(!q.empty()){\n            int sz = q.size();\n            map<int,multiset<int>> temp;\n            for(int i=0;i<sz;i++){\n                auto pr = q.front();\n                q.pop();\n                temp[pr.second].insert(pr.first->val);\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<vector<int>> ans;\n        for(auto pr:mp){\n            vector<int> temp;\n            for(auto val:pr.second){\n                temp.push_back(val);\n            }\n            ans.push_back(temp);\n        }\n        return ans;\n    }\n};"473    },474    {475        "title": "XOR Queries of a Subarray",476        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length, queries.length &lt;= 3 * 104\n\t1 &lt;= arr[i] &lt;= 109\n\tqueries[i].length == 2\n\t0 &lt;= lefti &lt;= righti &lt; arr.length\n\n",477        "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",478        "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``",479        "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}",480        "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<int> xorQueries(vector<int>& arr, vector<vector<int>>& 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<int> 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};"481    },482    {483        "title": "Count Unguarded Cells in the Grid",484        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= m, n &lt;= 105\n\t2 &lt;= m * n &lt;= 105\n\t1 &lt;= guards.length, walls.length &lt;= 5 * 104\n\t2 &lt;= guards.length + walls.length &lt;= m * n\n\tguards[i].length == walls[j].length == 2\n\t0 &lt;= rowi, rowj &lt; m\n\t0 &lt;= coli, colj &lt; n\n\tAll the positions in guards and walls are unique.\n\n",485        "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)                    ",486        "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};",487        "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}",488        "solution_c": "class Solution {\npublic:\n    void dfs( vector<vector<int>> &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<vector<int>>& guards, vector<vector<int>>& walls) {\n         vector<vector<int>> grid(m,vector<int>(n,0));\n        //marking guards\n        for(int i=0;i<guards.size();i++){\n            int x=guards[i][0];\n            int y=guards[i][1];\n            grid[x][y]=1;\n        }\n        // marking walls\n         for(int i=0;i<walls.size();i++){\n            int x=walls[i][0];\n            int y=walls[i][1];\n            grid[x][y]=2;\n        }\n        // dfs in each of 4 directions\n          for(int i=0;i<guards.size();i++){\n            int x=guards[i][0];\n            int y=guards[i][1];\n              dfs(grid,x+1,y,m,n,1);\n              dfs(grid,x,y+1,m,n,2);\n              dfs(grid,x-1,y,m,n,3);\n              dfs(grid,x,y-1,m,n,4);\n          }\n        long long 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) cnt++;\n            }\n        }\n        return cnt;\n    }\n};"489    },490    {491        "title": "Student Attendance Record I",492        "algo_input": "You are given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:\n\n\n\t'A': Absent.\n\t'L': Late.\n\t'P': Present.\n\n\nThe student is eligible for an attendance award if they meet both of the following criteria:\n\n\n\tThe student was absent ('A') for strictly fewer than 2 days total.\n\tThe student was never late ('L') for 3 or more consecutive days.\n\n\nReturn true if the student is eligible for an attendance award, or false otherwise.\n\n&nbsp;\nExample 1:\n\nInput: s = \"PPALLP\"\nOutput: true\nExplanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.\n\n\nExample 2:\n\nInput: s = \"PPALLL\"\nOutput: false\nExplanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts[i] is either 'A', 'L', or 'P'.\n\n",493        "solution_py": "class Solution:\n    def checkRecord(self, s: str) -> 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)",494        "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};",495        "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}",496        "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/*********************************************************/"497    },498    {499        "title": "Get Equal Substrings Within Budget",500        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\tt.length == s.length\n\t0 &lt;= maxCost &lt;= 106\n\ts and t consist of only lowercase English letters.\n\n",501        "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            ",502        "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};",503        "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}",504        "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};"505    },506    {507        "title": "Maximum Repeating Substring",508        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= sequence.length &lt;= 100\n\t1 &lt;= word.length &lt;= 100\n\tsequence and word&nbsp;contains only lowercase English letters.\n\n",509        "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",510        "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};",511        "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}",512        "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};"513    },514    {515        "title": "Count Square Sum Triples",516        "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 &lt;= a, b, c &lt;= n.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 250\n\n",517        "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",518        "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};",519        "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}",520        "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};"521    },522    {523        "title": "Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts",524        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= h, w &lt;= 109\n\t1 &lt;= horizontalCuts.length &lt;= min(h - 1, 105)\n\t1 &lt;= verticalCuts.length &lt;= min(w - 1, 105)\n\t1 &lt;= horizontalCuts[i] &lt; h\n\t1 &lt;= verticalCuts[i] &lt; w\n\tAll the elements in horizontalCuts are distinct.\n\tAll the elements in verticalCuts are distinct.\n\n",525        "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)",526        "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<horizontalCuts.length; i++){\n        max_hor_dis = Math.max(max_hor_dis, horizontalCuts[i] - horizontalCuts[i-1])\n    }\n    for(let i=1; i<verticalCuts.length; i++){\n        max_ver_dis = Math.max(max_ver_dis, verticalCuts[i] - verticalCuts[i-1])\n    }\n    return BigInt(max_hor_dis) * BigInt(max_ver_dis) % BigInt(1e9+7)\n};",527        "solution_java": "import java.math.BigInteger;\nclass Solution {\n    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {\n        Arrays.sort(horizontalCuts);\n        Arrays.sort(verticalCuts);\n        int i;\n        int hMax=horizontalCuts[0];\n        for(i=1;i<horizontalCuts.length;i++)\n            // if(hMax < horizontalCuts[i]-horizontalCuts[i-1])\n                hMax=Math.max(hMax,horizontalCuts[i]-horizontalCuts[i-1]);\n        if(h-horizontalCuts[horizontalCuts.length-1] > hMax)\n            hMax= h-horizontalCuts[horizontalCuts.length-1];\n        int vMax=verticalCuts[0];\n        for(i=1;i<verticalCuts.length;i++)\n            // if(vMax < verticalCuts[i]-verticalCuts[i-1])\n                vMax=Math.max(vMax,verticalCuts[i]-verticalCuts[i-1]);\n        if(w-verticalCuts[verticalCuts.length-1] > vMax)\n            vMax= w-verticalCuts[verticalCuts.length-1];\n        return (int)((long)hMax*vMax%1000000007);\n    }\n}",528        "solution_c": "class Solution {\npublic:\n    int maxArea(int h, int w, vector<int>& horizontalCuts, vector<int>& 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};"529    },530    {531        "title": "Expressive Words",532        "algo_input": "Sometimes people repeat letters to represent extra feeling. For example:\n\n\n\t\"hello\" -&gt; \"heeellooo\"\n\t\"hi\" -&gt; \"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\" -&gt; \"lllll\" to get \"helllllooo\". If s = \"helllllooo\", then the query word \"hello\" would be stretchy because of these two extension operations: query = \"hello\" -&gt; \"hellooo\" -&gt; \"helllllooo\" = s.\n\n\nReturn the number of query strings that are stretchy.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 100\n\ts and words[i] consist of lowercase letters.\n\n",533        "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",534        "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};",535        "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; i<len; i++) {\n            if(s.charAt(i) == prevChar) {\n                currFreq++;\n            } else {\n                freqString.append(currFreq);\n                freqString.append(s.charAt(i));\n                currFreq = 1;\n            }\n            prevChar = s.charAt(i);\n        }\n        \n        if(currFreq>0) {\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<sLen; i++) {\n            char sChar = s.charAt(i);\n            char wChar = word.charAt(i);\n            if(i%2 != 0) {       \n                if(sChar < wChar) {\n                    return false;\n                } if(isGreaterButLessThanThree(sChar, wChar)) {\n                    return false;\n                }\n                \n            } else if(sChar != wChar){\n                    return false;\n            }\n        }\n        \n        return true;\n    }\n    \n    public int expressiveWords(String s, String[] words) {\n        int wordLen = words.length;\n        if(wordLen < 1 || s.length() < 1) {\n            return 0;\n        }\n        \n        int stretchyWords = 0;\n        String freqStringS = getFreqString(s);\n        for(String word: words) {\n            String freqStringWord = getFreqString(word); \n            if(isStretchy(freqStringS, freqStringWord)) {\n                stretchyWords++;\n            }\n            \n        }  \n        return stretchyWords;\n    }\n}",536        "solution_c": "class Solution {\npublic:\n    \n    // Basically get the length of a repeated sequence starting at pointer p. \n    int getRepeatedLen(string& s, int p) {\n        int res = 0; \n        char c = s[p]; \n        while(p < s.size() && s[p] == c) {\n            res++;\n            p++;\n        }\n        return res; \n    }\n    \n    // Check if a word t is stretchy. i.e. can we turn word t into word s? \n    bool isStretchy(string& s, string& t, unordered_set<char>& 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<string>& words) {\n        int res = 0; \n        unordered_set<char> 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};"537    },538    {539        "title": "Maximum Subarray",540        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\n\n&nbsp;\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",541        "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)",542        "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}; ",543        "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<n;i++) {\n            currmax+=nums[i];\n            gmax=Math.max(gmax, currmax);\n            currmax=Math.max(currmax, 0);\n        }\n        return gmax;\n    }\n}",544        "solution_c": "class Solution {\npublic:\n    int maxSubArray(vector<int>& 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};"545    },546    {547        "title": "Minimum Cost to Make at Least One Valid Path in a Grid",548        "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&nbsp;\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) --&gt; (0, 1) --&gt; (0, 2) --&gt; (0, 3) change the arrow to down with cost = 1 --&gt; (1, 3) --&gt; (1, 2) --&gt; (1, 1) --&gt; (1, 0) change the arrow to down with cost = 1 --&gt; (2, 0) --&gt; (2, 1) --&gt; (2, 2) --&gt; (2, 3) change the arrow to down with cost = 1 --&gt; (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&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 100\n\t1 &lt;= grid[i][j] &lt;= 4\n\n",549        "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                    ",550        "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};",551        "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<n && j<m && 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<int[]> queue = new LinkedList<>(); // for performing 01 BFS\n\n        for(int i=0;i<n;i++)\n            Arrays.fill(dist[i],Integer.MAX_VALUE);\n\n        queue.add(new int[]{0,0});\n        dist[0][0]=0;\n\n        while(!queue.isEmpty()) {\n\n            int[] currEle = queue.remove();\n            vis[currEle[0]][currEle[1]] = true;\n\n            for(int[] currDir:dirs) {\n\n                    int nx = currDir[0]+currEle[0];\n                    int ny = currDir[1]+currEle[1];\n                    if(isValid(nx,ny,n,m) && vis[nx][ny]==false) {\n\n                        if(isValidDirection(grid,currEle,nx,ny)) {\n                            dist[nx][ny] = Math.min(dist[nx][ny],dist[currEle[0]][currEle[1]]);\n                            queue.add(0,new int[]{nx,ny});\n                        }\n                        else {\n                        dist[nx][ny] = Math.min(dist[nx][ny],1+dist[currEle[0]][currEle[1]]);\n                            queue.add(new int[]{nx,ny});\n                        }\n                    }\n            }\n\n        }\n\n       return dist[n-1][m-1];\n    }\n}",552        "solution_c": "#define vv vector<int>\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<vector<int>>& grid) {\n\n        int m=grid.size();\n        int n=grid[0].size();\n\n        priority_queue< vv , vector<vv> , greater<vv>> pq;\n\n        vector<vector<int>> dp(m+3 , vector<int>(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 && newi<m && newj<n)\n                {\n                    if((k+1)==grid[i][j])\n                    {\n                        if(dp[newi][newj]>cost)\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};"553    },554    {555        "title": "Sum Game",556        "algo_input": "Alice and Bob take turns playing a game, with Alice&nbsp;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&nbsp;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&nbsp;to win, the sums must not be equal.\n\n\n\tFor example, if the game ended with num = \"243801\", then Bob&nbsp;wins because 2+4+3 = 8+0+1. If the game ended with num = \"243803\", then Alice&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= num.length &lt;= 105\n\tnum.length is even.\n\tnum consists of only digits and '?'.\n\n",557        "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",558        "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};",559        "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}",560        "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};"561    },562    {563        "title": "Number of Arithmetic Triplets",564        "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 &lt; j &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t3 &lt;= nums.length &lt;= 200\n\t0 &lt;= nums[i] &lt;= 200\n\t1 &lt;= diff &lt;= 50\n\tnums is strictly increasing.\n\n",565        "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",566        "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};",567        "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}",568        "solution_c": "class Solution {\npublic:\n    int arithmeticTriplets(vector<int>& nums, int diff) {\n        int ans=0;\n        for(int i=0;i<nums.size();i++){\n            for(int j=i+1;j<nums.size();j++){\n                for(int k=j+1;k<nums.size();k++){\n                    if((nums[j]-nums[i])==diff && (nums[k]-nums[j])==diff){\n                        ans++;\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n};"569    },570    {571        "title": "Letter Combinations of a Phone Number",572        "algo_input": "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.\n\nA mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.\n\n&nbsp;\nExample 1:\n\nInput: digits = \"23\"\nOutput: [\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]\n\n\nExample 2:\n\nInput: digits = \"\"\nOutput: []\n\n\nExample 3:\n\nInput: digits = \"2\"\nOutput: [\"a\",\"b\",\"c\"]\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= digits.length &lt;= 4\n\tdigits[i] is a digit in the range ['2', '9'].\n\n",573        "solution_py": "class Solution:\n    def letterCombinations(self, digits: str) -> 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",574        "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};",575        "solution_java": "class Solution {\n    String[] num = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n    public List<String> letterCombinations(String digits) {\n        List<String> 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<String> 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}",576        "solution_c": "class Solution {\npublic:\n\n    void solve(string digit,string output,int index,vector<string>&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<value.length();i++)\n        {\n            output.push_back(value[i]);\n            solve(digit,output,index+1,ans,mapping);\n            //backtrack\n            //backtrach because initially output is empty and one case solves now you have to solve second case in similar way\n            output.pop_back(); }\n\n    }\n\n    vector<string> letterCombinations(string digits) {\n\n        vector<string>ans;\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};"577    },578    {579        "title": "Number of Sets of K Non-Overlapping Line Segments",580        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 1000\n\t1 &lt;= k &lt;= n-1\n\n",581        "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)",582        "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 <i; k++)\n            dp[i][k]=(dp[i-1][k-1]+dp[i-1][k]) %(1e9+7)     \n    return dp[n][k]\n}",583        "solution_java": "class Solution {\n    Integer[][][] memo;\n    int n;\n    public int numberOfSets(int n, int k) {\n        this.n = n;\n        this.memo = new Integer[n+1][k+1][2];\n        return dp(0, k, 1);\n    }\n    int dp(int i, int k, int isStart) {\n        if (memo[i][k][isStart] != null) return memo[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\n        int ans = dp(i+1, k, isStart); // Skip ith point\n        if (isStart == 1)\n            ans += dp(i+1, k, 0); // Take ith point as start\n        else\n            ans += dp(i, k-1, 1); // Take ith point as end\n\n        return memo[i][k][isStart] = ans % 1_000_000_007;\n    }\n}",584        "solution_c": "class Solution {\npublic:\n    int MOD = 1e9+7;\n    int sumDyp(int n, int k, vector<vector<int>> &dp, vector<vector<int>> &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<vector<int>> &dp, vector<vector<int>> &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<vector<int>> dp(n+1, vector<int>(k+1, -1));\n        vector<vector<int>> sumDp(n+1, vector<int>(k+1, -1));\n        return dyp(n, k, dp, sumDp);\n    }\n};"585    },586    {587        "title": "Display Table of Food Orders in a Restaurant",588        "algo_input": "Given&nbsp;the array orders, which represents the orders that customers have done in a restaurant. More specifically&nbsp;orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi&nbsp;is the table customer sit at, and foodItemi&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;orders.length &lt;= 5 * 10^4\n\torders[i].length == 3\n\t1 &lt;= customerNamei.length, foodItemi.length &lt;= 20\n\tcustomerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.\n\ttableNumberi&nbsp;is a valid integer between 1 and 500.\n",589        "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 ",590        "solution_js": "var displayTable = function(orders) {\n    var mapOrders = {};\n    var tables = [];\n    var dishes = [];\n    for(var i=0;i<orders.length;i++){\n        //if entry of table doesn't exist in mapOrders\n        if(mapOrders[orders[i][1]] == undefined){\n            //conver table number to integer\n            var tableNo = Number(orders[i][1])\n            mapOrders[tableNo] = {}\n            mapOrders[tableNo][orders[i][2]] = 1;\n            //if table number doesn't exist in table array, push it in the table array\n            if(!tables.includes(tableNo)){tables.push(tableNo)}\n            //if dish doesn't exist in dishes array, push it in the dishes array\n            if(!dishes.includes(orders[i][2])){dishes.push(orders[i][2])}\n        }else{\n            //if entry of table exists in mapOrders\n            //conver table number to integer\n            var tableNo = Number(orders[i][1])\n            var entry = mapOrders[tableNo];\n            //check if entry of dish exists in for that table in mapOrders\n            if(entry[orders[i][2]] == undefined){\n                entry[orders[i][2]] = 1;\n            }else{\n                entry[orders[i][2]] = entry[orders[i][2]] + 1;\n            }\n            //if dish doesn't exist in dishes array, push it in the dishes array\n            if(!dishes.includes(orders[i][2])){dishes.push(orders[i][2])}\n        }\n    }\n    //sort tables and dishes\n    tables.sort(function(a,b){return a-b});\n    dishes.sort();\n    //append word \"Table\" with all dish names om row[0] of result\n    var res = [[\"Table\"]];\n    for(var i=0;i<dishes.length;i++){\n        res[0].push(dishes[i]);\n    }\n    // read through map based on sorted table order\n    for(var i=0;i<tables.length;i++){\n        // append result in a temp array\n        var tmp = [];\n        //converting number to string using \"\"+\n        tmp.push(\"\"+tables[i]);\n        for(var j=0;j<dishes.length;j++){\n            if(mapOrders[tables[i]][dishes[j]]==undefined){\n                //if dish doesn't exist against that table then append \"0\" to the result for that dish\n                tmp.push(\"\"+0);\n            }else{\n                //if dish exists against that table then append value in mapOrders for that pair of (table,dish) to the result\n                tmp.push(\"\"+mapOrders[tables[i]][dishes[j]]);\n            }\n        }\n        //append the temp array in result\n        res.push(tmp);\n    }\n    return res;\n};",591        "solution_java": "class Solution {\n    public List<List<String>> displayTable(List<List<String>> orders) {\n        List<List<String>> ans = new ArrayList<>();\n        List<String> head = new ArrayList<>();\n        head.add(\"Table\");\n        Map<Integer, Map<String,Integer>> map = new TreeMap<>();\n        for(List<String> 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<String, Integer> 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<Integer, Map<String, Integer>> entry: map.entrySet()){\n            List<String> l = new ArrayList<>();\n            l.add(entry.getKey() + \"\");\n            Map<String,Integer> m = entry.getValue();\n            for(int i=1; i<arr.length; i++){\n                if(m.containsKey(arr[i])){\n                    l.add(m.get(arr[i])+\"\");\n                }else{\n                    l.add(\"0\");\n                }\n            }\n            ans.add(l);\n        }\n        System.out.print(map);\n        return ans;\n    }\n}",592        "solution_c": "class Solution {\n\npublic:\n\n    vector<vector<string>> displayTable(vector<vector<string>>& orders) {\n\n\n\n    vector<vector<string>>ans;\n\n    map<int,map<string,int>>m;\n\n    set<string>s; //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    vector<string>dem;\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        vector<string>row;\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};"593    },594    {595        "title": "Brace Expansion II",596        "algo_input": "Under the grammar given below, strings can represent a set of lowercase words. Let&nbsp;R(expr)&nbsp;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 &gt;= 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= expression.length &lt;= 60\n\texpression[i] consists of '{', '}', ','or lowercase English letters.\n\tThe given&nbsp;expression&nbsp;represents a set of words based on the grammar given in the description.\n\n",597        "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()) ",598        "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}",599        "solution_java": "class Solution {\n    // To Get the value of index traversed in a recursive call.\n    int index = 0;\n\n    public List<String> braceExpansionII(String expression) {\n        List<String> result = util(0, expression);\n        Set<String> set = new TreeSet<>();\n        set.addAll(result);\n        return new ArrayList<>(set);\n    }\n\n    List<String> util(int startIndex, String expression) {\n        // This represents processed List in the current recursion.\n        List<String> 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<String> 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<String> 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<String> 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 <String> 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<String> 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<String> 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}",600        "solution_c": "class Solution {\npublic:\n    vector<string> 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        stack<char>stk1;\n        vector<string>postfix;\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<vector<string>>cont;\n        for(string s:postfix){\n            if(isalpha(s[0])){\n                cont.push({s});\n            } else {\n                vector<string>second = cont.top();\n                cont.pop();\n                vector<string>first = 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                    vector<string>cartesian;\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        set<string>sstr;\n        for(string sc:cont.top()){\n            sstr.insert(sc);\n        }\n        \n        vector<string>ret(sstr.begin(), sstr.end());\n        return ret;\n    }\n};```"601    },602    {603        "title": "Rotate String",604        "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&nbsp;\nExample 1:\nInput: s = \"abcde\", goal = \"cdeab\"\nOutput: true\nExample 2:\nInput: s = \"abcde\", goal = \"abced\"\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length, goal.length &lt;= 100\n\ts and goal consist of lowercase English letters.\n\n",605        "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",606        "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};",607        "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}",608        "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};"609    },610    {611        "title": "Maximum Path Quality of a Graph",612        "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&nbsp;\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 -&gt; 1 -&gt; 0 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 + 10 + 10 = 40 &lt;= 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 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 = 20 &lt;= 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 -&gt; 1 -&gt; 3 -&gt; 1 -&gt; 0. The total time taken is 10 + 13 + 13 + 10 = 46 &lt;= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == values.length\n\t1 &lt;= n &lt;= 1000\n\t0 &lt;= values[i] &lt;= 108\n\t0 &lt;= edges.length &lt;= 2000\n\tedges[j].length == 3 \n\t0 &lt;= uj &lt; vj &lt;= n - 1\n\t10 &lt;= timej, maxTime &lt;= 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",613        "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",614        "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};",615        "solution_java": "class Solution {\n    public int maximalPathQuality(int[] values, int[][] edges, int maxTime) {\n        int n = values.length;\n        List<int[]>[] 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<int[]>[] 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}",616        "solution_c": "class Solution {\npublic:\n    int maximalPathQuality(vector<int>& values, vector<vector<int>>& edges, int maxTime) {\n        int n = values.size();\n        int res = values[0];\n        vector<vector<pair<int,int>>> graph(n);\n        for(int i=0;i<edges.size();i++)\n        {\n            graph[edges[i][0]].push_back({edges[i][1], edges[i][2]});\n            graph[edges[i][1]].push_back({edges[i][0], edges[i][2]});\n        }\n        \n        vector<int> visited(n, 0);\n        dfs(graph, values, visited, res, 0, 0, 0, maxTime);\n        return res;\n    }\n    \n    void dfs(vector<vector<pair<int,int>>>& graph, vector<int>& values, vector<int>& 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 &nbsp; &nbsp; &nbsp; &nbsp;visited[node]++;\n\t\t\n &nbsp; &nbsp; &nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp;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};"617    },618    {619        "title": "My Calendar III",620        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t0 &lt;= start &lt; end &lt;= 109\n\tAt most 400 calls will be made to book.\n\n",621        "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",622        "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};",623        "solution_java": "class MyCalendarThree {\n\n    TreeMap<Integer, Integer> 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<Integer, Integer> e: map.entrySet()){\n            sum += e.getValue();\n            res = Math.max(res,sum);\n        }\n\n        return res;\n    }\n}",624        "solution_c": "class MyCalendarThree {\npublic:\n    map<int,int>mp;\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};"625    },626    {627        "title": "Minimum Operations to Make a Uni-Value Grid",628        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 105\n\t1 &lt;= m * n &lt;= 105\n\t1 &lt;= x, grid[i][j] &lt;= 104\n\n",629        "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                ",630        "solution_js": "var minOperations = function(grid, x) {\n    \n    let remainder = -Infinity, flatten = [], res = 0;\n    \n    for(let i = 0;i<grid.length;i++){\n        for(let j = 0;j<grid[i].length;j++){\n            \n            if(remainder === -Infinity)\n                remainder = grid[i][j] % x;\n            else if(remainder !== grid[i][j] % x){\n                return -1;\n            }\n            flatten.push(grid[i][j])\n        }\n    }\n    flatten.sort((a,b)=> a-b);\n    let median = flatten[~~(flatten.length/2)] \n\n    for(let i = 0;i<flatten.length;i++){\n        res += Math.abs(flatten[i] - median) / x\n    }\n    return res;\n};",631        "solution_java": "class Solution {\n    public int minOperations(int[][] grid, int x) {\n        int[] arr = new int[grid.length * grid[0].length];\n        int index = 0;\n        \n        for (int i = 0; i < grid.length; i++) {\n            for (int j = 0; j < grid[0].length; j++) {\n                arr[index++] = grid[i][j];\n            }\n        }\n        \n        Arrays.sort(arr);\n        int median = arr[(arr.length - 1) / 2];\n        int steps = 0;\n        \n        for (int num : arr) {\n            if (num == median) {\n                continue;\n            }\n            \n            if (Math.abs(num - median) % x != 0) {\n                return -1;\n            }\n            \n            steps += (Math.abs(num - median) / x);\n        }\n        \n        return steps;\n    }\n}",632        "solution_c": "class Solution {\npublic:\n    int minOperations(vector<vector<int>>& grid, int x) {\n        vector<int>nums;\n        int m=grid.size(),n=grid[0].size();\n        for(int i=0;i<m;i++)\n            for(int j=0;j<n;j++)\n                nums.push_back(grid[i][j]);\n        sort(nums.begin(),nums.end());\n        int target=nums[m*n/2],ans=0;\n        for(int i=m*n-1;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};"633    },634    {635        "title": "Maximum Difference Between Node and Ancestor",636        "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&nbsp;or any child of a is an ancestor of b.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [2, 5000].\n\t0 &lt;= Node.val &lt;= 105\n\n",637        "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",638        "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};",639        "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}",640        "solution_c": "class Solution {\nprivate:\n    int maxDiff;\n    pair <int, int> helper(TreeNode* root) {\n        if (root == NULL) return {INT_MAX, INT_MIN};\n        pair <int, int> L = helper(root -> left), R = helper(root -> right);\n        pair <int, int> 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};"641    },642    {643        "title": "Minesweeper",644        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == board.length\n\tn == board[i].length\n\t1 &lt;= m, n &lt;= 50\n\tboard[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'.\n\tclick.length == 2\n\t0 &lt;= clickr &lt; m\n\t0 &lt;= clickc &lt; n\n\tboard[clickr][clickc] is either 'M' or 'E'.\n\n",645        "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<len(board) and 0<=b<len(board[0])\n\n\n        ",646        "solution_js": "var updateBoard = function(board, click) {\n\tconst [clickR, clickC] = click;\n\tconst traverseAround = ({ currentRow, currentCol, fun }) => {\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};",647        "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}",648        "solution_c": "class Solution {\npublic:\n    int m, n ;\n    vector<vector<char>> updateBoard(vector<vector<char>>& board, vector<int>& 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<vector<char>> &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};"649    },650    {651        "title": "Merge BSTs to Create Single BST",652        "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&nbsp;strictly less&nbsp;than the node's value.\n\tEvery node in the node's right subtree has a value&nbsp;strictly greater&nbsp;than the node's value.\n\n\nA leaf is a node that has no children.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == trees.length\n\t1 &lt;= n &lt;= 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 &lt;= TreeNode.val &lt;= 5 * 104.\n\n",653        "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",654        "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.val<l || node.val >r)\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};",655        "solution_java": "class Solution {\n    public TreeNode canMerge(List<TreeNode> trees) {\n        //Map root value to tree\n        HashMap<Integer, TreeNode> 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<Integer, TreeNode> 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}",656        "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<TreeNode*>& trees) {\n        //store the leaves of every node\n\n        unordered_map<int,TreeNode*> mp;\n        \n        //store the current min and current max nodes in the current tree\n        unordered_map<TreeNode*,pair<int,int>> mini;\n        for(int i=0;i<trees.size();i++)\n        {\n            pair<int,int> 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;i<trees.size();i++)\n        {\n            \n            //if the current tree can be merged into some other tree\n            if(mp.find(trees[i]->val)!=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};"657    },658    {659        "title": "Watering Plants",660        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == plants.length\n\t1 &lt;= n &lt;= 1000\n\t1 &lt;= plants[i] &lt;= 106\n\tmax(plants[i]) &lt;= capacity &lt;= 109\n\n",661        "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",662        "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};",663        "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.length;i++){\n            if(c>=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}",664        "solution_c": "class Solution {\npublic:\n\tint wateringPlants(vector<int>& 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};"665    },666    {667        "title": "Partition Array According to Given Pivot",668        "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 &lt; j and nums[i] &lt; pivot and nums[j] &lt; pivot, then pi &lt; pj. Similarly for elements greater than pivot, if i &lt; j and nums[i] &gt; pivot and nums[j] &gt; pivot, then pi &lt; pj.\n\t\n\t\n\n\nReturn nums after the rearrangement.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-106 &lt;= nums[i] &lt;= 106\n\tpivot equals to an element of nums.\n\n",669        "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(i<pivot):\n                left.append(i)\n            elif(i==pivot):\n                mid.append(i)\n            else:\n                right.append(i)\n        return left+mid+right",670        "solution_js": "/**\n * @param {number[]} nums\n * @param {number} pivot\n * @return {number[]}\n */\nvar pivotArray = function(nums, pivot) {\n\n    let n=nums.length;\n\n    //first Solution with 3 separet Array\n    let lessPivot=[]\n    let equalPivot=[]\n    let bigerPivot=[]\n\n    for(let i=0;i<n;i++){\n        if(nums[i]<pivot)lessPivot.push(nums[i])\n        else if(nums[i]===pivot)equalPivot.push(nums[i])\n        else bigerPivot.push(nums[i])\n\n    }\n    return lessPivot.concat(equalPivot.concat(bigerPivot))\n\n    //second Solution with one Array\n\n    let result=[]\n    for(let num of nums){\n        if(num<pivot)result.push(num)\n    }\n\n    for(let num of nums){\n        if(num===pivot)result.push(num)\n    }\n    for(let num of nums){\n        if(num>pivot)result.push(num)\n    }\n    return result\n};",671        "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}",672        "solution_c": "class Solution {\npublic:\n    vector<int> pivotArray(vector<int>& nums, int pivot) {\n        int i = 0;\n        vector<int> 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};"673    },674    {675        "title": "Check if Numbers Are Ascending in a Sentence",676        "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&nbsp;\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 &lt; 3 &lt; 4 &lt; 6 &lt; 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&nbsp;\nConstraints:\n\n\n\t3 &lt;= s.length &lt;= 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",677        "solution_py": "class Solution:\n    def areNumbersAscending(self, s):\n        nums = re.findall(r'\\d+', s)\n        return nums == sorted(set(nums), key=int)",678        "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};",679        "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}",680        "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};"681    },682    {683        "title": "Decode XORed Array",684        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 104\n\tencoded.length == n - 1\n\t0 &lt;= encoded[i] &lt;= 105\n\t0 &lt;= first &lt;= 105\n\n",685        "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]",686        "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};",687        "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}",688        "solution_c": "class Solution {\npublic:\n    vector<int> decode(vector<int>& encoded, int first) {\n        vector<int> ans{first};\n        for(int x: encoded)\n            ans.push_back(first^=x);\n        return ans;\n    }\n};"689    },690    {691        "title": "Minimum Changes To Make Alternating Binary String",692        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 104\n\ts[i] is either '0' or '1'.\n\n",693        "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)",694        "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<s.length;i++){\n        if(i%2===0){\n            if(s[i]===\"0\"){\n                counter1++;\n            }\n            if(s[i]===\"1\"){\n                counter2++;\n            }\n        }\n        if(i%2===1){\n            if(s[i]===\"1\"){\n                counter1++;\n            }\n            if(s[i]===\"0\"){\n                counter2++;\n            }\n        }\n    }\n    return Math.min(counter1,counter2);\n};",695        "solution_java": "class Solution {\n    public int minOperations(String s) {\n        int count0 = 0; // changes required when the string starts from 0\n        int count1 = 0; // changes required when the string starts from 1\n\n        for(int i = 0; i < s.length(); i++){\n\n            // string starts with 1 => 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}",696        "solution_c": "class Solution {\npublic:\n    int minOperations(string s) {\n        int n=s.size(), ans=0;\n        for(int i=0;i<n;i++)\n        {\n            if(s[i]-'0' != i%2)\n            ans++;\n        }\n        return min(ans, n-ans);\n    }\n};"697    },698    {699        "title": "Positions of Large Groups",700        "algo_input": "In a string s&nbsp;of lowercase letters, these letters form consecutive groups of the same character.\n\nFor example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and&nbsp;\"yy\".\n\nA group is identified by an interval&nbsp;[start, end], where&nbsp;start&nbsp;and&nbsp;end&nbsp;denote the start and end&nbsp;indices (inclusive) of the group. In the above example,&nbsp;\"xxxx\"&nbsp;has the interval&nbsp;[3,6].\n\nA group is considered&nbsp;large&nbsp;if it has 3 or more characters.\n\nReturn&nbsp;the intervals of every large group sorted in&nbsp;increasing order by start index.\n\n&nbsp;\nExample 1:\n\nInput: s = \"abbxxxxzzy\"\nOutput: [[3,6]]\nExplanation: \"xxxx\" is the only large group with start index 3 and end index 6.\n\n\nExample 2:\n\nInput: s = \"abc\"\nOutput: []\nExplanation: We have groups \"a\", \"b\", and \"c\", none of which are large groups.\n\n\nExample 3:\n\nInput: s = \"abcdddeeeeaabbbcd\"\nOutput: [[3,5],[6,9],[12,14]]\nExplanation: The large groups are \"ddd\", \"eeee\", and \"bbb\".\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 1000\n\ts contains lowercase English letters only.\n\n",701        "solution_py": "class Solution:\n    def largeGroupPositions(self, s: str) -> List[List[int]]:\n\n        i=0\n        c=1\n        prev=\"\"\n        l=len(s)\n        ans=[]\n        while i<l:\n            if s[i]==prev:\n                c+=1\n                if (i==l-1) & (c>=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",702        "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};",703        "solution_java": "class Solution {\n    public List<List<Integer>> largeGroupPositions(String s) {\n        List<List<Integer>> res = new ArrayList<>();\n        List<Integer> 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}",704        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> largeGroupPositions(string s) {\n        vector<vector<int>> 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};"705    },706    {707        "title": "Three Divisors",708        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 104\n\n",709        "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",710        "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};",711        "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<n;i++){\n            if(res%i ==0) return false;\n        }\n        return true;\n}}",712        "solution_c": "class Solution {\npublic:\n    bool isPrime(int n) {\n        for (int i = 2; i <= sqrt(n); i++) if (n % i == 0) return false;\n        return true;\n    }\n\n    bool isThree(int n) {\n        return n != 1 && n != 2 && (int)sqrt(n)*sqrt(n) == n && isPrime(sqrt(n));\n    }\n};"713    },714    {715        "title": "Best Position for a Service Centre",716        "algo_input": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.\n\nGiven an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.\n\nIn other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:\n\nAnswers within 10-5 of the actual value will be accepted.\n\n&nbsp;\nExample 1:\n\nInput: positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput: 4.00000\nExplanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n\n\nExample 2:\n\nInput: positions = [[1,1],[3,3]]\nOutput: 2.82843\nExplanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= positions.length &lt;= 50\n\tpositions[i].length == 2\n\t0 &lt;= xi, yi &lt;= 100\n\n",717        "solution_py": "class Solution:\n    def getMinDistSum(self, positions: List[List[int]]) -> 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)",718        "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};",719        "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}",720        "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<vector<int>>& 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<vector<int>>& 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<double, double> 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<double, double> 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};"721    },722    {723        "title": "Combination Sum IV",724        "algo_input": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to&nbsp;target.\n\nThe test cases are generated so that the answer can fit in a 32-bit integer.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 200\n\t1 &lt;= nums[i] &lt;= 1000\n\tAll the elements of nums are unique.\n\t1 &lt;= target &lt;= 1000\n\n\n&nbsp;\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",725        "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]",726        "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};",727        "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}",728        "solution_c": "class Solution {\npublic:\n    int combinationSum4(vector<int>& nums, int target) {\n        vector<unsigned int> 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};"729    },730    {731        "title": "Self Crossing",732        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;distance.length &lt;= 105\n\t1 &lt;=&nbsp;distance[i] &lt;= 105\n\n",733        "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        ",734        "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}",735        "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}",736        "solution_c": "class Solution {\npublic:\n    bool isSelfCrossing(vector<int>& 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};"737    },738    {739        "title": "Kth Ancestor of a Tree Node",740        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= k &lt;= n &lt;= 5 * 104\n\tparent.length == n\n\tparent[0] == -1\n\t0 &lt;= parent[i] &lt; n for all 0 &lt; i &lt; n\n\t0 &lt;= node &lt; n\n\tThere will be at most 5 * 104 queries.\n\n",741        "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",742        "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};",743        "solution_java": "class TreeAncestor {\n    int n;\n    int[] parent;\n    List<Integer>[] 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<Integer> 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<Integer> path = nodeInPath[node];\n        int idx = nodeIdxInPath[node] + k;\n        return idx >= path.size() ? -1 : path.get(idx);\n    }\n}",744        "solution_c": "class TreeAncestor {\npublic:\n    //go up by only powers of two\n    vector<vector<int>> lift ;\n    TreeAncestor(int n, vector<int>& parent) {\n        lift.resize(n,vector<int>(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};"745    },746    {747        "title": "Magic Squares In Grid",748        "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&nbsp;grid&nbsp;of integers, how many 3 x 3 \"magic square\" subgrids are there?&nbsp; (Each subgrid is contiguous).\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\trow == grid.length\n\tcol == grid[i].length\n\t1 &lt;= row, col &lt;= 10\n\t0 &lt;= grid[i][j] &lt;= 15\n\n",749        "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",750        "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};",751        "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;i<n-2;i++)\n\t\t{\n\t\t\tfor(int j=0;j<m-2;j++)\n\t\t\t{\n\t\t\t\tif(sum(i,j,grid))\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n\tpublic boolean sum(int x,int y,int[][] grid)\n\t{\n\t\tint sum=grid[x][y]+grid[x][y+1]+grid[x][y+2],sum1=0,sum2=0;\n\t\tint []count=new int[10];\n\t\tfor(int i=0;i<3;i++)\n\t\t{\n\t\t\tsum1=0;\n\t\t\tsum2=0;   \n\t\t\tfor(int j=0;j<3;j++)\n\t\t\t{\n\t\t\t\tsum1+=grid[x+i][y+j];\n\t\t\t\tsum2+=grid[x+j][y+i];\n\t\t\t\tif(grid[x+i][y+j]<1 ||grid[x+i][y+j]>9 ||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}",752        "solution_c": "class Solution {\npublic:\n    int numMagicSquaresInside(vector<vector<int>>& 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<vector<int>>& 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<int> 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};"753    },754    {755        "title": "Maximum Nesting Depth of the Parentheses",756        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 100\n\ts consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.\n\tIt is guaranteed that parentheses expression s is a VPS.\n\n",757        "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 ",758        "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};",759        "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}",760        "solution_c": "class Solution {\npublic:\n    int maxDepth(string s) {\n        int maxi=0,curr=0;\n        for(int i=0;i<s.size();i++){\n            if(s[i]=='('){\n                maxi=max(maxi,++curr);\n            }else if(s[i]==')'){\n                curr--;\n            }\n        }\n        return maxi;\n    }\n};"761    },762    {763        "title": "Find All People With Secret",764        "algo_input": "You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson.\n\nPerson 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa.\n\nThe secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.\n\nReturn a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.\n\n&nbsp;\nExample 1:\n\nInput: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\nOutput: [0,1,2,3,5]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.โ€‹โ€‹โ€‹โ€‹\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.\n\n\nExample 2:\n\nInput: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\nOutput: [0,1,3]\nExplanation:\nAt time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.\n\n\nExample 3:\n\nInput: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\nOutput: [0,1,2,3,4]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.\n\n\n&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 105\n\t1 &lt;= meetings.length &lt;= 105\n\tmeetings[i].length == 3\n\t0 &lt;= xi, yi &lt;= n - 1\n\txi != yi\n\t1 &lt;= timei &lt;= 105\n\t1 &lt;= firstPerson &lt;= n - 1\n\n",765        "solution_py": "class Solution:\n    def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> 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)",766        "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}",767        "solution_java": "class Solution {\n    public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) {\n\t\n\t\t// create <time, index> map\n        Map<Integer, List<Integer>> 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<Integer> 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<Integer> 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}",768        "solution_c": "class Solution {\npublic:\n    vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) {\n        vector<int> res;\n        set<int> ust;\n        ust.insert(0);\n        ust.insert(firstPerson);\n        map<int,vector<pair<int,int>>> 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};"769    },770    {771        "title": "Longest Common Subsequence",772        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= text1.length, text2.length &lt;= 1000\n\ttext1 and text2 consist of only lowercase English characters.\n\n",773        "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",774        "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};",775        "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}",776        "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};"777    },778    {779        "title": "Decode the Slanted Ciphertext",780        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t0 &lt;= encodedText.length &lt;= 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 &lt;= rows &lt;= 1000\n\tThe testcases are generated such that there is only one possible originalText.\n\n",781        "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()",782        "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}",783        "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<cols;i++) {\n        \n            //iterating diagonally!!\n            for(int j=i;j<str.length();j+=cols+1)\n    \t\t\tres.append(str.charAt(j));\n    \t}\n        \n        //removing last spaces!!!\n        int fg=0;\n        for(int i=res.length()-1;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}",784        "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<vector<char>> mat(rows, vector<char>(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};"785    },786    {787        "title": "Reorganize String",788        "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&nbsp;\nExample 1:\nInput: s = \"aab\"\nOutput: \"aba\"\nExample 2:\nInput: s = \"aaab\"\nOutput: \"\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of lowercase English letters.\n\n",789        "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",790        "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};",791        "solution_java": "class Solution {\n    public String reorganizeString(String s) {\n        StringBuilder ans=new StringBuilder(\"\");\n        char[] charArray=new char[s.length()];\n        Map<Character,Integer> hashMap=new HashMap<>();\n        Queue<CharOccurence> queue=new PriorityQueue<>((a,b)->b.occurence-a.occurence);\n\n        charArray=s.toCharArray();\n\n        for(int i=0;i<charArray.length;i++)\n        {\n            Integer occurence=hashMap.get(charArray[i]);\n            if(occurence==null)\n                hashMap.put(charArray[i],1);\n            else\n                hashMap.put(charArray[i],occurence+1);\n        }\n        queue.addAll(hashMap.entrySet()\n                     .stream()\n                     .parallel()\n                     .map(e->new CharOccurence(e.getKey(),e.getValue()))\n                     .collect(Collectors.toList()));\n        while(!queue.isEmpty())\n        {\n            Queue<CharOccurence> 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;i<sizeQueue;i++)\n            {\n                CharOccurence letter=queue.poll();\n                if(!lastLetter.contains(String.valueOf(letter.letter)))\n                {\n                    letter.occurence--;\n                    ans.append(String.valueOf(letter.letter));\n                    if(letter.occurence>0)\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}",792        "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<char, int> 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<pair<int, char>> 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};"793    },794    {795        "title": "Remove Colored Pieces if Both Neighbors are the Same Color",796        "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&nbsp;\nExample 1:\n\nInput: colors = \"AAABABB\"\nOutput: true\nExplanation:\nAAABABB -&gt; 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 -&gt; ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -&gt; 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&nbsp;\nConstraints:\n\n\n\t1 &lt;=&nbsp;colors.length &lt;= 105\n\tcolors&nbsp;consists of only the letters&nbsp;'A'&nbsp;and&nbsp;'B'\n\n",797        "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",798        "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};",799        "solution_java": "class Solution {\n    public boolean winnerOfGame(String colors) {\n        int cntA=0,cntB=0;\n        for(int i=1;i<colors.length()-1;i++){\n             if(colors.charAt(i)=='A'&&colors.charAt(i-1)=='A'&&colors.charAt(i+1)=='A')cntA++;\n            if(colors.charAt(i)=='B'&&colors.charAt(i-1)=='B'&&colors.charAt(i+1)=='B')cntB++;\n        }\n\n        return cntA>cntB;\n    }\n}",800        "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};"801    },802    {803        "title": "Remove Linked List Elements",804        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the list is in the range [0, 104].\n\t1 &lt;= Node.val &lt;= 50\n\t0 &lt;= val &lt;= 50\n\n",805        "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",806        "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};",807        "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}",808        "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};"809    },810    {811        "title": "Prison Cells After N Days",812        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tcells.length == 8\n\tcells[i]&nbsp;is either 0 or 1.\n\t1 &lt;= n &lt;= 109\n\n",813        "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",814        "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 ",815        "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 <cells.length- 1; i++)\n            {\n              temp[i] = cells[i-1] == cells[i+1]? 1: 0;\n            }\n            cells = temp.clone();\n        }\n\n        return cells;\n    }\n}",816        "solution_c": "class Solution {\npublic:\n    vector<int> prisonAfterNDays(vector<int>& 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;i<cells.size();i++){\n            if(cells[i]){\n                state^=(1<<(7-i));\n            }\n        }\n        //this array stores the various states encountered\n        vector<int>seen;\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<<pos);\n                }\n            }\n            //if the next state is equal to the initial state, this means that we have\n            //found the cycle. Let the length of the cycle be l=seen.size(). Therefore \n            //in the remaining n days, n/l of those will have no effect on the \n            //prison configuration. This means we can return the configuration of the \n            //n%l day.\n            if(seen.size() and seen[0]==next){\n                int cnt=seen.size();\n                state=seen[n%cnt];\n                break;\n            } else {\n                seen.push_back(next);\n                state=next;\n            }\n        }\n        //translating the prison state from the bitmask to an array.\n        vector<int>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};"817    },818    {819        "title": "Pizza With 3n Slices",820        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t3 * n == slices.length\n\t1 &lt;= slices.length &lt;= 500\n\t1 &lt;= slices[i] &lt;= 1000\n\n",821        "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)",822        "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};",823        "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}",824        "solution_c": "class Solution {\npublic:\n    \n    int dp[501][501];\n    \n    int solve(vector<int>&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<int>& slices) { \n        \n     vector<int>v1 ;\n     vector<int>v2 ;\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};"825    },826    {827        "title": "Max Area of Island",828        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 50\n\tgrid[i][j] is either 0 or 1.\n\n",829        "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",830        "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};",831        "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<String,List<int[]>> adj=new HashMap<>();\n      boolean[][] visited=new boolean[rows][cols];\n      Queue<String> queue=new LinkedList<>();\n      int res=0;\n\n      for(int i=0;i<grid.length;i++)\n      {\n        for(int j=0;j<grid[i].length;j++)\n        {\n\n          List<int[]> 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<rows;i++)\n      {\n        for(int j=0;j<cols;j++)\n        {\n          int count=0;\n          if(visited[i][j])\n            continue;\n          queue.add(getNodeStringFormat(i,j,grid[i][j]));\n          while(!queue.isEmpty())\n          {\n            String currentStr=queue.poll();\n            String[] current=currentStr.split(\",\");\n\n            int row=Integer.valueOf(current[0]);\n            int col=Integer.valueOf(current[1]);\n            int isLand=Integer.valueOf(current[2]);\n            if(!adj.containsKey(currentStr))\n                continue;\n            if(visited[row][col])\n                continue;\n            if(isLand==1)\n                count++;\n            visited[row][col]=true;\n            for(int[] item:adj.get(currentStr))\n            {\n              int newRow=item[0];\n              int newCol=item[1];\n              int newIsLand=item[2];\n              if(!visited[newRow][newCol] && newIsLand==1 && isLand==1)\n                  queue.add(getNodeStringFormat(newRow,newCol,newIsLand));\n            }\n          }\n          res=Math.max(res,count);\n        }\n      }\n\n      return res;\n\n    }\n  private String getNodeStringFormat(int row,int col,int isLand)\n  {\n      StringBuilder sb=new StringBuilder();\n      sb.append(row);\n      sb.append(\",\");\n      sb.append(col);\n      sb.append(\",\");\n      sb.append(isLand);\n    return sb.toString();\n  }\n}",832        "solution_c": "class Solution {\npublic:\n    int cal(vector<vector<int>>& 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<vector<int>>& grid) {\n        int m=grid.size(),n=grid[0].size(),maxArea=0;\n        for(int i=0;i<m;i++){\n            for(int j=0;j<n;j++){\n                if(grid[i][j]==1){\n                    int area=0;\n                    area=cal(grid,i,j,m,n);\n                    maxArea=max(maxArea,area);\n                }\n            }\n        }\n        return maxArea;\n    }\n};"833    },834    {835        "title": "Find First Palindromic String in the Array",836        "algo_input": "Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string \"\".\n\nA string is palindromic if it reads the same forward and backward.\n\n&nbsp;\nExample 1:\n\nInput: words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]\nOutput: \"ada\"\nExplanation: The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.\n\n\nExample 2:\n\nInput: words = [\"notapalindrome\",\"racecar\"]\nOutput: \"racecar\"\nExplanation: The first and only string that is palindromic is \"racecar\".\n\n\nExample 3:\n\nInput: words = [\"def\",\"ghi\"]\nOutput: \"\"\nExplanation: There are no palindromic strings, so the empty string is returned.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= words.length &lt;= 100\n\t1 &lt;= words[i].length &lt;= 100\n\twords[i] consists only of lowercase English letters.\n\n",837        "solution_py": "class Solution:\n    def firstPalindrome(self, words):\n        for word in words:\n            if word == word[::-1]: return word\n        return \"\"",838        "solution_js": "var firstPalindrome = function(words) {\n    for (const word of words) {\n        if (word === word.split('').reverse().join('')) return word;\n    }\n    \n    return '';\n};",839        "solution_java": "class Solution {\n    public String firstPalindrome(String[] words) {\n        for (String s : words) {\n            StringBuilder sb = new StringBuilder(s);\n            if (s.equals(sb.reverse().toString())) {\n                return s;\n            }\n        }\n        return \"\";\n    }\n}",840        "solution_c": "class Solution {\n    bool isPalindrome(string str){\n        int i=0 ;\n        int j=str.length()-1;\n        while( i<= j ){\n            if( str[i] != str[j] )\n                return false;\n            i++;\n            j--;\n        }\n        return true;\n    }\npublic:\n    string firstPalindrome(vector<string>& words) {\n\n        for(int i=0 ; i<words.size() ; i++){\n            if(isPalindrome(words[i]))\n                return words[i];\n        }\n        return \"\";\n    }\n};"841    },842    {843        "title": "Array Nesting",844        "algo_input": "You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].\n\nYou should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:\n\n\n\tThe first element in s[k] starts with the selection of the element nums[k] of index = k.\n\tThe next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.\n\tWe stop adding right before a duplicate element occurs in s[k].\n\n\nReturn the longest length of a set s[k].\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,4,0,3,1,6,2]\nOutput: 4\nExplanation: \nnums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\n\n\nExample 2:\n\nInput: nums = [0,1,2]\nOutput: 1\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t0 &lt;= nums[i] &lt; nums.length\n\tAll the values of nums are unique.\n\n",845        "solution_py": "class Solution:\n    def arrayNesting(self, nums: List[int]) -> 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",846        "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};",847        "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.length;i++){\n            if(!visited[i]){\n                int len = dfs(nums,i,visited);\n                res = Math.max(res,len);\n            }\n        }\n        return res;\n    }\n    public int dfs(int[] nums,int i,boolean[] visited){\n        if(visited[i]) return 0;\n        visited[i] = true;\n        return 1+dfs(nums,nums[i],visited);\n    }\n}",848        "solution_c": "class Solution {\npublic:\n    int dfs(vector<int>&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<int>& nums) {\n        \n        int arr[nums.size()],ans=0;\n        for(int i=0;i<nums.size();i++)\n            arr[i]=0;\n        for(int i=0;i<nums.size();i++)\n        {\n            int res=dfs(nums,i,arr,0);\n            ans=max(res,ans);\n        }\n        return ans;\n    }\n};"849    },850    {851        "title": "Consecutive Numbers Sum",852        "algo_input": "Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.\n\n&nbsp;\nExample 1:\n\nInput: n = 5\nOutput: 2\nExplanation: 5 = 2 + 3\n\n\nExample 2:\n\nInput: n = 9\nOutput: 3\nExplanation: 9 = 4 + 5 = 2 + 3 + 4\n\n\nExample 3:\n\nInput: n = 15\nOutput: 4\nExplanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 109\n\n",853        "solution_py": "# For every odd divisor d of n, there's exactly one sum of length d, e.g.\n#\n#     21 = 3 * 7 = 6 + 7 + 8.\n#\n# Also, every odd length sum is of this form, since the middle value is average,\n# and the sum is just (number of elements) * (average) = d * n/d.\n#\n# For even length sums, the average is a half-integer\n#\n#     2 + 3 + 4 + 5 = 4 * 3.5\n#\n# So n can be written as\n#\n#     n = (even length) * (half-integer average)\n#       = (2 * c) * (d / 2)\n#       = c * d\n#\n# for some arbitrary integer c and odd integer d. So again, any odd d divisor of\n# n produces an even length sum, and every even length sum is of this form.\n#\n# However, we need to ensure that the sum only contains positive integers.\n#\n# For the first case, the smallest number is n/d - (d-1)/2. For the second case,\n# it's (d+1)/2 - n/d.\n#\n# For all d, exactly one of these is positive, and so every odd divisor\n# corresponds to exactly one sum, and all sums are of this form.\n#\n# Therefore, we need to count the odd divisors.\n#\n# There's no way I know of doing this without essentially factoring the number.\n# So say\n#\n#     n = 2**n0 * p1**n1 * p2**n2 * ... * pk**nk\n#\n# is the prime decomposition (all p are odd). Then n has\n#\n#     (n1+1) * (n2+1) * ... * (nk+1)\n#\n# odd divisors.\n#\n# For the implementation, we search the smallest divisor, which is neccessarily\n# prime and divide by it as often as possible (and count the divisions). If\n# after that p**2 > 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",854        "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};",855        "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}",856        "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};"857    },858    {859        "title": "Maximum Erasure Value",860        "algo_input": "You are given an array of positive integers nums and want to erase a subarray containing&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= nums[i] &lt;= 104\n\n",861        "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",862        "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};",863        "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}",864        "solution_c": "class Solution {\npublic:\n    int maximumUniqueSubarray(vector<int>& nums) {\n        int curr_sum=0, res=0;\n\n        //set to store the elements\n        unordered_set<int> st;\n\n        int i=0,j=0;\n        while(j<nums.size()) {\n            while(st.count(nums[j])>0) {\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};"865    },866    {867        "title": "HTML Entity Parser",868        "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 &amp;quot; and symbol character is \".\n\tSingle Quote Mark: the entity is &amp;apos; and symbol character is '.\n\tAmpersand: the entity is &amp;amp; and symbol character is &amp;.\n\tGreater Than Sign: the entity is &amp;gt; and symbol character is &gt;.\n\tLess Than Sign: the entity is &amp;lt; and symbol character is &lt;.\n\tSlash: the entity is &amp;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&nbsp;\nExample 1:\n\nInput: text = \"&amp;amp; is an HTML entity but &amp;ambassador; is not.\"\nOutput: \"&amp; is an HTML entity but &amp;ambassador; is not.\"\nExplanation: The parser will replace the &amp;amp; entity by &amp;\n\n\nExample 2:\n\nInput: text = \"and I quote: &amp;quot;...&amp;quot;\"\nOutput: \"and I quote: \\\"...\\\"\"\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= text.length &lt;= 105\n\tThe string may contain any possible characters out of all the 256 ASCII characters.\n\n",869        "solution_py": "class Solution:\n    def entityParser(self, text: str) -> str:\n        d = {\"&quot;\" : '\"' , \"&apos;\":\"'\" , \"&amp;\" : \"&\" , \"&gt;\" : \">\" , \"&lt;\":\"<\" , \"&frasl;\" : \"/\"}\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        ",870        "solution_js": "/**\n * @param {string} text\n * @return {string}\n */\nvar entityParser = function(text) {\n    const entityMap = {\n        '&quot;': `\"`,\n        '&apos;': `'`,\n        '&amp;': `&`,\n        '&gt;': `>`,\n        '&lt;': `<`,\n        '&frasl;': `/`\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};",871        "solution_java": "class Solution {\n    public String entityParser(String text) {\n        return text.replace(\"&quot;\",\"\\\"\").replace(\"&apos;\",\"'\").replace(\"&gt;\",\">\").replace(\"&lt;\",\"<\").replace(\"&frasl;\",\"/\").replace(\"&amp;\",\"&\");\n    }\n}",872        "solution_c": "class Solution {\npublic:\n    string entityParser(string text) {\n        map<string,char>mp;\n        mp[\"&quot;\"] = '\\\"';\n        mp[\"&apos;\"] = '\\'';\n        mp[\"&amp;\"] = '&';\n        mp[\"&gt;\"] = '>';mp[\"&lt;\"]='<';\n        mp[\"&frasl;\"] = '/';\n        \n        for(int i =0;i<text.size();i++){\n            if(text[i]=='&'){\n                int j = i;\n                string com =\"\";\n                while(text[j]!=';' && j<text.size()){\n                    com+=text[j];\n                    j++;\n                }\n                com+=text[j];\n                if(mp.find(com)!=mp.end()){\n                    text.erase(i,j-i);\n                    text[i] = mp[com];\n                }\n                \n            }\n        }\n        return text;\n    }\n};"873    },874    {875        "title": "Check If a Word Occurs As a Prefix of Any Word in a Sentence",876        "algo_input": "Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.\n\nReturn the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.\n\nA prefix of a string s is any leading contiguous substring of s.\n\n&nbsp;\nExample 1:\n\nInput: sentence = \"i love eating burger\", searchWord = \"burg\"\nOutput: 4\nExplanation: \"burg\" is prefix of \"burger\" which is the 4th word in the sentence.\n\n\nExample 2:\n\nInput: sentence = \"this problem is an easy problem\", searchWord = \"pro\"\nOutput: 2\nExplanation: \"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.\n\n\nExample 3:\n\nInput: sentence = \"i am tired\", searchWord = \"you\"\nOutput: -1\nExplanation: \"you\" is not a prefix of any word in the sentence.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= sentence.length &lt;= 100\n\t1 &lt;= searchWord.length &lt;= 10\n\tsentence consists of lowercase English letters and spaces.\n\tsearchWord consists of lowercase English letters.\n\n",877        "solution_py": "class Solution(object):\n    def isPrefixOfWord(self, sentence, searchWord):\n        \"\"\"\n        :type sentence: str\n        :type searchWord: str\n        :rtype: int\n        \"\"\"\n        word_list = sentence.split()\n        counter = 0\n        for word in sentence.split():\n            counter+=1\n            if searchWord == word[0:len(searchWord)]:\n                return counter\n        return -1",878        "solution_js": "var isPrefixOfWord = function(sentence, searchWord) {\n    let arr = sentence.split(' ');\n    \n    for (let i = 0; i < arr.length; i++) {\n        let word = arr[i];\n        \n        if (word.startsWith(searchWord)) return i + 1;\n    }\n    \n    return -1;\n};",879        "solution_java": "class Solution {\n    public int isPrefixOfWord(String sentence, String searchWord) {\n        if(!sentence.contains(searchWord))\n            return -1;\n        boolean y=false;\n        String[] str=sentence.split(\" \");\n\n        for(int i=0;i<str.length;i++){\n            if(str[i].contains(searchWord)){\n                for(int j=0;j<searchWord.length();j++){\n                    if(str[i].charAt(j)!=searchWord.charAt(j)){\n                        y=true;\n                        break;\n                    }\n\n                }\n                 if(!y){\n                     return i+1;\n                 }\n            }\n            y=false;\n        }\n\n        return -1;\n    }\n}",880        "solution_c": "class Solution {\npublic:\n    int isPrefixOfWord(string s, string sw) {\n    stringstream ss(s);\n    string temp;\n    int i=1;\n        while(ss>>temp) {\n            if(temp.compare(0, sw.size(),sw)==0) return i;\n            i++;\n        }\n        return -1;\n    }\n};"881    },882    {883        "title": "Moving Stones Until Consecutive",884        "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 &lt; y &lt; z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x &lt; k &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= a, b, c &lt;= 100\n\ta, b, and c have different values.\n\n",885        "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]",886        "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};",887        "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}",888        "solution_c": "class Solution {\npublic:\n\n    vector<int> numMovesStones(int a, int b, int c) {\n\n        vector<int> 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};"889    },890    {891        "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target",892        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t-104 &lt;= nums[i] &lt;= 104\n\t0 &lt;= target &lt;= 106\n\n",893        "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",894        "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};",895        "solution_java": "class Solution {\n    public int maxNonOverlapping(int[] nums, int target) {\n        Map<Integer, Integer> 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}",896        "solution_c": "class Solution {\npublic:\n    unordered_map<int,int> mpp ;\n    int maxNonOverlapping(vector<int>& 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};"897    },898    {899        "title": "Maximum Building Height",900        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= n &lt;= 109\n\t0 &lt;= restrictions.length &lt;= min(n - 1, 105)\n\t2 &lt;= idi &lt;= n\n\tidi&nbsp;is unique.\n\t0 &lt;= maxHeighti &lt;= 109\n\n",901        "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",902        "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<restrictions.length;i++){\n        restrictions[i][1] = Math.min(restrictions[i][1], (restrictions[i][0]-restrictions[i-1][0])+restrictions[i-1][1]);\n    }\n    //Propogate from right to left to tighten the restriction: Check building restriction can be furhter tightened due to the right side building restriction.\n    for(let i=restrictions.length-2;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<restrictions.length-1;i++){\n        let leftHeight = restrictions[i][1];\n        let rightHeight = restrictions[i+1][1];\n        let distance = restrictions[i+1][0]-restrictions[i][0]-1;//Number of cities between ith and i+1th city, excluding these cities\n        let hightDiff = Math.abs(restrictions[i+1][1]-restrictions[i][1]);\n        let middleHeight = Math.max(leftHeight,rightHeight)+Math.ceil((distance-hightDiff)/2);\n        max = Math.max(max,middleHeight);\n    }\n    return max;\n};",903        "solution_java": "class Solution {\n    public int maxBuilding(int n, int[][] restrictions) {\n        List<int[]> 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<list.size();i++){\n           list.get(i)[1]=Math.min(list.get(i)[1],list.get(i-1)[1] + list.get(i)[0]-list.get(i-1)[0]);\n       }\n\n       for(int i=list.size()-2;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<list.size();i++){\n           int h1=list.get(i-1)[1]; // heigth of previous restriction\n           int h2=list.get(i)[1]; // height of current restriction\n           int x=list.get(i-1)[0]; // id of previous restriction\n           int y=list.get(i)[0]; // id of current restriction\n\n          result=Math.max(result,Math.max(h1,h2) + (y-x-Math.abs(h1-h2))/2);\n       }\n        return result;\n    }\n\n    public class IDSorter implements Comparator<int[]>{\n        @Override\n        public int compare(int[] myself,int[] other){\n            return myself[0]-other[0];\n        }\n    }\n}",904        "solution_c": "class Solution {\npublic:\n    int maxBuilding(int n, vector<vector<int>>& 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};"905    },906    {907        "title": "Find Winner on a Tic Tac Toe Game",908        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= moves.length &lt;= 9\n\tmoves[i].length == 2\n\t0 &lt;= rowi, coli &lt;= 2\n\tThere are no repeated elements on moves.\n\tmoves follow the rules of tic tac toe.\n\n",909        "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\"",910        "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};",911        "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}",912        "solution_c": "class Solution {\npublic:\n    string tictactoe(vector<vector<int>>& moves)\n    {\n        vector<vector<char>> grid(3,vector<char>(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."913    },914    {915        "title": "Minimum Time to Finish the Race",916        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= tires.length &lt;= 105\n\ttires[i].length == 2\n\t1 &lt;= fi, changeTime &lt;= 105\n\t2 &lt;= ri &lt;= 105\n\t1 &lt;= numLaps &lt;= 1000\n\n",917        "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)",918        "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};",919        "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}",920        "solution_c": "class Solution {\npublic:\n    int minimumFinishTime(vector<vector<int>>& 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<vector<int>> without_change(n, vector<int>(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<int> 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};"921    },922    {923        "title": "Validate Binary Tree Nodes",924        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tn == leftChild.length == rightChild.length\n\t1 &lt;= n &lt;= 104\n\t-1 &lt;= leftChild[i], rightChild[i] &lt;= n - 1\n\n",925        "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",926        "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;};",927        "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}",928        "solution_c": "class Solution {\npublic:\n    int find_parent(vector<int>&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<int>& leftChild, vector<int>& rightChild) {\n        vector<int> parent(n);\n        for(int i=0;i<n;i++){\n            parent[i]=i;\n        }\n        int cnt=0;\n        for(int i=0;i<n;i++){\n            int y=find_parent(parent,i);\n            if(leftChild[i]!=-1){\n                int x=find_parent(parent,leftChild[i]);\n                if(x!=leftChild[i]||y==x)\n                return false;\n                parent[leftChild[i]]=y;\n            }\n            if(rightChild[i]!=-1){\n                int x=find_parent(parent,rightChild[i]);\n                if(x!=rightChild[i]||y==x)\n                return false;\n                parent[rightChild[i]]=y;\n            }\n        }\n        int x=find_parent(parent,0);\n        for(int i=1;i<n;i++){\n            if(find_parent(parent,i)!=x)\n            return false;\n        }\n        return true;\n    }\n};"929    },930    {931        "title": "Reduction Operations to Make the Array Elements Equal",932        "algo_input": "Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:\n\n\n\tFind the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.\n\tFind the next largest value in nums strictly smaller than largest. Let its value be nextLargest.\n\tReduce nums[i] to nextLargest.\n\n\nReturn the number of operations to make all elements in nums equal.\n\n&nbsp;\nExample 1:\n\nInput: nums = [5,1,3]\nOutput: 3\nExplanation:&nbsp;It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].\n\n\nExample 2:\n\nInput: nums = [1,1,1]\nOutput: 0\nExplanation:&nbsp;All elements in nums are already equal.\n\n\nExample 3:\n\nInput: nums = [1,1,2,2,3]\nOutput: 4\nExplanation:&nbsp;It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 5 * 104\n\t1 &lt;= nums[i] &lt;= 5 * 104\n\n",933        "solution_py": "class Solution:\n    def reductionOperations(self, nums: List[int]) -> int:\n        return sum(accumulate(c for _,c in sorted(Counter(nums).items(), reverse=True)[:-1]))",934        "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};",935        "solution_java": "class Solution {\n    public int reductionOperations(int[] nums) {\n        Map<Integer, Integer> valMap = new TreeMap<>(Collections.reverseOrder());\n\n        for (int i=0; i<nums.length; i++)\n            valMap.put(nums[i], valMap.getOrDefault(nums[i], 0) + 1);\n\n        int mapSize = valMap.size();\n        int opsCount = 0;\n        for (Map.Entry<Integer, Integer> entry : valMap.entrySet()) {\n            opsCount += entry.getValue() * (--mapSize);\n        }\n        return opsCount;\n    }\n}",936        "solution_c": "class Solution {\npublic:\n    int reductionOperations(vector<int>& nums) {\n        int n = nums.size();\n        \n        map<int, int> 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};"937    },938    {939        "title": "Minimum Number of K Consecutive Bit Flips",940        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 105\n\t1 &lt;= k &lt;= nums.length\n\n",941        "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)",942        "solution_js": "var minKBitFlips = function(nums, k) {\n    let count = 0\n    \n    for(let i=0; i<nums.length; i++){\n        if (nums[i] == 0){\n            for(let j=0; j<k && i+k <= nums.length; j++){\n                nums[i+j] = 1 - nums[i+j]\n            }\n            count++\n        }\n    }\n        \n    return nums.every(n => n ==1) ? count : -1\n};",943        "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 (i<nums.length-k+1&&nums[i]==target){\n                target^=1;\n                flip[i+k]^=true;\n                ans++;\n            }\n            if (i>nums.length-k&&nums[i]==target){\n                return -1;\n            }\n        }\n        return ans;\n    }\n}",944        "solution_c": "class Solution {\npublic:\n    int minKBitFlips(vector<int>& nums, int k) {\n        \n        int n = nums.size();\n        \n        int flips = 0;                  // flips on current positions\n        vector<int> 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;i++){\n            \n            flips +=flip[i];            // update flips for current position\n                                       \n            // even flips on 1 okay\n            if(nums[i]==1 && (flips)%2==0){\n                continue;\n            }\n            \n            // odd flips on 0 okay\n            \n            if(nums[i]==0 && (flips)%2!=0){\n                continue;\n            }\n            \n            // margin error as k bits flips is must\n            \n            if(i+k > 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};"945    },946    {947        "title": "Find Median from Data Stream",948        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t-105 &lt;= num &lt;= 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&nbsp;\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",949        "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]",950        "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 */",951        "solution_java": "class MedianFinder {\n\n    PriorityQueue maxHeap;\n    PriorityQueue minHeap;\n\n    public MedianFinder() {\n        maxHeap= new PriorityQueue<Integer>((a,b)->b-a);\n        minHeap= new PriorityQueue<Integer>();\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}",952        "solution_c": "class MedianFinder {\npublic:\n    /* Implemented @StefanPochmann's Incridible Idea */\n    priority_queue<long long> 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};"953    },954    {955        "title": "Reformat Date",956        "algo_input": "Given a date string in the form&nbsp;Day Month Year, where:\n\n\n\tDay&nbsp;is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"}.\n\tMonth&nbsp;is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"}.\n\tYear&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe given dates are guaranteed to be valid, so no error handling is necessary.\n\n",957        "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)",958        "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};",959        "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}",960        "solution_c": "class Solution {\npublic:\n    string reformatDate(string date) {\n        map<string,int>m;\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<date.length(); i++){\n            ans+=date[i];\n        }\n        ans += \"-\";\n        string month;\n        for(int i=date.length()-8; i<=date.length()-6; i++){\n            month+=date[i];\n        }\n\n        int yes = m[month];\n\n        if(yes<=9){\n            ans += '0';\n        }\n        ans = ans + to_string(yes);\n        ans += \"-\";\n        int i = 0;\n        if(date[1]=='t' || date[1]=='s' || date[1]=='n' || date[1]=='r'){\n            ans+='0';\n            ans+=date[0];\n        }\n        else{\n            ans+=date[0];\n            ans+=date[1];\n        }\n        return ans;\n    }\n};"961    },962    {963        "title": "Count Lattice Points Inside a Circle",964        "algo_input": "Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle.\n\nNote:\n\n\n\tA lattice point is a point with integer coordinates.\n\tPoints that lie on the circumference of a circle are also considered to be inside it.\n\n\n&nbsp;\nExample 1:\n\nInput: circles = [[2,2,1]]\nOutput: 5\nExplanation:\nThe figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.\n\nExample 2:\n\nInput: circles = [[2,2,2],[3,4,1]]\nOutput: 16\nExplanation:\nThe figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= circles.length &lt;= 200\n\tcircles[i].length == 3\n\t1 &lt;= xi, yi &lt;= 100\n\t1 &lt;= ri &lt;= min(xi, yi)\n\n",965        "solution_py": "class Solution:\n    def countLatticePoints(self, c: List[List[int]]) -> 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)",966        "solution_js": "var countLatticePoints = function(circles) {\n    let minX=minY=Infinity, maxX=maxY=-Infinity;\n    for(let i=0; i<circles.length; i++){\n        minX=Math.min(minX, circles[i][0]-circles[i][2]); maxX=Math.max(maxX, circles[i][0]+circles[i][2]);\n        minY=Math.min(minY, circles[i][1]-circles[i][2]); maxY=Math.max(maxY, circles[i][1]+circles[i][2]);\n    }\n\t\n    let count=0;\n    for(let i=minX; i<=maxX; i++){\n        for(let j=minY; j<=maxY; j++){\n            let find=false;\n            for(let k=0; k<circles.length; k++){\n                if(((i-circles[k][0])**2+(j-circles[k][1])**2)<=circles[k][2]**2){\n                    find=true; break;\n                }\n            }\n            if(find){count++};\n        }\n    }\n    return count;\n};",967        "solution_java": "class Solution {\n    public int countLatticePoints(int[][] circles) {\n        Set<String> answer = new HashSet<String>();\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}",968        "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<vector<int>>& circles) {\n        int n = circles.size() , ans = 0 ;\n        set<pair<int,int>> 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<int,int> p(i,j) ;\n                        set.insert(p) ;\n                    }\n        }\n        return set.size() ;\n    }\n};"969    },970    {971        "title": "Distribute Candies to People",972        "algo_input": "We distribute some&nbsp;number of candies, to a row of n =&nbsp;num_people&nbsp;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&nbsp;candies to the last person.\n\nThen, we go back to the start of the row, giving n&nbsp;+ 1 candies to the first person, n&nbsp;+ 2 candies to the second person, and so on until we give 2 * n&nbsp;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.&nbsp; 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&nbsp;and sum candies) that represents the final distribution of candies.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= candies &lt;= 10^9\n\t1 &lt;= num_people &lt;= 1000\n\n",973        "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()",974        "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};",975        "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<n;i++){\n                if(candies>=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}",976        "solution_c": "class Solution {\npublic:\n    vector<int> distributeCandies(int candies, int num_people) {\n        vector<int> 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};"977    },978    {979        "title": "Maximize Score After N Operations",980        "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&nbsp;\nExample 1:\n\nInput: nums = [1,2]\nOutput: 1\nExplanation:&nbsp;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:&nbsp;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:&nbsp;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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 7\n\tnums.length == 2 * n\n\t1 &lt;= nums[i] &lt;= 106\n\n",981        "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<<i)) and not(mask &(1<<j)):\n                        res = max(res, k*gcd(nums[i], nums[j])+dfs(mask|(1<<i)|(1<<j), k+1))\n            return res\n        return dfs(0, 1)",982        "solution_js": "var maxScore = function(nums) {\n    \n    function gcd(a, b) {\n        if(!b) return a;\n        return gcd(b, a % b);\n    }\n    \n    const memo = new Map();\n    \n    function recurse(arr, num1, op) {\n        if(!arr.length) return 0;\n        \n        const key = arr.join() + num1;\n        if(memo.has(key)) return memo.get(key);\n        \n        let max = 0;\n        \n        for(let i = 0; i < arr.length; i++) {\n            const nextArr = [...arr.slice(0, i), ...arr.slice(i+1)];\n            \n            if(num1) {\n                const currGCD = gcd(num1, arr[i]);\n                const rest = recurse(nextArr, null, op+1);\n                max = Math.max(max, ((op * currGCD) + rest));\n            } else {\n                const rest = recurse(nextArr, arr[i], op);\n                max = Math.max(max, rest);\n            }\n        }\n        memo.set(key, max);\n        return max;\n    }\n    return recurse(nums, null, 1);\n};",983        "solution_java": "class Solution {\n    public int maxScore(int[] nums) {\n        int n = nums.length;\n        Map<Integer, Integer> 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)",984        "solution_c": "int dp[16384];\nint gcd_table[14][14];\n\nclass Solution {\npublic:\n    int maxScore(vector<int>& 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<<sz)-1\n        dp[0] = 0;\n        for (int s = 0; s < (1<<sz); ++s) {\n            int cnt = __builtin_popcount(s);\n            if (cnt &1 )continue; // bitcount can't be odd\n            for (int i = 0; i < sz; ++i) {\n                if (s & (1<<i)) continue;\n                for (int j = i+1; j < sz; ++j) {\n                    if (s & (1<<j)) continue;\n                    int next_state = s^(1<<i)^(1<<j);\n                    dp[next_state] = max(dp[next_state], dp[s] + (cnt/2+1)*gcd_table[i][j]);\n                }\n            }\n        }\n        return dp[(1<<sz)-1];\n    }\n};"985    },986    {987        "title": "Make Array Zero by Subtracting Equal Amounts",988        "algo_input": "You are given a non-negative integer array nums. In one operation, you must:\n\n\n\tChoose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.\n\tSubtract x from every positive element in nums.\n\n\nReturn the minimum number of operations to make every element in nums equal to 0.\n\n&nbsp;\nExample 1:\n\nInput: nums = [1,5,0,3,5]\nOutput: 3\nExplanation:\nIn the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].\n\n\nExample 2:\n\nInput: nums = [0]\nOutput: 0\nExplanation: Each element in nums is already 0 so no operations are needed.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 100\n\t0 &lt;= nums[i] &lt;= 100\n\n",989        "solution_py": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        return len(set(nums) - {0})",990        "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};",991        "solution_java": "class Solution {\n    public int minimumOperations(int[] nums) {\n        Set<Integer> 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}",992        "solution_c": "class Solution {\npublic:\n    int minimumOperations(vector<int>& nums) {\n        priority_queue <int, vector<int>, greater<int> > pq;\n        \n        for(int i=0;i<nums.size();i++)\n            pq.push(nums[i]);\n        \n        int curr_min=0;\n        int count=0;\n        \n        while(!pq.empty()){\n            if(pq.top()==0)pq.pop();\n            else{\n                int top=pq.top()-curr_min;\n                if(top!=0){\n                    curr_min+=top;\n                    count++;\n                }\n                pq.pop();\n            }\n        }\n        return count;\n    }\n};"993    },994    {995        "title": "Multiply Strings",996        "algo_input": "Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.\n\nNote:&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.\n\n&nbsp;\nExample 1:\nInput: num1 = \"2\", num2 = \"3\"\nOutput: \"6\"\nExample 2:\nInput: num1 = \"123\", num2 = \"456\"\nOutput: \"56088\"\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= num1.length, num2.length &lt;= 200\n\tnum1 and num2 consist of digits only.\n\tBoth num1 and num2&nbsp;do not contain any leading zero, except the number 0 itself.\n\n",997        "solution_py": "class Solution:\n    def multiply(self, num1: str, num2: str) -> 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      ",998        "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};",999        "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}",1000        "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};"1001    },1002    {1003        "title": "Best Sightseeing Pair",1004        "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 &lt; 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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= values.length &lt;= 5 * 104\n\t1 &lt;= values[i] &lt;= 1000\n\n",1005        "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",1006        "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<curIndexMaxValue){\n            maxValue=curIndexMaxValue;\n        }\n        prevIndexMaxAddition=curIndexMaxAddition;\n    }\n    return maxValue;\n};",1007        "solution_java": "class Solution {\n    public int maxScoreSightseeingPair(int[] values) {\n        int n=values.length;\n        int[] dp=new int[n];\n        dp[0]=values[0];\n        int ans=0;\n        for(int i=1;i<n;i++){\n            dp[i]=Math.max(dp[i-1],values[i]+i);\n            ans=Math.max(ans,dp[i-1]+values[i]-i);\n        }\n        return ans;\n    }\n}",1008        "solution_c": "class Solution {\npublic:\n    int maxScoreSightseeingPair(vector<int>& values) {\n        int ans=-1e9;\n        int maxSum=values[0];\n        int n=values.size();\n        for(int i=1;i<n;i++){\n            ans=max(ans,maxSum+values[i]-i);\n            maxSum=max(maxSum,values[i]+i);\n        }\n        return ans;\n\n    }\n};"1009    },1010    {1011        "title": "Rectangle Overlap",1012        "algo_input": "An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.\n\nTwo rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.\n\nGiven two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.\n\n&nbsp;\nExample 1:\nInput: rec1 = [0,0,2,2], rec2 = [1,1,3,3]\nOutput: true\nExample 2:\nInput: rec1 = [0,0,1,1], rec2 = [1,0,2,1]\nOutput: false\nExample 3:\nInput: rec1 = [0,0,1,1], rec2 = [2,2,3,3]\nOutput: false\n\n&nbsp;\nConstraints:\n\n\n\trec1.length == 4\n\trec2.length == 4\n\t-109 &lt;= rec1[i], rec2[i] &lt;= 109\n\trec1 and rec2 represent a valid rectangle with a non-zero area.\n\n",1013        "solution_py": "class Solution:\n    def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> 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",1014        "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};",1015        "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}",1016        "solution_c": "class Solution {\npublic:\n    bool isRectangleOverlap(vector<int>& rec1, vector<int>& 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<x6 && y5<y6){\n            return true;\n        }\n        else{\n            return false;\n        }\n\n    }\n};"1017    },1018    {1019        "title": "Splitting a String Into Descending Consecutive Values",1020        "algo_input": "You are given a string s that consists of only digits.\n\nCheck if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.\n\n\n\tFor example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.\n\tAnother example, the string s = \"001\" can be split into [\"0\", \"01\"], [\"00\", \"1\"], or [\"0\", \"0\", \"1\"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.\n\n\nReturn true if it is possible to split sโ€‹โ€‹โ€‹โ€‹โ€‹โ€‹ as described above, or false otherwise.\n\nA substring is a contiguous sequence of characters in a string.\n\n&nbsp;\nExample 1:\n\nInput: s = \"1234\"\nOutput: false\nExplanation: There is no valid way to split s.\n\n\nExample 2:\n\nInput: s = \"050043\"\nOutput: true\nExplanation: s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.\n\n\nExample 3:\n\nInput: s = \"9080701\"\nOutput: false\nExplanation: There is no valid way to split s.\n\n\n&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 20\n\ts only consists of digits.\n\n",1021        "solution_py": "class Solution:\n    def splitString(self, s: str, last_val: int = None) -> 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",1022        "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};",1023        "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<s.length();i++) {\n            current = current * 10 + s.charAt(i)-'0';\n            if(current >= 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}",1024        "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};"1025    },1026    {1027        "title": "Transpose Matrix",1028        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == matrix.length\n\tn == matrix[i].length\n\t1 &lt;= m, n &lt;= 1000\n\t1 &lt;= m * n &lt;= 105\n\t-109 &lt;= matrix[i][j] &lt;= 109\n\n",1029        "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",1030        "solution_js": "var transpose = function(matrix){\n    let result = []\n    for(let i=0;i<matrix[0].length;i++){\n\n        let col = []\n\n        for(let j= 0;j<matrix.length;j++){\n            col.push(matrix[j][i])\n        }\n        result.push(col)\n    }\n    return result\n};\n\n    console.log(transpose( [ [1 , 2 , 3] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ) )",1031        "solution_java": "class Solution {\n    public int[][] transpose(int[][] matrix) {\n        int m = matrix.length;\n        int n = matrix[0].length;\n\n        int[][] trans = new int[n][m];\n\n        for(int i = 0; i < n; i++) {\n            for(int j = 0; j < m; j++) {\n                trans[i][j] = matrix[j][i];\n            }\n        }\n\n        return trans;\n    }\n}",1032        "solution_c": "class Solution {\npublic:\n    vector<vector<int>> transpose(vector<vector<int>>& matrix) {\n        \n        vector<vector<int>>result;\n        map<int,vector<int>>m;\n        \n        for(int i=0;i<matrix.size();i++){\n            vector<int>v = matrix[i];\n            for(int j=0;j<v.size();j++){\n                m[j].push_back(v[j]);\n            }\n        }\n        \n        for(auto i:m){\n            result.push_back(i.second);\n        }\n        return result;\n    }\n};"1033    },1034    {1035        "title": "Delete Node in a Linked List",1036        "algo_input": "Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.\n\nIt is guaranteed that the node to be deleted is not a tail node in the list.\n\n&nbsp;\nExample 1:\n\nInput: head = [4,5,1,9], node = 5\nOutput: [4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function.\n\n\nExample 2:\n\nInput: head = [4,5,1,9], node = 1\nOutput: [4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function.\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of the nodes in the given list is in the range [2, 1000].\n\t-1000 &lt;= Node.val &lt;= 1000\n\tThe value of each node in the list is unique.\n\tThe node to be deleted is in the list and is not a tail node\n\n",1037        "solution_py": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n    def deleteNode(self, node):\n        \"\"\"\n        :type node: ListNode\n        :rtype: void Do not return anything, modify node in-place instead.\n        \"\"\"\n        node.val = node.next.val\n        node.next = node.next.next",1038        "solution_js": "var deleteNode = function(node) {\n    let nextNode = node.next;\n    node.val = nextNode.val;\n    node.next = nextNode.next;\n};",1039        "solution_java": "class Solution {\n    public void deleteNode(ListNode node) {\n\n        // 4 5 1 9 : Node = 5\n\n        node.val = node.next.val;\n\n        //Copy next node val to current node.\n        //4 1 1 9\n        // ------------\n\n        //Point node.next = node.next.next\n        // 4 -----> 1 ----> 9\n\n        node.next = node.next.next;\n        // 4 1 9\n    }\n}",1040        "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};"1041    },1042    {1043        "title": "Flatten a Multilevel Doubly Linked List",1044        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tThe number of Nodes will not exceed 1000.\n\t1 &lt;= Node.val &lt;= 105\n\n\n&nbsp;\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",1045        "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)",1046        "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};",1047        "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<Node> 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}",1048        "solution_c": "class Solution {\npublic:\n    Node* flatten(Node* head)\n    {\n        if(head==NULL) return head;\n       Node *temp=head;\n       stack<Node*> 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"1049    },1050    {1051        "title": "Lucky Numbers in a Matrix",1052        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == mat.length\n\tn == mat[i].length\n\t1 &lt;= n, m &lt;= 50\n\t1 &lt;= matrix[i][j] &lt;= 105.\n\tAll elements in the matrix are distinct.\n\n",1053        "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))",1054        "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};",1055        "solution_java": "class Solution {\n    public List<Integer> luckyNumbers (int[][] matrix) {\n        List<Integer> 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}",1056        "solution_c": "class Solution {\npublic:\n    vector<int> luckyNumbers (vector<vector<int>>& matrix) {\n\n        unordered_map<int,vector<int>>m;\n\n        for(int i=0;i<matrix.size();i++){\n            vector<int>temp = matrix[i];\n            for(int j=0;j<temp.size();j++){\n                m[j].push_back(temp[j]);\n            }\n        }\n\n        unordered_map<int,int>mp;\n        for(int i=0;i<matrix.size();i++){\n            vector<int>helper = matrix[i];\n\n            sort(helper.begin(),helper.end());\n\n            mp[helper[0]]++;\n        }\n        vector<int>result;\n        for(auto i:m){\n            vector<int>helper = 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};"1057    },1058    {1059        "title": "Bricks Falling When Hit",1060        "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&nbsp;(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&nbsp;\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&nbsp;\nConstraints:\n\n\n\tm == grid.length\n\tn == grid[i].length\n\t1 &lt;= m, n &lt;= 200\n\tgrid[i][j] is 0 or 1.\n\t1 &lt;= hits.length &lt;= 4 * 104\n\thits[i].length == 2\n\t0 &lt;= xi&nbsp;&lt;= m - 1\n\t0 &lt;=&nbsp;yi &lt;= n - 1\n\tAll (xi, yi) are unique.\n\n",1061        "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",1062        "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[0].length; j++) {\n                if (grid[0][j] == 1) {\n                    dfs (grid, output, map, 0, j);\n                    break;\n                }\n            }\n            /* removing bricks that are not connected and adding the count to array */\n            removeBricks(grid, map, output);  \n        } else {\n            output.push(0)\n        }\n        \n        \n    }\n    return output;\n};\n\nfunction dfs(grid, output, map, i, j) {\n    \n    if (i >= 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}",1063        "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<hits.length;i++)\n            if(grid[hits[i][0]][hits[i][1]] == 1)\n                grid[hits[i][0]][hits[i][1]] = -1;\n        \n        //marking all the stable bricks\n        for(int i=0;i<grid[0].length;i++)\n            markAndCountStableBricks(grid, 0, i);\n        \n        int[] res = new int[hits.length];\n        //looping over hits array backwards and restoring bricks\n        for(int i=hits.length-1;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}",1064        "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<vector<bool>>& 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<vis.size()-1 && vis[i+1][j])\n            return true;\n        if(j<vis[0].size()-1 && vis[i][j+1])\n            return true;\n        \n        return false;\n    }\n    \n    vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {\n        vector<int> ans(hits.size(), 0);\n        \n\t\t//Remove all the bricks which are hit during entire process\n        vector<vector<int>> mat = grid;\n        for(int i=0; i<hits.size(); i++)\n            mat[hits[i][0]][hits[i][1]] = 0;\n        \n\t\t//Do BFS to determine connected nodes (to top of matrix) and mark them as visited\n        vector<vector<bool>> vis(grid.size(), vector<bool> (grid[0].size(), false));\n        queue<pair<int, int>> q;\n        for(int i=0; i<grid[0].size(); i++){\n            if(mat[0][i]==1){\n                vis[0][i] = true;\n                q.push({0, i});\n            }\n        }\n        while(!q.empty()){\n            int idx = q.front().first, jdx = q.front().second;\n            q.pop();\n            \n            if(idx>0 && 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<grid.size()-1 && 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<grid[0].size()-1 && 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        }\n        \n        //Traverse the hits array in reverse order to one by one add a brick \n        for(int i=hits.size()-1; i>=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<grid.size()-1 && 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<grid[0].size()-1 && mat[idx][jdx+1]==1 && !vis[idx][jdx+1]){\n                    q.push({idx, jdx+1});\n                    vis[idx][jdx+1]=true;\n                }\n            }\n            ans[i] = cnt-1;\n        }\n        return ans;\n    }\n};"1065    },1066    {1067        "title": "Validate IP Address",1068        "algo_input": "Given a string queryIP, return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type.\n\nA valid IPv4 address is an IP in the form \"x1.x2.x3.x4\" where 0 &lt;= xi &lt;= 255 and xi cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\", \"192.168.1.00\", and \"192.168@1.1\" are invalid IPv4 addresses.\n\nA valid IPv6 address is an IP in the form \"x1:x2:x3:x4:x5:x6:x7:x8\" where:\n\n\n\t1 &lt;= xi.length &lt;= 4\n\txi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F').\n\tLeading zeros are allowed in xi.\n\n\nFor example, \"2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \"2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \"2001:0db8:85a3::8A2E:037j:7334\" and \"02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses.\n\n&nbsp;\nExample 1:\n\nInput: queryIP = \"172.16.254.1\"\nOutput: \"IPv4\"\nExplanation: This is a valid IPv4 address, return \"IPv4\".\n\n\nExample 2:\n\nInput: queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\nOutput: \"IPv6\"\nExplanation: This is a valid IPv6 address, return \"IPv6\".\n\n\nExample 3:\n\nInput: queryIP = \"256.256.256.256\"\nOutput: \"Neither\"\nExplanation: This is neither a IPv4 address nor a IPv6 address.\n\n\n&nbsp;\nConstraints:\n\n\n\tqueryIP consists only of English letters, digits and the characters '.' and ':'.\n\n",1069        "solution_py": "class Solution:\n    def validIPAddress(self, queryIP: str) -> 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        ",1070        "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};",1071        "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}",1072        "solution_c": "class Solution {\npublic:\n    bool checkforIPv6(string IP){\n        int n = IP.size();\n        vector<string>store;\n        string s = \"\";\n        for(int i=0; i<n; i++){\n            if(IP[i] == ':'){\n                store.push_back(s);\n                s = \"\";\n            }\n            else{\n                s+=IP[i];\n            }\n        }\n        store.push_back(s);\n        if(store.size() != 8){\n            return false;\n        }\n        for(int i=0; i<store.size(); i++){\n            string s = store[i];\n            if(s.size() > 4 or s.size() == 0){\n                return false;\n            }\n            for(int j=0; j<s.size(); j++){\n                if(s[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        vector<string>store;\n        string s = \"\";\n        for(int i=0; i<n; i++){\n            if(IP[i] == '.'){\n                store.push_back(s);\n                s = \"\";\n            }\n            else{\n                s+=IP[i];\n            }\n        }\n        store.push_back(s);\n        if(store.size() != 4){\n            return false;\n        }\n        for(int i=0; i<store.size(); i++){\n            string s = store[i];\n            if(s.size() > 3 or s.size() == 0){\n                return false;\n            }\n            int num = 0;\n            for(int j=0; j<s.size(); j++){\n                if(s.size() >= 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};"1073    },1074    {1075        "title": "Minimum Moves to Equal Array Elements II",1076        "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&nbsp;\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]  =&gt;  [2,2,3]  =&gt;  [2,2,2]\n\n\nExample 2:\n\nInput: nums = [1,10,2,9]\nOutput: 16\n\n\n&nbsp;\nConstraints:\n\n\n\tn == nums.length\n\t1 &lt;= nums.length &lt;= 105\n\t-109 &lt;= nums[i] &lt;= 109\n\n",1077        "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        ",1078        "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};",1079        "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.length;i++){\n            sum+=Math.abs(nums[i]-nums[idx]);\n        }\n        return sum;\n    }\n}",1080        "solution_c": "class Solution {\npublic:\n    int minMoves2(vector<int>& 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};"1081    },1082    {1083        "title": "Longest ZigZag Path in a Binary Tree",1084        "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&nbsp;\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 -&gt; left -&gt; 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 -&gt; right -&gt; left -&gt; right).\n\n\nExample 3:\n\nInput: root = [1]\nOutput: 0\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [1, 5 * 104].\n\t1 &lt;= Node.val &lt;= 100\n\n",1085        "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",1086        "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};",1087        "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}",1088        "solution_c": "class Solution {\n    typedef long long ll;\n    typedef pair<ll, ll> 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};"1089    },1090    {1091        "title": "Rearrange Array Elements by Sign",1092        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t2 &lt;= nums.length &lt;= 2 * 105\n\tnums.length is even\n\t1 &lt;= |nums[i]| &lt;= 105\n\tnums consists of equal number of positive and negative integers.\n\n",1093        "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]",1094        "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;i<nums.length;i++) {\n       if(nums[i]>0) {\n           result[posIdx] = nums[i]\n           posIdx +=2;\n       } else {\n            result[negIdx] = nums[i]\n           negIdx +=2;\n       }\n   }\n    return result;\n };",1095        "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<nums.length;i++){\n            if(i % 2 == 0){\n                posIdx++;\n                while(nums[posIdx] <0 )posIdx++;\n                res[resIdx++] = nums[posIdx];\n            }\n            else{\n                minusIdx++;\n                while(nums[minusIdx] > 0 )minusIdx++;\n                res[resIdx++] = nums[minusIdx];\n            }\n        }\n\n        return res;\n    }\n}",1096        "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<int> rearrangeArray(vector<int>& 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<nums.size() % (4 * chunk_size); ++i) {\n            nums.push_back(i % 2 == 0 ? kPadPositive : kPadNegative);\n        }\n        ENABLE_LOG(\n            cout << \"chunk_size: \" << chunk_size << endl;\n\n            cout << \"padded array: \";\n            for (int v: nums) cout << v << \" \"; cout << endl;\n        )\n        // Denotion:\n        // the i-th positive number in original array: P_i.\n        // the i-th negative number in original array: N_i\n\n        // Step 1: Sort each chunk stably so that positive numbers appear before\n        // negative numbers\n        vector<int> 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<i+chunk_size; ++j)\n                if (nums[j] > 0)\n                    chunk_buffer.push_back(nums[j]);\n            for (int j=i; j<i+chunk_size; ++j)\n                if (nums[j] < 0)\n                    chunk_buffer.push_back(nums[j]);\n            // Copy chunk_buffer back to nums[i:i+chunk_size]\n            copy_n(chunk_buffer.cbegin(), chunk_size, nums.begin() + i);\n        }\n        ENABLE_LOG(\n            cout << \"chunk-sorted array: \";\n            for (int v: nums) cout << v << \" \"; cout << endl;\n        )\n\n        // Step 2: Merge every two chunks so that each chunk are either all positive numbers\n        // or all negative numbers\n        //\n        // This is based on the observation that:\n        // assuming chunk A having m positives followed by n negatives,\n        // chunk B having p positives followed by q negatives,\n        // a) if m+p >= 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<int>{nums.begin(), nums.begin() + chunk_size};\n        for (int i = chunk_size; i<nums.size(); i+= chunk_size) {\n            const int m = find_if(chunk_buffer.cbegin(), chunk_buffer.cend(), [](int v) {\n                return v < 0;\n            }) - chunk_buffer.cbegin();\n            const int n = chunk_size - m;\n            const int p = find_if(nums.cbegin() + i, nums.cbegin() + i + chunk_size, [](int v) {\n                return v < 0;\n            }) - (nums.cbegin() + i);\n            const int q = chunk_size - p;\n\n            if (m + p >= 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<int> 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<int> 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<int> target(chunk_cnt); // O(sqrt(N))\n        int positive_chunks = 0, negative_chunks = 0;\n        for (int i=0; i<chunk_cnt; ++i) {\n            if (nums[i * chunk_size] > 0)\n                target[i] = (positive_chunks++) * 2;\n            else\n                target[i] = (negative_chunks++) * 2 + 1;\n        }\n        for (int i=0; i<chunk_cnt; ++i) {\n            while (target[i] != i) {\n                swap_ranges(nums.begin() + i * chunk_size,\n                            nums.begin() + i * chunk_size + chunk_size,\n                            nums.begin() + target[i] * chunk_size);\n                swap(target[target[i]], target[i]);\n            }\n        }\n        ENABLE_LOG(\n            cout << \"sorted array: \";\n            for (int v: nums) cout << v << \" \"; cout << endl;\n        )\n\n        // Step 4:\n        // Now we get Positive Chunk1, Negative Chunk 1, Positive Chunk 2, Negative Chunk 2, ...\n        // For each pair of adjacent (positive, negative) chunks, we can reorder the elements inside\n        // to make positive and negative numbers interleave each other\n        vector<int> two_chunk_elements_interleaved; // O(2 * chunk_size) = O(sqrt(N))\n        for (int i=0; i<nums.size(); i += 2 * chunk_size) {\n            two_chunk_elements_interleaved.clear();\n            for (int j=0; j<chunk_size; ++j)\n            {\n                two_chunk_elements_interleaved.push_back(nums[i + j]);\n                two_chunk_elements_interleaved.push_back(nums[i + chunk_size + j]);\n            }\n            copy_n(two_chunk_elements_interleaved.cbegin(), 2 * chunk_size, nums.begin() + i);\n        }\n        // Remove paddings\n        nums.resize(original_n);\n        return nums;\n\n    }\n};"1097    },1098    {1099        "title": "Sum of Square Numbers",1100        "algo_input": "Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.\n\n&nbsp;\nExample 1:\n\nInput: c = 5\nOutput: true\nExplanation: 1 * 1 + 2 * 2 = 5\n\n\nExample 2:\n\nInput: c = 3\nOutput: false\n\n\n&nbsp;\nConstraints:\n\n\n\t0 &lt;= c &lt;= 231 - 1\n\n",1101        "solution_py": "import math\n\nclass Solution:\n    def judgeSquareSum(self, c: int) -> 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",1102        "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};",1103        "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}",1104        "solution_c": "class Solution {\npublic:\n    bool judgeSquareSum(int c) {\n        long long start=0,end=0;\n        while(end*end<c){\n            end++;\n        }\n        long long target=c;\n        while(start<=end){\n            long long product=start*start+end*end;\n            if(product==target){\n                return true;\n            } else if(product>c){\n                end--;\n            } else {\n                start++;\n            }\n        }\n        return false;\n    }\n};"1105    },1106    {1107        "title": "Most Stones Removed with Same Row or Column",1108        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= stones.length &lt;= 1000\n\t0 &lt;= xi, yi &lt;= 104\n\tNo two stones are at the same coordinate point.\n\n",1109        "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)",1110        "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};",1111        "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;i<stones.length;i++) {\n            for(int j=i+1;j<stones.length;j++) {\n                int s1[]=stones[i];\n                int s2[]=stones[j];\n\n                if(s1[0]==s2[0] || s1[1]==s2[1]) {\n                    ds.union(i, j);\n                }\n            }\n        }\n        // System.out.println(Arrays.toString(ds.sets));\n        for(int i=0;i<ds.sets.length;i++) {\n            if(ds.sets[i]<0)\n                ret+=Math.abs(ds.sets[i])-1;\n        }\n\n        return ret;\n    }\n\n    class DisjointSet {\n        public int sets[];\n\n        public DisjointSet(int size) {\n            sets=new int[size];\n            Arrays.fill(sets, -1);\n        }\n\n        //\n        // weighted union\n        //union->return 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}",1112        "solution_c": "class Solution {\n    class UnionFind \n    {\n        vector<int> 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<n;i++)\n            {\n                parent[i] = i;\n            }\n        }\n        int find(int p)\n        {\n            while(p!=parent[p])\n            {\n                parent[p] = parent[parent[p]];\n                p = parent[p];\n            }\n            return p;\n        }\n        bool Union(int p, int q)\n        {\n            int rootp = find(p);\n            int rootq = find(q);\n            if(rootp == rootq)\n                return false;\n            else if(rank[rootp] < rank[rootq])\n            {\n                parent[rootp] = rootq;\n                rank[rootq]++;\n                count--;\n                return true;\n            }\n            else\n            {\n                parent[rootq] = rootp;\n                rank[rootp]++;\n                count--;\n                return true;\n            }\n        }\n    };\npublic:\n    int removeStones(vector<vector<int>>& stones) {\n        int n = stones.size();\n        UnionFind uf(n);\n        for(int i=0;i<n;i++){\n            for(int j=0;j<i;j++){\n                if(stones[i][0] == stones[j][0] or stones[i][1] == stones[j][1])\n                    uf.Union(i,j);\n            }\n        }\n\n        return n - uf.count;\n    }\n};"1113    },1114    {1115        "title": "Friends Of Appropriate Ages",1116        "algo_input": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.\n\nA Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:\n\n\n\tage[y] &lt;= 0.5 * age[x] + 7\n\tage[y] &gt; age[x]\n\tage[y] &gt; 100 &amp;&amp; age[x] &lt; 100\n\n\nOtherwise, x will send a friend request to y.\n\nNote that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.\n\nReturn the total number of friend requests made.\n\n&nbsp;\nExample 1:\n\nInput: ages = [16,16]\nOutput: 2\nExplanation: 2 people friend request each other.\n\n\nExample 2:\n\nInput: ages = [16,17,18]\nOutput: 2\nExplanation: Friend requests are made 17 -&gt; 16, 18 -&gt; 17.\n\n\nExample 3:\n\nInput: ages = [20,30,100,110,120]\nOutput: 3\nExplanation: Friend requests are made 110 -&gt; 100, 120 -&gt; 110, 120 -&gt; 100.\n\n\n&nbsp;\nConstraints:\n\n\n\tn == ages.length\n\t1 &lt;= n &lt;= 2 * 104\n\t1 &lt;= ages[i] &lt;= 120\n\n",1117        "solution_py": "class Solution:\n    \"\"\"\n    approach:\n    we can try solving this problem by finding the valid age group for each age\n    sort the array in descending order\n    iterate from right to left\n    for current age, find the valid agegroup to which the current age person will send a request\n    we can use binary search for that\n    if current age is x, then valid age group to send a request is:\n    x*0.5 + 7 < age(y) <= x\n    we can find the left limit using binary search\n    \"\"\"\n    def binary_search(self, arr, low, high, value):\n        if low > 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",1118        "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};",1119        "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}",1120        "solution_c": "class Solution {\npublic:\n    int numFriendRequests(vector<int>& 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};"1121    },1122    {1123        "title": "Rank Teams by Votes",1124        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= votes.length &lt;= 1000\n\t1 &lt;= votes[i].length &lt;= 26\n\tvotes[i].length == votes[j].length for 0 &lt;= i, j &lt; 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 &lt;= j &lt; votes.length.\n\n",1125        "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)",1126        "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};",1127        "solution_java": "class Solution {\n    public String rankTeams(String[] votes) {\n        int n = votes.length;\n        int teams = votes[0].length();\n        Map<Character, int[]> map = new HashMap<>();\n        List<Character> 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}",1128        "solution_c": "class Solution {\npublic:\n\n    static bool cmp(vector<int>a, vector<int>b){\n\n        for(int i = 1; i<a.size(); i++){\n            if(a[i]!=b[i]){\n                return a[i]>b[i];\n            }\n        }\n\n        return a[0]<b[0];\n    }\n\n    string rankTeams(vector<string>& votes) {\n\n        int noofteams = votes[0].size();\n        string ans = \"\";\n        vector<vector<int>>vec(noofteams, vector<int>(noofteams+1, 0));\n\n        unordered_map<char, int>mp;\n        for(int i = 0; i<votes[0].size(); i++){\n            mp[votes[0][i]] = i;\n            vec[i][0] = votes[0][i]-'a';\n        }\n\n        for(string x: votes){\n            for(int i = 0; i<x.size(); i++){\n                vec[mp[x[i]]][i+1]++;\n            }\n        }\n\n        sort(vec.begin(), vec.end(), cmp);\n\n        for(int i = 0; i<vec.size(); i++){\n            ans.push_back(vec[i][0]+'a');\n        }\n\n        return ans;\n    }\n};"1129    },1130    {1131        "title": "Flatten Binary Tree to Linked List",1132        "algo_input": "Given the root of a binary tree, flatten the tree into a \"linked list\":\n\n\n\tThe \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.\n\tThe \"linked list\" should be in the same order as a pre-order traversal of the binary tree.\n\n\n&nbsp;\nExample 1:\n\nInput: root = [1,2,5,3,4,null,6]\nOutput: [1,null,2,null,3,null,4,null,5,null,6]\n\n\nExample 2:\n\nInput: root = []\nOutput: []\n\n\nExample 3:\n\nInput: root = [0]\nOutput: [0]\n\n\n&nbsp;\nConstraints:\n\n\n\tThe number of nodes in the tree is in the range [0, 2000].\n\t-100 &lt;= Node.val &lt;= 100\n\n\n&nbsp;\nFollow up: Can you flatten the tree in-place (with O(1) extra space)?",1133        "solution_py": "#Call the right of the tree node till the node root left and right is not None\n#After reaching the bottom of the tree make the root.right = prev and\n#root.left = None and then prev = None\n#Initially prev will point to None but this is used to point the previously visited root node\n#Prev pointer helps us to change the values from left to right\nclass Solution:\n    def flatten(self, root: Optional[TreeNode]) -> 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).",1134        "solution_js": "/**\n * Definition for a binary tree node.\n * function TreeNode(val, left, right) {\n * this.val = (val===undefined ? 0 : val)\n * this.left = (left===undefined ? null : left)\n * this.right = (right===undefined ? null : right)\n * }\n */\n/**\n * @param {TreeNode} root\n * @return {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};",1135        "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}",1136        "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};"1137    },1138    {1139        "title": "Minimum Insertion Steps to Make a String Palindrome",1140        "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&nbsp;palindrome.\n\nA&nbsp;Palindrome String&nbsp;is one that reads the same backward as well as forward.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 500\n\ts consists of lowercase English letters.\n\n",1141        "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]",1142        "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};",1143        "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<m+1;i++){\n           for(int j=0;j<n+1;j++){\n            if(m==0||n==0){t[m][n]=0;}\n           }\n        }\n        for(int i=1;i<m+1;i++){\n            for(int j=1;j<n+1;j++){\n                if(x.charAt(i-1)==y.charAt(j-1)){\n                    t[i][j]=1+t[i-1][j-1];\n                }\n                else{t[i][j]=Math.max(t[i][j-1],t[i-1][j]);\n                }\n            }\n        }\n        return y.length()-t[m][n];\n    }\n}",1144        "solution_c": "class Solution {\npublic:\n    int t[501][501];\n    int MinInsertion(string x,int m){\n    string y=x;\n    reverse(y.begin(),y.end());\n    for(int i=0;i<m+1;i++){\n        for(int j=0;j<m+1;j++){\n            if(i==0||j==0)\n                t[i][j]=0;\n        }\n    }\n    for(int i=1;i<m+1;i++){\n        for(int j=1;j<m+1;j++){\n            if(x[i-1]==y[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    return m-t[m][m];\n}\n    int minInsertions(string s) {\n        return MinInsertion(s,s.length());\n    }\n};"1145    },1146    {1147        "title": "Rearrange Words in a Sentence",1148        "algo_input": "Given a sentence&nbsp;text (A&nbsp;sentence&nbsp;is a string of space-separated words) in the following format:\n\n\n\tFirst letter is in upper case.\n\tEach word in text are separated by a single space.\n\n\nYour task is to rearrange the words in text such that&nbsp;all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.\n\nReturn the new text&nbsp;following the format shown above.\n\n&nbsp;\nExample 1:\n\nInput: text = \"Leetcode is cool\"\nOutput: \"Is cool leetcode\"\nExplanation: There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.\n\n\nExample 2:\n\nInput: text = \"Keep calm and code on\"\nOutput: \"On and keep calm code\"\nExplanation: Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.\n\n\nExample 3:\n\nInput: text = \"To be or not to be\"\nOutput: \"To be or to be not\"\n\n\n&nbsp;\nConstraints:\n\n\n\ttext begins with a capital letter and then contains lowercase letters and single space between words.\n\t1 &lt;= text.length &lt;= 10^5\n\n",1149        "solution_py": "class Solution:\n    def arrangeWords(self, text: str) -> str:\n        l=list(text.split(\" \"))\n        l=sorted(l,key= lambda word: len(word))\n        l=' '.join(l)\n        return l.capitalize()",1150        "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};",1151        "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}",1152        "solution_c": "class Solution {\npublic:\n    vector<pair<string,int>> 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<string,int> &p1 , const pair<string,int> &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};"1153    },1154    {1155        "title": "Maximum Depth of N-ary Tree",1156        "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&nbsp;\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&nbsp;\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",1157        "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 ",1158        "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};",1159        "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}",1160        "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 ; i<root->children.size() ; i++)\n        {\n            helper(root->children[i], dep+1, mx);\n        }\n    }\n};"1161    },1162    {1163        "title": "Smallest String With A Given Numeric Value",1164        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= n &lt;= 105\n\tn &lt;= k &lt;= 26 * n\n\n",1165        "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",1166        "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};",1167        "solution_java": "class Solution {\n    public String getSmallestString(int n, int k) {\n        char[] ch = new char[n];\n        for(int i=0;i<n;i++) {\n            ch[i]='a';\n            k--;\n        }\n        int currChar=0;\n        while(k>0) {\n            currChar=Math.min(25,k);\n            ch[--n]+=currChar;\n            k-=currChar;\n        }\n        return String.valueOf(ch);\n    }\n}",1168        "solution_c": "class Solution {\npublic:\n    string getSmallestString(int n, int k) {\n        string str=\"\";\n        for(int i=0;i<n;i++){\n            str+='a';\n        }\n        int curr=n;\n        int diff=k-curr;\n        if(diff==0) return str;\n        for(int i=n-1;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// "1169    },1170    {1171        "title": "Maximum XOR of Two Numbers in an Array",1172        "algo_input": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 &lt;= i &lt;= j &lt; n.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= nums.length &lt;= 2 * 105\n\t0 &lt;= nums[i] &lt;= 231 - 1\n\n",1173        "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<<i) else 0\n\t\t\t\tcur = cur[bit]\n\t\t\tcur['val']=n\n\n\t\tans = 0\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<<i) else 0\n\t\t\t\tif bit == 1:\n\t\t\t\t\tif 0 in cur: cur = cur[0]\n\t\t\t\t\telse: cur = cur[1]\n\t\t\t\telse: \n\t\t\t\t\tif 1 in cur: cur = cur[1]\n\t\t\t\t\telse: cur = cur[0]\n\t\t\tans = max(ans,cur['val']^n)\n\n\t\treturn ans",1174        "solution_js": "var findMaximumXOR = function(nums) {\n    const trie = {};\n    const add = (num) => {\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<<i);\n                p = p[opp];\n            } else {\n                p = p[isSet];\n            }\n        }\n        return ans;\n    }\n    \n    for(let num of nums) {\n        add(num);\n    }\n    let max = 0;\n    for(let num of nums) {\n        max = Math.max(max, xor(num))\n    }\n    return max;\n};",1175        "solution_java": "class Node {\n    Node[] links = new Node[2];\n    \n    public Node () {\n        \n    }\n    \n    boolean containsKey(int ind) {\n        return links[ind] != null;\n    }\n    \n    Node get(int ind) {\n        return links[ind];\n    }\n    \n    void put(int ind, Node node) {\n        links[ind] = node;\n    }\n}\n\nclass Trie {\n    private static Node root;\n    \n    public Trie() {\n        root = new Node();\n    }\n    \n    public static void insert(int num) {\n        Node node = root;\n        for (int i = 31; i >= 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}",1176        "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<int>& 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};"1177    },1178    {1179        "title": "Valid Number",1180        "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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 20\n\ts consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.\n\n",1181        "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",1182        "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};",1183        "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}",1184        "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<s.size(); ++i){\n            if( (s[i] == '+' || s[i] == '-') && (stage == 0 || stage == 5)){ stage++; }\n            else if((s[i] == 'e' || s[i] == 'E') && stage > 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};"1185    },1186    {1187        "title": "Sort Integers by The Number of 1 Bits",1188        "algo_input": "You are given an integer array arr. Sort the integers in the array&nbsp;in ascending order by the number of 1's&nbsp;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&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= arr.length &lt;= 500\n\t0 &lt;= arr[i] &lt;= 104\n\n",1189        "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",1190        "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};",1191        "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<arr.length;i++) {\n            arrInt[i]=arr[i];\n        }\n\n        Arrays.sort(arrInt, new Comparator<Integer>() {\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<arr.length;i++) {\n            arr[i]=arrInt[i];\n        }\n        return arr;\n    }\n\n    public int numOfBits(int a) {\n        int bits=0;\n        while(a!=0) {\n            bits+=a&1;\n            a=a>>>1;\n        }\n\n        return bits;\n    }\n}",1192        "solution_c": "class Solution {\npublic:\n    vector<int> sortByBits(vector<int>& arr) {\n        int n = size(arr);\n        priority_queue<pair<int, int>> 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};"1193    },1194    {1195        "title": "Valid Palindrome II",1196        "algo_input": "Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n\n&nbsp;\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&nbsp;\nConstraints:\n\n\n\t1 &lt;= s.length &lt;= 105\n\ts consists of lowercase English letters.\n\n",1197        "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)",1198        "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}",1199        "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}",1200        "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};"

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